diff --git a/Code/Mantid/Build/CMake/DarwinSetup.cmake b/Code/Mantid/Build/CMake/DarwinSetup.cmake
index 9821a44e261db29f3f377f2ce4d3605e8630ae08..24ac3dbe55a9ff722bd08fe720c5b3dd7ea45c70 100644
--- a/Code/Mantid/Build/CMake/DarwinSetup.cmake
+++ b/Code/Mantid/Build/CMake/DarwinSetup.cmake
@@ -107,11 +107,16 @@ set ( CMAKE_INSTALL_PREFIX "" )
 set ( CPACK_PACKAGE_EXECUTABLES MantidPlot )
 set ( INBUNDLE MantidPlot.app/ )
 
-# We know exactly where this has to be on Darwin
-set ( PARAVIEW_APP_DIR "/Applications/${OSX_PARAVIEW_APP}" )
-set ( PARAVIEW_APP_BIN_DIR "${PARAVIEW_APP_DIR}/Contents/MacOS" )
-set ( PARAVIEW_APP_LIB_DIR "${PARAVIEW_APP_DIR}/Contents/Libraries" )
-set ( PARAVIEW_APP_PLUGIN_DIR "${PARAVIEW_APP_DIR}/Contents/Plugins" )
+# We know exactly where this has to be on Darwin, but separate whether we have
+# kit build or a regular build.
+if ( ENABLE_CPACK AND MAKE_VATES )
+  add_definitions(-DBUNDLE_PARAVIEW)
+else ()
+  set ( PARAVIEW_APP_DIR "${ParaView_DIR}" )
+  set ( PARAVIEW_APP_BIN_DIR "${PARAVIEW_APP_DIR}/bin" )
+  set ( PARAVIEW_APP_LIB_DIR "${PARAVIEW_APP_DIR}/lib" )
+  set ( PARAVIEW_APP_PLUGIN_DIR "${PARAVIEW_APP_DIR}/lib" )
+endif ()
 
 set ( BIN_DIR MantidPlot.app/Contents/MacOS )
 set ( LIB_DIR MantidPlot.app/Contents/MacOS )
diff --git a/Code/Mantid/Build/CMake/FindBoost.cmake b/Code/Mantid/Build/CMake/FindBoost.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..9e546e6a8d07546f4150b26d19edc6ef6959ae7f
--- /dev/null
+++ b/Code/Mantid/Build/CMake/FindBoost.cmake
@@ -0,0 +1,1293 @@
+#.rst:
+# FindBoost
+# ---------
+#
+# Find Boost include dirs and libraries
+#
+# Use this module by invoking find_package with the form::
+#
+#   find_package(Boost
+#     [version] [EXACT]      # Minimum or EXACT version e.g. 1.36.0
+#     [REQUIRED]             # Fail with error if Boost is not found
+#     [COMPONENTS <libs>...] # Boost libraries by their canonical name
+#     )                      # e.g. "date_time" for "libboost_date_time"
+#
+# This module finds headers and requested component libraries OR a CMake
+# package configuration file provided by a "Boost CMake" build.  For the
+# latter case skip to the "Boost CMake" section below.  For the former
+# case results are reported in variables::
+#
+#   Boost_FOUND            - True if headers and requested libraries were found
+#   Boost_INCLUDE_DIRS     - Boost include directories
+#   Boost_LIBRARY_DIRS     - Link directories for Boost libraries
+#   Boost_LIBRARIES        - Boost component libraries to be linked
+#   Boost_<C>_FOUND        - True if component <C> was found (<C> is upper-case)
+#   Boost_<C>_LIBRARY      - Libraries to link for component <C> (may include
+#                            target_link_libraries debug/optimized keywords)
+#   Boost_VERSION          - BOOST_VERSION value from boost/version.hpp
+#   Boost_LIB_VERSION      - Version string appended to library filenames
+#   Boost_MAJOR_VERSION    - Boost major version number (X in X.y.z)
+#   Boost_MINOR_VERSION    - Boost minor version number (Y in x.Y.z)
+#   Boost_SUBMINOR_VERSION - Boost subminor version number (Z in x.y.Z)
+#   Boost_LIB_DIAGNOSTIC_DEFINITIONS (Windows)
+#                          - Pass to add_definitions() to have diagnostic
+#                            information about Boost's automatic linking
+#                            displayed during compilation
+#
+# This module reads hints about search locations from variables::
+#
+#   BOOST_ROOT             - Preferred installation prefix
+#    (or BOOSTROOT)
+#   BOOST_INCLUDEDIR       - Preferred include directory e.g. <prefix>/include
+#   BOOST_LIBRARYDIR       - Preferred library directory e.g. <prefix>/lib
+#   Boost_NO_SYSTEM_PATHS  - Set to ON to disable searching in locations not
+#                            specified by these hint variables. Default is OFF.
+#   Boost_ADDITIONAL_VERSIONS
+#                          - List of Boost versions not known to this module
+#                            (Boost install locations may contain the version)
+#
+# and saves search results persistently in CMake cache entries::
+#
+#   Boost_INCLUDE_DIR         - Directory containing Boost headers
+#   Boost_LIBRARY_DIR_RELEASE - Directory containing release Boost libraries
+#   Boost_LIBRARY_DIR_DEBUG   - Directory containing debug Boost libraries
+#   Boost_<C>_LIBRARY_DEBUG   - Component <C> library debug variant
+#   Boost_<C>_LIBRARY_RELEASE - Component <C> library release variant
+#
+# Users may set these hints or results as cache entries.  Projects
+# should not read these entries directly but instead use the above
+# result variables.  Note that some hint names start in upper-case
+# "BOOST".  One may specify these as environment variables if they are
+# not specified as CMake variables or cache entries.
+#
+# This module first searches for the Boost header files using the above
+# hint variables (excluding BOOST_LIBRARYDIR) and saves the result in
+# Boost_INCLUDE_DIR.  Then it searches for requested component libraries
+# using the above hints (excluding BOOST_INCLUDEDIR and
+# Boost_ADDITIONAL_VERSIONS), "lib" directories near Boost_INCLUDE_DIR,
+# and the library name configuration settings below.  It saves the
+# library directories in Boost_LIBRARY_DIR_DEBUG and
+# Boost_LIBRARY_DIR_RELEASE and individual library
+# locations in Boost_<C>_LIBRARY_DEBUG and Boost_<C>_LIBRARY_RELEASE.
+# When one changes settings used by previous searches in the same build
+# tree (excluding environment variables) this module discards previous
+# search results affected by the changes and searches again.
+#
+# Boost libraries come in many variants encoded in their file name.
+# Users or projects may tell this module which variant to find by
+# setting variables::
+#
+#   Boost_USE_MULTITHREADED  - Set to OFF to use the non-multithreaded
+#                              libraries ('mt' tag).  Default is ON.
+#   Boost_USE_STATIC_LIBS    - Set to ON to force the use of the static
+#                              libraries.  Default is OFF.
+#   Boost_USE_STATIC_RUNTIME - Set to ON or OFF to specify whether to use
+#                              libraries linked statically to the C++ runtime
+#                              ('s' tag).  Default is platform dependent.
+#   Boost_USE_DEBUG_RUNTIME  - Set to ON or OFF to specify whether to use
+#                              libraries linked to the MS debug C++ runtime
+#                              ('g' tag).  Default is ON.
+#   Boost_USE_DEBUG_PYTHON   - Set to ON to use libraries compiled with a
+#                              debug Python build ('y' tag). Default is OFF.
+#   Boost_USE_STLPORT        - Set to ON to use libraries compiled with
+#                              STLPort ('p' tag).  Default is OFF.
+#   Boost_USE_STLPORT_DEPRECATED_NATIVE_IOSTREAMS
+#                            - Set to ON to use libraries compiled with
+#                              STLPort deprecated "native iostreams"
+#                              ('n' tag).  Default is OFF.
+#   Boost_COMPILER           - Set to the compiler-specific library suffix
+#                              (e.g. "-gcc43").  Default is auto-computed
+#                              for the C++ compiler in use.
+#   Boost_THREADAPI          - Suffix for "thread" component library name,
+#                              such as "pthread" or "win32".  Names with
+#                              and without this suffix will both be tried.
+#   Boost_NAMESPACE          - Alternate namespace used to build boost with
+#                              e.g. if set to "myboost", will search for
+#                              myboost_thread instead of boost_thread.
+#
+# Other variables one may set to control this module are::
+#
+#   Boost_DEBUG              - Set to ON to enable debug output from FindBoost.
+#                              Please enable this before filing any bug report.
+#   Boost_DETAILED_FAILURE_MSG
+#                            - Set to ON to add detailed information to the
+#                              failure message even when the REQUIRED option
+#                              is not given to the find_package call.
+#   Boost_REALPATH           - Set to ON to resolve symlinks for discovered
+#                              libraries to assist with packaging.  For example,
+#                              the "system" component library may be resolved to
+#                              "/usr/lib/libboost_system.so.1.42.0" instead of
+#                              "/usr/lib/libboost_system.so".  This does not
+#                              affect linking and should not be enabled unless
+#                              the user needs this information.
+#   Boost_LIBRARY_DIR        - Default value for Boost_LIBRARY_DIR_RELEASE and
+#                              Boost_LIBRARY_DIR_DEBUG.
+#
+# On Visual Studio and Borland compilers Boost headers request automatic
+# linking to corresponding libraries.  This requires matching libraries
+# to be linked explicitly or available in the link library search path.
+# In this case setting Boost_USE_STATIC_LIBS to OFF may not achieve
+# dynamic linking.  Boost automatic linking typically requests static
+# libraries with a few exceptions (such as Boost.Python).  Use::
+#
+#   add_definitions(${Boost_LIB_DIAGNOSTIC_DEFINITIONS})
+#
+# to ask Boost to report information about automatic linking requests.
+#
+# Example to find Boost headers only::
+#
+#   find_package(Boost 1.36.0)
+#   if(Boost_FOUND)
+#     include_directories(${Boost_INCLUDE_DIRS})
+#     add_executable(foo foo.cc)
+#   endif()
+#
+# Example to find Boost headers and some *static* libraries::
+#
+#   set(Boost_USE_STATIC_LIBS        ON) # only find static libs
+#   set(Boost_USE_MULTITHREADED      ON)
+#   set(Boost_USE_STATIC_RUNTIME    OFF)
+#   find_package(Boost 1.36.0 COMPONENTS date_time filesystem system ...)
+#   if(Boost_FOUND)
+#     include_directories(${Boost_INCLUDE_DIRS})
+#     add_executable(foo foo.cc)
+#     target_link_libraries(foo ${Boost_LIBRARIES})
+#   endif()
+#
+# Boost CMake
+# ^^^^^^^^^^^
+#
+# If Boost was built using the boost-cmake project it provides a package
+# configuration file for use with find_package's Config mode.  This
+# module looks for the package configuration file called
+# BoostConfig.cmake or boost-config.cmake and stores the result in cache
+# entry "Boost_DIR".  If found, the package configuration file is loaded
+# and this module returns with no further action.  See documentation of
+# the Boost CMake package configuration for details on what it provides.
+#
+# Set Boost_NO_BOOST_CMAKE to ON to disable the search for boost-cmake.
+
+#=============================================================================
+# Copyright 2006-2012 Kitware, Inc.
+# Copyright 2006-2008 Andreas Schneider <mail@cynapses.org>
+# Copyright 2007      Wengo
+# Copyright 2007      Mike Jackson
+# Copyright 2008      Andreas Pakulat <apaku@gmx.de>
+# Copyright 2008-2012 Philip Lowman <philip@yhbt.com>
+#
+# Distributed under the OSI-approved BSD License (the "License");
+# see accompanying file Copyright.txt for details.
+#
+# This software is distributed WITHOUT ANY WARRANTY; without even the
+# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+# See the License for more information.
+#=============================================================================
+# (To distribute this file outside of CMake, substitute the full
+#  License text for the above reference.)
+
+
+#-------------------------------------------------------------------------------
+# Before we go searching, check whether boost-cmake is available, unless the
+# user specifically asked NOT to search for boost-cmake.
+#
+# If Boost_DIR is set, this behaves as any find_package call would. If not,
+# it looks at BOOST_ROOT and BOOSTROOT to find Boost.
+#
+if (NOT Boost_NO_BOOST_CMAKE)
+  # If Boost_DIR is not set, look for BOOSTROOT and BOOST_ROOT as alternatives,
+  # since these are more conventional for Boost.
+  if ("$ENV{Boost_DIR}" STREQUAL "")
+    if (NOT "$ENV{BOOST_ROOT}" STREQUAL "")
+      set(ENV{Boost_DIR} $ENV{BOOST_ROOT})
+    elseif (NOT "$ENV{BOOSTROOT}" STREQUAL "")
+      set(ENV{Boost_DIR} $ENV{BOOSTROOT})
+    endif()
+  endif()
+
+  # Do the same find_package call but look specifically for the CMake version.
+  # Note that args are passed in the Boost_FIND_xxxxx variables, so there is no
+  # need to delegate them to this find_package call.
+  find_package(Boost QUIET NO_MODULE)
+  mark_as_advanced(Boost_DIR)
+
+  # If we found boost-cmake, then we're done.  Print out what we found.
+  # Otherwise let the rest of the module try to find it.
+  if (Boost_FOUND)
+    message("Boost ${Boost_FIND_VERSION} found.")
+    if (Boost_FIND_COMPONENTS)
+      message("Found Boost components:")
+      message("   ${Boost_FIND_COMPONENTS}")
+    endif()
+    return()
+  endif()
+endif()
+
+
+#-------------------------------------------------------------------------------
+#  FindBoost functions & macros
+#
+
+############################################
+#
+# Check the existence of the libraries.
+#
+############################################
+# This macro was taken directly from the FindQt4.cmake file that is included
+# with the CMake distribution. This is NOT my work. All work was done by the
+# original authors of the FindQt4.cmake file. Only minor modifications were
+# made to remove references to Qt and make this file more generally applicable
+# And ELSE/ENDIF pairs were removed for readability.
+#########################################################################
+
+macro(_Boost_ADJUST_LIB_VARS basename)
+  if(Boost_INCLUDE_DIR )
+    if(Boost_${basename}_LIBRARY_DEBUG AND Boost_${basename}_LIBRARY_RELEASE)
+      # if the generator supports configuration types then set
+      # optimized and debug libraries, or if the CMAKE_BUILD_TYPE has a value
+      if(CMAKE_CONFIGURATION_TYPES OR CMAKE_BUILD_TYPE)
+        set(Boost_${basename}_LIBRARY optimized ${Boost_${basename}_LIBRARY_RELEASE} debug ${Boost_${basename}_LIBRARY_DEBUG})
+      else()
+        # if there are no configuration types and CMAKE_BUILD_TYPE has no value
+        # then just use the release libraries
+        set(Boost_${basename}_LIBRARY ${Boost_${basename}_LIBRARY_RELEASE} )
+      endif()
+      # FIXME: This probably should be set for both cases
+      set(Boost_${basename}_LIBRARIES optimized ${Boost_${basename}_LIBRARY_RELEASE} debug ${Boost_${basename}_LIBRARY_DEBUG})
+    endif()
+
+    # if only the release version was found, set the debug variable also to the release version
+    if(Boost_${basename}_LIBRARY_RELEASE AND NOT Boost_${basename}_LIBRARY_DEBUG)
+      set(Boost_${basename}_LIBRARY_DEBUG ${Boost_${basename}_LIBRARY_RELEASE})
+      set(Boost_${basename}_LIBRARY       ${Boost_${basename}_LIBRARY_RELEASE})
+      set(Boost_${basename}_LIBRARIES     ${Boost_${basename}_LIBRARY_RELEASE})
+    endif()
+
+    # if only the debug version was found, set the release variable also to the debug version
+    if(Boost_${basename}_LIBRARY_DEBUG AND NOT Boost_${basename}_LIBRARY_RELEASE)
+      set(Boost_${basename}_LIBRARY_RELEASE ${Boost_${basename}_LIBRARY_DEBUG})
+      set(Boost_${basename}_LIBRARY         ${Boost_${basename}_LIBRARY_DEBUG})
+      set(Boost_${basename}_LIBRARIES       ${Boost_${basename}_LIBRARY_DEBUG})
+    endif()
+
+    # If the debug & release library ends up being the same, omit the keywords
+    if(${Boost_${basename}_LIBRARY_RELEASE} STREQUAL ${Boost_${basename}_LIBRARY_DEBUG})
+      set(Boost_${basename}_LIBRARY   ${Boost_${basename}_LIBRARY_RELEASE} )
+      set(Boost_${basename}_LIBRARIES ${Boost_${basename}_LIBRARY_RELEASE} )
+    endif()
+
+    if(Boost_${basename}_LIBRARY)
+      set(Boost_${basename}_FOUND ON)
+    endif()
+
+  endif()
+  # Make variables changeable to the advanced user
+  mark_as_advanced(
+      Boost_${basename}_LIBRARY_RELEASE
+      Boost_${basename}_LIBRARY_DEBUG
+  )
+endmacro()
+
+# Detect changes in used variables.
+# Compares the current variable value with the last one.
+# In short form:
+# v != v_LAST                      -> CHANGED = 1
+# v is defined, v_LAST not         -> CHANGED = 1
+# v is not defined, but v_LAST is  -> CHANGED = 1
+# otherwise                        -> CHANGED = 0
+# CHANGED is returned in variable named ${changed_var}
+macro(_Boost_CHANGE_DETECT changed_var)
+  set(${changed_var} 0)
+  foreach(v ${ARGN})
+    if(DEFINED _Boost_COMPONENTS_SEARCHED)
+      if(${v})
+        if(_${v}_LAST)
+          string(COMPARE NOTEQUAL "${${v}}" "${_${v}_LAST}" _${v}_CHANGED)
+        else()
+          set(_${v}_CHANGED 1)
+        endif()
+      elseif(_${v}_LAST)
+        set(_${v}_CHANGED 1)
+      endif()
+      if(_${v}_CHANGED)
+        set(${changed_var} 1)
+      endif()
+    else()
+      set(_${v}_CHANGED 0)
+    endif()
+  endforeach()
+endmacro()
+
+#
+# Find the given library (var).
+# Use 'build_type' to support different lib paths for RELEASE or DEBUG builds
+#
+macro(_Boost_FIND_LIBRARY var build_type)
+
+  find_library(${var} ${ARGN})
+
+  if(${var})
+    # If this is the first library found then save Boost_LIBRARY_DIR_[RELEASE,DEBUG].
+    if(NOT Boost_LIBRARY_DIR_${build_type})
+      get_filename_component(_dir "${${var}}" PATH)
+      set(Boost_LIBRARY_DIR_${build_type} "${_dir}" CACHE PATH "Boost library directory ${build_type}" FORCE)
+    endif()
+  elseif(_Boost_FIND_LIBRARY_HINTS_FOR_COMPONENT)
+    # Try component-specific hints but do not save Boost_LIBRARY_DIR_[RELEASE,DEBUG].
+    find_library(${var} HINTS ${_Boost_FIND_LIBRARY_HINTS_FOR_COMPONENT} ${ARGN})
+  endif()
+
+  # If Boost_LIBRARY_DIR_[RELEASE,DEBUG] is known then search only there.
+  if(Boost_LIBRARY_DIR_${build_type})
+    set(_boost_LIBRARY_SEARCH_DIRS_${build_type} ${Boost_LIBRARY_DIR_${build_type}} NO_DEFAULT_PATH NO_CMAKE_FIND_ROOT_PATH)
+    if(Boost_DEBUG)
+      message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
+        " Boost_LIBRARY_DIR_${build_type} = ${Boost_LIBRARY_DIR_${build_type}}"
+        " _boost_LIBRARY_SEARCH_DIRS_${build_type} = ${_boost_LIBRARY_SEARCH_DIRS_${build_type}}")
+    endif()
+  endif()
+endmacro()
+
+#-------------------------------------------------------------------------------
+
+#
+# Runs compiler with "-dumpversion" and parses major/minor
+# version with a regex.
+#
+function(_Boost_COMPILER_DUMPVERSION _OUTPUT_VERSION)
+
+  exec_program(${CMAKE_CXX_COMPILER}
+    ARGS ${CMAKE_CXX_COMPILER_ARG1} -dumpversion
+    OUTPUT_VARIABLE _boost_COMPILER_VERSION
+  )
+  string(REGEX REPLACE "([0-9])\\.([0-9])(\\.[0-9])?" "\\1\\2"
+    _boost_COMPILER_VERSION ${_boost_COMPILER_VERSION})
+
+  set(${_OUTPUT_VERSION} ${_boost_COMPILER_VERSION} PARENT_SCOPE)
+endfunction()
+
+#
+# Take a list of libraries with "thread" in it
+# and prepend duplicates with "thread_${Boost_THREADAPI}"
+# at the front of the list
+#
+function(_Boost_PREPEND_LIST_WITH_THREADAPI _output)
+  set(_orig_libnames ${ARGN})
+  string(REPLACE "thread" "thread_${Boost_THREADAPI}" _threadapi_libnames "${_orig_libnames}")
+  set(${_output} ${_threadapi_libnames} ${_orig_libnames} PARENT_SCOPE)
+endfunction()
+
+#
+# If a library is found, replace its cache entry with its REALPATH
+#
+function(_Boost_SWAP_WITH_REALPATH _library _docstring)
+  if(${_library})
+    get_filename_component(_boost_filepathreal ${${_library}} REALPATH)
+    unset(${_library} CACHE)
+    set(${_library} ${_boost_filepathreal} CACHE FILEPATH "${_docstring}")
+  endif()
+endfunction()
+
+function(_Boost_CHECK_SPELLING _var)
+  if(${_var})
+    string(TOUPPER ${_var} _var_UC)
+    message(FATAL_ERROR "ERROR: ${_var} is not the correct spelling.  The proper spelling is ${_var_UC}.")
+  endif()
+endfunction()
+
+# Guesses Boost's compiler prefix used in built library names
+# Returns the guess by setting the variable pointed to by _ret
+function(_Boost_GUESS_COMPILER_PREFIX _ret)
+  if(CMAKE_CXX_COMPILER_ID STREQUAL "Intel"
+      OR CMAKE_CXX_COMPILER MATCHES "icl"
+      OR CMAKE_CXX_COMPILER MATCHES "icpc")
+    if(WIN32)
+      set (_boost_COMPILER "-iw")
+    else()
+      set (_boost_COMPILER "-il")
+    endif()
+  elseif (MSVC14)
+    set(_boost_COMPILER "-vc140")
+  elseif (MSVC12)
+    set(_boost_COMPILER "-vc120")
+  elseif (MSVC11)
+    set(_boost_COMPILER "-vc110")
+  elseif (MSVC10)
+    set(_boost_COMPILER "-vc100")
+  elseif (MSVC90)
+    set(_boost_COMPILER "-vc90")
+  elseif (MSVC80)
+    set(_boost_COMPILER "-vc80")
+  elseif (MSVC71)
+    set(_boost_COMPILER "-vc71")
+  elseif (MSVC70) # Good luck!
+    set(_boost_COMPILER "-vc7") # yes, this is correct
+  elseif (MSVC60) # Good luck!
+    set(_boost_COMPILER "-vc6") # yes, this is correct
+  elseif (BORLAND)
+    set(_boost_COMPILER "-bcb")
+  elseif(CMAKE_CXX_COMPILER_ID STREQUAL "SunPro")
+    set(_boost_COMPILER "-sw")
+  elseif (MINGW)
+    if(${Boost_MAJOR_VERSION}.${Boost_MINOR_VERSION} VERSION_LESS 1.34)
+        set(_boost_COMPILER "-mgw") # no GCC version encoding prior to 1.34
+    else()
+      _Boost_COMPILER_DUMPVERSION(_boost_COMPILER_VERSION)
+      set(_boost_COMPILER "-mgw${_boost_COMPILER_VERSION}")
+    endif()
+  elseif (UNIX)
+    if (CMAKE_COMPILER_IS_GNUCXX)
+      if(${Boost_MAJOR_VERSION}.${Boost_MINOR_VERSION} VERSION_LESS 1.34)
+        set(_boost_COMPILER "-gcc") # no GCC version encoding prior to 1.34
+      else()
+        _Boost_COMPILER_DUMPVERSION(_boost_COMPILER_VERSION)
+        # Determine which version of GCC we have.
+        if(APPLE)
+          if(Boost_MINOR_VERSION)
+            if(${Boost_MINOR_VERSION} GREATER 35)
+              # In Boost 1.36.0 and newer, the mangled compiler name used
+              # on Mac OS X/Darwin is "xgcc".
+              set(_boost_COMPILER "-xgcc${_boost_COMPILER_VERSION}")
+            else()
+              # In Boost <= 1.35.0, there is no mangled compiler name for
+              # the Mac OS X/Darwin version of GCC.
+              set(_boost_COMPILER "")
+            endif()
+          else()
+            # We don't know the Boost version, so assume it's
+            # pre-1.36.0.
+            set(_boost_COMPILER "")
+          endif()
+        else()
+          set(_boost_COMPILER "-gcc${_boost_COMPILER_VERSION}")
+        endif()
+      endif()
+    endif ()
+  else()
+    # TODO at least Boost_DEBUG here?
+    set(_boost_COMPILER "")
+  endif()
+  set(${_ret} ${_boost_COMPILER} PARENT_SCOPE)
+endfunction()
+
+#
+# End functions/macros
+#
+#-------------------------------------------------------------------------------
+
+#-------------------------------------------------------------------------------
+# main.
+#-------------------------------------------------------------------------------
+
+
+# If the user sets Boost_LIBRARY_DIR, use it as the default for both
+# configurations.
+if(NOT Boost_LIBRARY_DIR_RELEASE AND Boost_LIBRARY_DIR)
+  set(Boost_LIBRARY_DIR_RELEASE "${Boost_LIBRARY_DIR}")
+endif()
+if(NOT Boost_LIBRARY_DIR_DEBUG AND Boost_LIBRARY_DIR)
+  set(Boost_LIBRARY_DIR_DEBUG   "${Boost_LIBRARY_DIR}")
+endif()
+
+if(NOT DEFINED Boost_USE_MULTITHREADED)
+    set(Boost_USE_MULTITHREADED TRUE)
+endif()
+if(NOT DEFINED Boost_USE_DEBUG_RUNTIME)
+  set(Boost_USE_DEBUG_RUNTIME TRUE)
+endif()
+
+# Check the version of Boost against the requested version.
+if(Boost_FIND_VERSION AND NOT Boost_FIND_VERSION_MINOR)
+  message(SEND_ERROR "When requesting a specific version of Boost, you must provide at least the major and minor version numbers, e.g., 1.34")
+endif()
+
+if(Boost_FIND_VERSION_EXACT)
+  # The version may appear in a directory with or without the patch
+  # level, even when the patch level is non-zero.
+  set(_boost_TEST_VERSIONS
+    "${Boost_FIND_VERSION_MAJOR}.${Boost_FIND_VERSION_MINOR}.${Boost_FIND_VERSION_PATCH}"
+    "${Boost_FIND_VERSION_MAJOR}.${Boost_FIND_VERSION_MINOR}")
+else()
+  # The user has not requested an exact version.  Among known
+  # versions, find those that are acceptable to the user request.
+  set(_Boost_KNOWN_VERSIONS ${Boost_ADDITIONAL_VERSIONS}
+    "1.58.0" "1.58" "1.57.0" "1.57" "1.56.0" "1.56" "1.55.0" "1.55" "1.54.0" "1.54"
+    "1.53.0" "1.53" "1.52.0" "1.52" "1.51.0" "1.51"
+    "1.50.0" "1.50" "1.49.0" "1.49" "1.48.0" "1.48" "1.47.0" "1.47" "1.46.1"
+    "1.46.0" "1.46" "1.45.0" "1.45" "1.44.0" "1.44" "1.43.0" "1.43" "1.42.0" "1.42"
+    "1.41.0" "1.41" "1.40.0" "1.40" "1.39.0" "1.39" "1.38.0" "1.38" "1.37.0" "1.37"
+    "1.36.1" "1.36.0" "1.36" "1.35.1" "1.35.0" "1.35" "1.34.1" "1.34.0"
+    "1.34" "1.33.1" "1.33.0" "1.33")
+  set(_boost_TEST_VERSIONS)
+  if(Boost_FIND_VERSION)
+    set(_Boost_FIND_VERSION_SHORT "${Boost_FIND_VERSION_MAJOR}.${Boost_FIND_VERSION_MINOR}")
+    # Select acceptable versions.
+    foreach(version ${_Boost_KNOWN_VERSIONS})
+      if(NOT "${version}" VERSION_LESS "${Boost_FIND_VERSION}")
+        # This version is high enough.
+        list(APPEND _boost_TEST_VERSIONS "${version}")
+      elseif("${version}.99" VERSION_EQUAL "${_Boost_FIND_VERSION_SHORT}.99")
+        # This version is a short-form for the requested version with
+        # the patch level dropped.
+        list(APPEND _boost_TEST_VERSIONS "${version}")
+      endif()
+    endforeach()
+  else()
+    # Any version is acceptable.
+    set(_boost_TEST_VERSIONS "${_Boost_KNOWN_VERSIONS}")
+  endif()
+endif()
+
+# The reason that we failed to find Boost. This will be set to a
+# user-friendly message when we fail to find some necessary piece of
+# Boost.
+set(Boost_ERROR_REASON)
+
+if(Boost_DEBUG)
+  # Output some of their choices
+  message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
+                 "_boost_TEST_VERSIONS = ${_boost_TEST_VERSIONS}")
+  message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
+                 "Boost_USE_MULTITHREADED = ${Boost_USE_MULTITHREADED}")
+  message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
+                 "Boost_USE_STATIC_LIBS = ${Boost_USE_STATIC_LIBS}")
+  message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
+                 "Boost_USE_STATIC_RUNTIME = ${Boost_USE_STATIC_RUNTIME}")
+  message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
+                 "Boost_ADDITIONAL_VERSIONS = ${Boost_ADDITIONAL_VERSIONS}")
+  message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
+                 "Boost_NO_SYSTEM_PATHS = ${Boost_NO_SYSTEM_PATHS}")
+endif()
+
+if(WIN32)
+  # In windows, automatic linking is performed, so you do not have
+  # to specify the libraries.  If you are linking to a dynamic
+  # runtime, then you can choose to link to either a static or a
+  # dynamic Boost library, the default is to do a static link.  You
+  # can alter this for a specific library "whatever" by defining
+  # BOOST_WHATEVER_DYN_LINK to force Boost library "whatever" to be
+  # linked dynamically.  Alternatively you can force all Boost
+  # libraries to dynamic link by defining BOOST_ALL_DYN_LINK.
+
+  # This feature can be disabled for Boost library "whatever" by
+  # defining BOOST_WHATEVER_NO_LIB, or for all of Boost by defining
+  # BOOST_ALL_NO_LIB.
+
+  # If you want to observe which libraries are being linked against
+  # then defining BOOST_LIB_DIAGNOSTIC will cause the auto-linking
+  # code to emit a #pragma message each time a library is selected
+  # for linking.
+  set(Boost_LIB_DIAGNOSTIC_DEFINITIONS "-DBOOST_LIB_DIAGNOSTIC")
+endif()
+
+_Boost_CHECK_SPELLING(Boost_ROOT)
+_Boost_CHECK_SPELLING(Boost_LIBRARYDIR)
+_Boost_CHECK_SPELLING(Boost_INCLUDEDIR)
+
+# Collect environment variable inputs as hints.  Do not consider changes.
+foreach(v BOOSTROOT BOOST_ROOT BOOST_INCLUDEDIR BOOST_LIBRARYDIR)
+  set(_env $ENV{${v}})
+  if(_env)
+    file(TO_CMAKE_PATH "${_env}" _ENV_${v})
+  else()
+    set(_ENV_${v} "")
+  endif()
+endforeach()
+if(NOT _ENV_BOOST_ROOT AND _ENV_BOOSTROOT)
+  set(_ENV_BOOST_ROOT "${_ENV_BOOSTROOT}")
+endif()
+
+# Collect inputs and cached results.  Detect changes since the last run.
+if(NOT BOOST_ROOT AND BOOSTROOT)
+  set(BOOST_ROOT "${BOOSTROOT}")
+endif()
+set(_Boost_VARS_DIR
+  BOOST_ROOT
+  Boost_NO_SYSTEM_PATHS
+  )
+
+if(Boost_DEBUG)
+  message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
+                 "Declared as CMake or Environmental Variables:")
+  message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
+                 "  BOOST_ROOT = ${BOOST_ROOT}")
+  message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
+                 "  BOOST_INCLUDEDIR = ${BOOST_INCLUDEDIR}")
+  message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
+                 "  BOOST_LIBRARYDIR = ${BOOST_LIBRARYDIR}")
+  message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
+                 "_boost_TEST_VERSIONS = ${_boost_TEST_VERSIONS}")
+endif()
+
+# ------------------------------------------------------------------------
+#  Search for Boost include DIR
+# ------------------------------------------------------------------------
+
+set(_Boost_VARS_INC BOOST_INCLUDEDIR Boost_INCLUDE_DIR Boost_ADDITIONAL_VERSIONS)
+_Boost_CHANGE_DETECT(_Boost_CHANGE_INCDIR ${_Boost_VARS_DIR} ${_Boost_VARS_INC})
+# Clear Boost_INCLUDE_DIR if it did not change but other input affecting the
+# location did.  We will find a new one based on the new inputs.
+if(_Boost_CHANGE_INCDIR AND NOT _Boost_INCLUDE_DIR_CHANGED)
+  unset(Boost_INCLUDE_DIR CACHE)
+endif()
+
+if(NOT Boost_INCLUDE_DIR)
+  set(_boost_INCLUDE_SEARCH_DIRS "")
+  if(BOOST_INCLUDEDIR)
+    list(APPEND _boost_INCLUDE_SEARCH_DIRS ${BOOST_INCLUDEDIR})
+  elseif(_ENV_BOOST_INCLUDEDIR)
+    list(APPEND _boost_INCLUDE_SEARCH_DIRS ${_ENV_BOOST_INCLUDEDIR})
+  endif()
+
+  if( BOOST_ROOT )
+    list(APPEND _boost_INCLUDE_SEARCH_DIRS ${BOOST_ROOT}/include ${BOOST_ROOT})
+  elseif( _ENV_BOOST_ROOT )
+    list(APPEND _boost_INCLUDE_SEARCH_DIRS ${_ENV_BOOST_ROOT}/include ${_ENV_BOOST_ROOT})
+  endif()
+
+  if( Boost_NO_SYSTEM_PATHS)
+    list(APPEND _boost_INCLUDE_SEARCH_DIRS NO_CMAKE_SYSTEM_PATH)
+  else()
+    list(APPEND _boost_INCLUDE_SEARCH_DIRS PATHS
+      C:/boost/include
+      C:/boost
+      /sw/local/include
+      )
+  endif()
+
+  # Try to find Boost by stepping backwards through the Boost versions
+  # we know about.
+  # Build a list of path suffixes for each version.
+  set(_boost_PATH_SUFFIXES)
+  foreach(_boost_VER ${_boost_TEST_VERSIONS})
+    # Add in a path suffix, based on the required version, ideally
+    # we could read this from version.hpp, but for that to work we'd
+    # need to know the include dir already
+    set(_boost_BOOSTIFIED_VERSION)
+
+    # Transform 1.35 => 1_35 and 1.36.0 => 1_36_0
+    if(_boost_VER MATCHES "([0-9]+)\\.([0-9]+)\\.([0-9]+)")
+        set(_boost_BOOSTIFIED_VERSION
+          "${CMAKE_MATCH_1}_${CMAKE_MATCH_2}_${CMAKE_MATCH_3}")
+    elseif(_boost_VER MATCHES "([0-9]+)\\.([0-9]+)")
+        set(_boost_BOOSTIFIED_VERSION
+          "${CMAKE_MATCH_1}_${CMAKE_MATCH_2}")
+    endif()
+
+    list(APPEND _boost_PATH_SUFFIXES
+      "boost-${_boost_BOOSTIFIED_VERSION}"
+      "boost_${_boost_BOOSTIFIED_VERSION}"
+      "boost/boost-${_boost_BOOSTIFIED_VERSION}"
+      "boost/boost_${_boost_BOOSTIFIED_VERSION}"
+      )
+
+  endforeach()
+
+  if(Boost_DEBUG)
+    message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
+                   "Include debugging info:")
+    message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
+                   "  _boost_INCLUDE_SEARCH_DIRS = ${_boost_INCLUDE_SEARCH_DIRS}")
+    message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
+                   "  _boost_PATH_SUFFIXES = ${_boost_PATH_SUFFIXES}")
+  endif()
+
+  # Look for a standard boost header file.
+  find_path(Boost_INCLUDE_DIR
+    NAMES         boost/config.hpp
+    HINTS         ${_boost_INCLUDE_SEARCH_DIRS}
+    PATH_SUFFIXES ${_boost_PATH_SUFFIXES}
+    )
+endif()
+
+# ------------------------------------------------------------------------
+#  Extract version information from version.hpp
+# ------------------------------------------------------------------------
+
+# Set Boost_FOUND based only on header location and version.
+# It will be updated below for component libraries.
+if(Boost_INCLUDE_DIR)
+  if(Boost_DEBUG)
+    message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
+                   "location of version.hpp: ${Boost_INCLUDE_DIR}/boost/version.hpp")
+  endif()
+
+  # Extract Boost_VERSION and Boost_LIB_VERSION from version.hpp
+  set(Boost_VERSION 0)
+  set(Boost_LIB_VERSION "")
+  file(STRINGS "${Boost_INCLUDE_DIR}/boost/version.hpp" _boost_VERSION_HPP_CONTENTS REGEX "#define BOOST_(LIB_)?VERSION ")
+  set(_Boost_VERSION_REGEX "([0-9]+)")
+  set(_Boost_LIB_VERSION_REGEX "\"([0-9_]+)\"")
+  foreach(v VERSION LIB_VERSION)
+    if("${_boost_VERSION_HPP_CONTENTS}" MATCHES "#define BOOST_${v} ${_Boost_${v}_REGEX}")
+      set(Boost_${v} "${CMAKE_MATCH_1}")
+    endif()
+  endforeach()
+  unset(_boost_VERSION_HPP_CONTENTS)
+
+  math(EXPR Boost_MAJOR_VERSION "${Boost_VERSION} / 100000")
+  math(EXPR Boost_MINOR_VERSION "${Boost_VERSION} / 100 % 1000")
+  math(EXPR Boost_SUBMINOR_VERSION "${Boost_VERSION} % 100")
+
+  set(Boost_ERROR_REASON
+    "${Boost_ERROR_REASON}Boost version: ${Boost_MAJOR_VERSION}.${Boost_MINOR_VERSION}.${Boost_SUBMINOR_VERSION}\nBoost include path: ${Boost_INCLUDE_DIR}")
+  if(Boost_DEBUG)
+    message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
+                   "version.hpp reveals boost "
+                   "${Boost_MAJOR_VERSION}.${Boost_MINOR_VERSION}.${Boost_SUBMINOR_VERSION}")
+  endif()
+
+  if(Boost_FIND_VERSION)
+    # Set Boost_FOUND based on requested version.
+    set(_Boost_VERSION "${Boost_MAJOR_VERSION}.${Boost_MINOR_VERSION}.${Boost_SUBMINOR_VERSION}")
+    if("${_Boost_VERSION}" VERSION_LESS "${Boost_FIND_VERSION}")
+      set(Boost_FOUND 0)
+      set(_Boost_VERSION_AGE "old")
+    elseif(Boost_FIND_VERSION_EXACT AND
+        NOT "${_Boost_VERSION}" VERSION_EQUAL "${Boost_FIND_VERSION}")
+      set(Boost_FOUND 0)
+      set(_Boost_VERSION_AGE "new")
+    else()
+      set(Boost_FOUND 1)
+    endif()
+    if(NOT Boost_FOUND)
+      # State that we found a version of Boost that is too new or too old.
+      set(Boost_ERROR_REASON
+        "${Boost_ERROR_REASON}\nDetected version of Boost is too ${_Boost_VERSION_AGE}. Requested version was ${Boost_FIND_VERSION_MAJOR}.${Boost_FIND_VERSION_MINOR}")
+      if (Boost_FIND_VERSION_PATCH)
+        set(Boost_ERROR_REASON
+          "${Boost_ERROR_REASON}.${Boost_FIND_VERSION_PATCH}")
+      endif ()
+      if (NOT Boost_FIND_VERSION_EXACT)
+        set(Boost_ERROR_REASON "${Boost_ERROR_REASON} (or newer)")
+      endif ()
+      set(Boost_ERROR_REASON "${Boost_ERROR_REASON}.")
+    endif ()
+  else()
+    # Caller will accept any Boost version.
+    set(Boost_FOUND 1)
+  endif()
+else()
+  set(Boost_FOUND 0)
+  set(Boost_ERROR_REASON
+    "${Boost_ERROR_REASON}Unable to find the Boost header files. Please set BOOST_ROOT to the root directory containing Boost or BOOST_INCLUDEDIR to the directory containing Boost's headers.")
+endif()
+
+# ------------------------------------------------------------------------
+#  Prefix initialization
+# ------------------------------------------------------------------------
+
+set(Boost_LIB_PREFIX "")
+if ( WIN32 AND Boost_USE_STATIC_LIBS AND NOT CYGWIN)
+  set(Boost_LIB_PREFIX "lib")
+endif()
+
+if ( NOT Boost_NAMESPACE )
+  set(Boost_NAMESPACE "boost")
+endif()
+
+# ------------------------------------------------------------------------
+#  Suffix initialization and compiler suffix detection.
+# ------------------------------------------------------------------------
+
+set(_Boost_VARS_NAME
+  Boost_NAMESPACE
+  Boost_COMPILER
+  Boost_THREADAPI
+  Boost_USE_DEBUG_PYTHON
+  Boost_USE_MULTITHREADED
+  Boost_USE_STATIC_LIBS
+  Boost_USE_STATIC_RUNTIME
+  Boost_USE_STLPORT
+  Boost_USE_STLPORT_DEPRECATED_NATIVE_IOSTREAMS
+  )
+_Boost_CHANGE_DETECT(_Boost_CHANGE_LIBNAME ${_Boost_VARS_NAME})
+
+# Setting some more suffixes for the library
+if (Boost_COMPILER)
+  set(_boost_COMPILER ${Boost_COMPILER})
+  if(Boost_DEBUG)
+    message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
+                   "using user-specified Boost_COMPILER = ${_boost_COMPILER}")
+  endif()
+else()
+  # Attempt to guess the compiler suffix
+  # NOTE: this is not perfect yet, if you experience any issues
+  # please report them and use the Boost_COMPILER variable
+  # to work around the problems.
+  _Boost_GUESS_COMPILER_PREFIX(_boost_COMPILER)
+  if(Boost_DEBUG)
+    message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
+      "guessed _boost_COMPILER = ${_boost_COMPILER}")
+  endif()
+endif()
+
+set (_boost_MULTITHREADED "-mt")
+if( NOT Boost_USE_MULTITHREADED )
+  set (_boost_MULTITHREADED "")
+endif()
+if(Boost_DEBUG)
+  message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
+    "_boost_MULTITHREADED = ${_boost_MULTITHREADED}")
+endif()
+
+#======================
+# Systematically build up the Boost ABI tag
+# http://boost.org/doc/libs/1_41_0/more/getting_started/windows.html#library-naming
+set( _boost_RELEASE_ABI_TAG "-")
+set( _boost_DEBUG_ABI_TAG   "-")
+# Key       Use this library when:
+#  s        linking statically to the C++ standard library and
+#           compiler runtime support libraries.
+if(Boost_USE_STATIC_RUNTIME)
+  set( _boost_RELEASE_ABI_TAG "${_boost_RELEASE_ABI_TAG}s")
+  set( _boost_DEBUG_ABI_TAG   "${_boost_DEBUG_ABI_TAG}s")
+endif()
+#  g        using debug versions of the standard and runtime
+#           support libraries
+if(WIN32 AND Boost_USE_DEBUG_RUNTIME)
+  if(MSVC OR "${CMAKE_CXX_COMPILER}" MATCHES "icl"
+          OR "${CMAKE_CXX_COMPILER}" MATCHES "icpc")
+    set(_boost_DEBUG_ABI_TAG "${_boost_DEBUG_ABI_TAG}g")
+  endif()
+endif()
+#  y        using special debug build of python
+if(Boost_USE_DEBUG_PYTHON)
+  set(_boost_DEBUG_ABI_TAG "${_boost_DEBUG_ABI_TAG}y")
+endif()
+#  d        using a debug version of your code
+set(_boost_DEBUG_ABI_TAG "${_boost_DEBUG_ABI_TAG}d")
+#  p        using the STLport standard library rather than the
+#           default one supplied with your compiler
+if(Boost_USE_STLPORT)
+  set( _boost_RELEASE_ABI_TAG "${_boost_RELEASE_ABI_TAG}p")
+  set( _boost_DEBUG_ABI_TAG   "${_boost_DEBUG_ABI_TAG}p")
+endif()
+#  n        using the STLport deprecated "native iostreams" feature
+if(Boost_USE_STLPORT_DEPRECATED_NATIVE_IOSTREAMS)
+  set( _boost_RELEASE_ABI_TAG "${_boost_RELEASE_ABI_TAG}n")
+  set( _boost_DEBUG_ABI_TAG   "${_boost_DEBUG_ABI_TAG}n")
+endif()
+
+if(Boost_DEBUG)
+  message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
+    "_boost_RELEASE_ABI_TAG = ${_boost_RELEASE_ABI_TAG}")
+  message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
+    "_boost_DEBUG_ABI_TAG = ${_boost_DEBUG_ABI_TAG}")
+endif()
+
+# ------------------------------------------------------------------------
+#  Begin finding boost libraries
+# ------------------------------------------------------------------------
+
+foreach(c DEBUG RELEASE)
+  set(_Boost_VARS_LIB_${c} BOOST_LIBRARYDIR Boost_LIBRARY_DIR_${c})
+  _Boost_CHANGE_DETECT(_Boost_CHANGE_LIBDIR_${c} ${_Boost_VARS_DIR} ${_Boost_VARS_LIB_${c}} Boost_INCLUDE_DIR)
+  # Clear Boost_LIBRARY_DIR_${c} if it did not change but other input affecting the
+  # location did.  We will find a new one based on the new inputs.
+  if(_Boost_CHANGE_LIBDIR_${c} AND NOT _Boost_LIBRARY_DIR_${c}_CHANGED)
+    unset(Boost_LIBRARY_DIR_${c} CACHE)
+  endif()
+
+  # If Boost_LIBRARY_DIR_[RELEASE,DEBUG] is set, prefer its value.
+  if(Boost_LIBRARY_DIR_${c})
+    set(_boost_LIBRARY_SEARCH_DIRS_${c} ${Boost_LIBRARY_DIR_${c}} NO_DEFAULT_PATH NO_CMAKE_FIND_ROOT_PATH)
+  else()
+    set(_boost_LIBRARY_SEARCH_DIRS_${c} "")
+    if(BOOST_LIBRARYDIR)
+      list(APPEND _boost_LIBRARY_SEARCH_DIRS_${c} ${BOOST_LIBRARYDIR})
+    elseif(_ENV_BOOST_LIBRARYDIR)
+      list(APPEND _boost_LIBRARY_SEARCH_DIRS_${c} ${_ENV_BOOST_LIBRARYDIR})
+    endif()
+
+    if(BOOST_ROOT)
+      list(APPEND _boost_LIBRARY_SEARCH_DIRS_${c} ${BOOST_ROOT}/lib ${BOOST_ROOT}/stage/lib)
+    elseif(_ENV_BOOST_ROOT)
+      list(APPEND _boost_LIBRARY_SEARCH_DIRS_${c} ${_ENV_BOOST_ROOT}/lib ${_ENV_BOOST_ROOT}/stage/lib)
+    endif()
+
+    list(APPEND _boost_LIBRARY_SEARCH_DIRS_${c}
+      ${Boost_INCLUDE_DIR}/lib
+      ${Boost_INCLUDE_DIR}/../lib
+      ${Boost_INCLUDE_DIR}/stage/lib
+      )
+    if( Boost_NO_SYSTEM_PATHS )
+      list(APPEND _boost_LIBRARY_SEARCH_DIRS_${c} NO_CMAKE_SYSTEM_PATH)
+    else()
+      list(APPEND _boost_LIBRARY_SEARCH_DIRS_${c} PATHS
+        C:/boost/lib
+        C:/boost
+        /sw/local/lib
+        )
+    endif()
+  endif()
+endforeach()
+
+if(Boost_DEBUG)
+  message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
+    "_boost_LIBRARY_SEARCH_DIRS_RELEASE = ${_boost_LIBRARY_SEARCH_DIRS_RELEASE}"
+    "_boost_LIBRARY_SEARCH_DIRS_DEBUG   = ${_boost_LIBRARY_SEARCH_DIRS_DEBUG}")
+endif()
+
+# Support preference of static libs by adjusting CMAKE_FIND_LIBRARY_SUFFIXES
+if( Boost_USE_STATIC_LIBS )
+  set( _boost_ORIG_CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES})
+  if(WIN32)
+    set(CMAKE_FIND_LIBRARY_SUFFIXES .lib .a ${CMAKE_FIND_LIBRARY_SUFFIXES})
+  else()
+    set(CMAKE_FIND_LIBRARY_SUFFIXES .a )
+  endif()
+endif()
+
+# We want to use the tag inline below without risking double dashes
+if(_boost_RELEASE_ABI_TAG)
+  if(${_boost_RELEASE_ABI_TAG} STREQUAL "-")
+    set(_boost_RELEASE_ABI_TAG "")
+  endif()
+endif()
+if(_boost_DEBUG_ABI_TAG)
+  if(${_boost_DEBUG_ABI_TAG} STREQUAL "-")
+    set(_boost_DEBUG_ABI_TAG "")
+  endif()
+endif()
+
+# The previous behavior of FindBoost when Boost_USE_STATIC_LIBS was enabled
+# on WIN32 was to:
+#  1. Search for static libs compiled against a SHARED C++ standard runtime library (use if found)
+#  2. Search for static libs compiled against a STATIC C++ standard runtime library (use if found)
+# We maintain this behavior since changing it could break people's builds.
+# To disable the ambiguous behavior, the user need only
+# set Boost_USE_STATIC_RUNTIME either ON or OFF.
+set(_boost_STATIC_RUNTIME_WORKAROUND false)
+if(WIN32 AND Boost_USE_STATIC_LIBS)
+  if(NOT DEFINED Boost_USE_STATIC_RUNTIME)
+    set(_boost_STATIC_RUNTIME_WORKAROUND true)
+  endif()
+endif()
+
+# On versions < 1.35, remove the System library from the considered list
+# since it wasn't added until 1.35.
+if(Boost_VERSION AND Boost_FIND_COMPONENTS)
+   if(Boost_VERSION LESS 103500)
+     list(REMOVE_ITEM Boost_FIND_COMPONENTS system)
+   endif()
+endif()
+
+# If the user changed any of our control inputs flush previous results.
+if(_Boost_CHANGE_LIBDIR OR _Boost_CHANGE_LIBNAME)
+  foreach(COMPONENT ${_Boost_COMPONENTS_SEARCHED})
+    string(TOUPPER ${COMPONENT} UPPERCOMPONENT)
+    foreach(c DEBUG RELEASE)
+      set(_var Boost_${UPPERCOMPONENT}_LIBRARY_${c})
+      unset(${_var} CACHE)
+      set(${_var} "${_var}-NOTFOUND")
+    endforeach()
+  endforeach()
+  set(_Boost_COMPONENTS_SEARCHED "")
+endif()
+
+foreach(COMPONENT ${Boost_FIND_COMPONENTS})
+  string(TOUPPER ${COMPONENT} UPPERCOMPONENT)
+
+  set( _boost_docstring_release "Boost ${COMPONENT} library (release)")
+  set( _boost_docstring_debug   "Boost ${COMPONENT} library (debug)")
+
+  # Compute component-specific hints.
+  set(_Boost_FIND_LIBRARY_HINTS_FOR_COMPONENT "")
+  if(${COMPONENT} STREQUAL "mpi" OR ${COMPONENT} STREQUAL "mpi_python" OR
+     ${COMPONENT} STREQUAL "graph_parallel")
+    foreach(lib ${MPI_CXX_LIBRARIES} ${MPI_C_LIBRARIES})
+      if(IS_ABSOLUTE "${lib}")
+        get_filename_component(libdir "${lib}" PATH)
+        string(REPLACE "\\" "/" libdir "${libdir}")
+        list(APPEND _Boost_FIND_LIBRARY_HINTS_FOR_COMPONENT ${libdir})
+        # This need to be done more cleanly - Needed for MPI Job 
+        list(APPEND _Boost_FIND_LIBRARY_HINTS_FOR_COMPONENT "/usr/lib64/openmpi/lib")
+      endif()
+    endforeach()
+  endif()
+
+  # Consolidate and report component-specific hints.
+  if(_Boost_FIND_LIBRARY_HINTS_FOR_COMPONENT)
+    list(REMOVE_DUPLICATES _Boost_FIND_LIBRARY_HINTS_FOR_COMPONENT)
+    if(Boost_DEBUG)
+      message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
+        "Component-specific library search paths for ${COMPONENT}: "
+        "${_Boost_FIND_LIBRARY_HINTS_FOR_COMPONENT}")
+    endif()
+  endif()
+
+  #
+  # Find RELEASE libraries
+  #
+  set(_boost_RELEASE_NAMES
+    ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${_boost_COMPILER}${_boost_MULTITHREADED}${_boost_RELEASE_ABI_TAG}-${Boost_LIB_VERSION}
+    ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${_boost_COMPILER}${_boost_MULTITHREADED}${_boost_RELEASE_ABI_TAG}
+    ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${_boost_MULTITHREADED}${_boost_RELEASE_ABI_TAG}-${Boost_LIB_VERSION}
+    ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${_boost_MULTITHREADED}${_boost_RELEASE_ABI_TAG}
+    ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT} )
+  if(_boost_STATIC_RUNTIME_WORKAROUND)
+    set(_boost_RELEASE_STATIC_ABI_TAG "-s${_boost_RELEASE_ABI_TAG}")
+    list(APPEND _boost_RELEASE_NAMES
+      ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${_boost_COMPILER}${_boost_MULTITHREADED}${_boost_RELEASE_STATIC_ABI_TAG}-${Boost_LIB_VERSION}
+      ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${_boost_COMPILER}${_boost_MULTITHREADED}${_boost_RELEASE_STATIC_ABI_TAG}
+      ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${_boost_MULTITHREADED}${_boost_RELEASE_STATIC_ABI_TAG}-${Boost_LIB_VERSION}
+      ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${_boost_MULTITHREADED}${_boost_RELEASE_STATIC_ABI_TAG} )
+  endif()
+  if(Boost_THREADAPI AND ${COMPONENT} STREQUAL "thread")
+     _Boost_PREPEND_LIST_WITH_THREADAPI(_boost_RELEASE_NAMES ${_boost_RELEASE_NAMES})
+  endif()
+  if(Boost_DEBUG)
+    message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
+                   "Searching for ${UPPERCOMPONENT}_LIBRARY_RELEASE: ${_boost_RELEASE_NAMES}")
+  endif()
+
+  # if Boost_LIBRARY_DIR_RELEASE is not defined,
+  # but Boost_LIBRARY_DIR_DEBUG is, look there first for RELEASE libs
+  if(NOT Boost_LIBRARY_DIR_RELEASE AND Boost_LIBRARY_DIR_DEBUG)
+    list(INSERT _boost_LIBRARY_SEARCH_DIRS_RELEASE 0 ${Boost_LIBRARY_DIR_DEBUG})
+  endif()
+
+  # Avoid passing backslashes to _Boost_FIND_LIBRARY due to macro re-parsing.
+  string(REPLACE "\\" "/" _boost_LIBRARY_SEARCH_DIRS_tmp "${_boost_LIBRARY_SEARCH_DIRS_RELEASE}")
+
+  _Boost_FIND_LIBRARY(Boost_${UPPERCOMPONENT}_LIBRARY_RELEASE RELEASE
+    NAMES ${_boost_RELEASE_NAMES}
+    HINTS ${_boost_LIBRARY_SEARCH_DIRS_tmp}
+    NAMES_PER_DIR
+    DOC "${_boost_docstring_release}"
+    )
+
+  #
+  # Find DEBUG libraries
+  #
+  set(_boost_DEBUG_NAMES
+    ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${_boost_COMPILER}${_boost_MULTITHREADED}${_boost_DEBUG_ABI_TAG}-${Boost_LIB_VERSION}
+    ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${_boost_COMPILER}${_boost_MULTITHREADED}${_boost_DEBUG_ABI_TAG}
+    ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${_boost_MULTITHREADED}${_boost_DEBUG_ABI_TAG}-${Boost_LIB_VERSION}
+    ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${_boost_MULTITHREADED}${_boost_DEBUG_ABI_TAG}
+    ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${_boost_MULTITHREADED}
+    ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT} )
+  if(_boost_STATIC_RUNTIME_WORKAROUND)
+    set(_boost_DEBUG_STATIC_ABI_TAG "-s${_boost_DEBUG_ABI_TAG}")
+    list(APPEND _boost_DEBUG_NAMES
+      ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${_boost_COMPILER}${_boost_MULTITHREADED}${_boost_DEBUG_STATIC_ABI_TAG}-${Boost_LIB_VERSION}
+      ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${_boost_COMPILER}${_boost_MULTITHREADED}${_boost_DEBUG_STATIC_ABI_TAG}
+      ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${_boost_MULTITHREADED}${_boost_DEBUG_STATIC_ABI_TAG}-${Boost_LIB_VERSION}
+      ${Boost_LIB_PREFIX}${Boost_NAMESPACE}_${COMPONENT}${_boost_MULTITHREADED}${_boost_DEBUG_STATIC_ABI_TAG} )
+  endif()
+  if(Boost_THREADAPI AND ${COMPONENT} STREQUAL "thread")
+     _Boost_PREPEND_LIST_WITH_THREADAPI(_boost_DEBUG_NAMES ${_boost_DEBUG_NAMES})
+  endif()
+  if(Boost_DEBUG)
+    message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
+                   "Searching for ${UPPERCOMPONENT}_LIBRARY_DEBUG: ${_boost_DEBUG_NAMES}")
+  endif()
+
+  # if Boost_LIBRARY_DIR_DEBUG is not defined,
+  # but Boost_LIBRARY_DIR_RELEASE is, look there first for DEBUG libs
+  if(NOT Boost_LIBRARY_DIR_DEBUG AND Boost_LIBRARY_DIR_RELEASE)
+    list(INSERT _boost_LIBRARY_SEARCH_DIRS_DEBUG 0 ${Boost_LIBRARY_DIR_RELEASE})
+  endif()
+
+  # Avoid passing backslashes to _Boost_FIND_LIBRARY due to macro re-parsing.
+  string(REPLACE "\\" "/" _boost_LIBRARY_SEARCH_DIRS_tmp "${_boost_LIBRARY_SEARCH_DIRS_DEBUG}")
+
+  _Boost_FIND_LIBRARY(Boost_${UPPERCOMPONENT}_LIBRARY_DEBUG DEBUG
+    NAMES ${_boost_DEBUG_NAMES}
+    HINTS ${_boost_LIBRARY_SEARCH_DIRS_tmp}
+    NAMES_PER_DIR
+    DOC "${_boost_docstring_debug}"
+    )
+
+  if(Boost_REALPATH)
+    _Boost_SWAP_WITH_REALPATH(Boost_${UPPERCOMPONENT}_LIBRARY_RELEASE "${_boost_docstring_release}")
+    _Boost_SWAP_WITH_REALPATH(Boost_${UPPERCOMPONENT}_LIBRARY_DEBUG   "${_boost_docstring_debug}"  )
+  endif()
+
+  _Boost_ADJUST_LIB_VARS(${UPPERCOMPONENT})
+
+endforeach()
+
+# Restore the original find library ordering
+if( Boost_USE_STATIC_LIBS )
+  set(CMAKE_FIND_LIBRARY_SUFFIXES ${_boost_ORIG_CMAKE_FIND_LIBRARY_SUFFIXES})
+endif()
+
+# ------------------------------------------------------------------------
+#  End finding boost libraries
+# ------------------------------------------------------------------------
+
+set(Boost_INCLUDE_DIRS ${Boost_INCLUDE_DIR})
+set(Boost_LIBRARY_DIRS)
+if(Boost_LIBRARY_DIR_RELEASE)
+  list(APPEND Boost_LIBRARY_DIRS ${Boost_LIBRARY_DIR_RELEASE})
+endif()
+if(Boost_LIBRARY_DIR_DEBUG)
+  list(APPEND Boost_LIBRARY_DIRS ${Boost_LIBRARY_DIR_DEBUG})
+endif()
+if(Boost_LIBRARY_DIRS)
+  list(REMOVE_DUPLICATES Boost_LIBRARY_DIRS)
+endif()
+
+# The above setting of Boost_FOUND was based only on the header files.
+# Update it for the requested component libraries.
+if(Boost_FOUND)
+  # The headers were found.  Check for requested component libs.
+  set(_boost_CHECKED_COMPONENT FALSE)
+  set(_Boost_MISSING_COMPONENTS "")
+  foreach(COMPONENT ${Boost_FIND_COMPONENTS})
+    string(TOUPPER ${COMPONENT} COMPONENT)
+    set(_boost_CHECKED_COMPONENT TRUE)
+    if(NOT Boost_${COMPONENT}_FOUND)
+      string(TOLOWER ${COMPONENT} COMPONENT)
+      list(APPEND _Boost_MISSING_COMPONENTS ${COMPONENT})
+    endif()
+  endforeach()
+
+  if(Boost_DEBUG)
+    message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] Boost_FOUND = ${Boost_FOUND}")
+  endif()
+
+  if (_Boost_MISSING_COMPONENTS)
+    set(Boost_FOUND 0)
+    # We were unable to find some libraries, so generate a sensible
+    # error message that lists the libraries we were unable to find.
+    set(Boost_ERROR_REASON
+      "${Boost_ERROR_REASON}\nCould not find the following")
+    if(Boost_USE_STATIC_LIBS)
+      set(Boost_ERROR_REASON "${Boost_ERROR_REASON} static")
+    endif()
+    set(Boost_ERROR_REASON
+      "${Boost_ERROR_REASON} Boost libraries:\n")
+    foreach(COMPONENT ${_Boost_MISSING_COMPONENTS})
+      set(Boost_ERROR_REASON
+        "${Boost_ERROR_REASON}        ${Boost_NAMESPACE}_${COMPONENT}\n")
+    endforeach()
+
+    list(LENGTH Boost_FIND_COMPONENTS Boost_NUM_COMPONENTS_WANTED)
+    list(LENGTH _Boost_MISSING_COMPONENTS Boost_NUM_MISSING_COMPONENTS)
+    if (${Boost_NUM_COMPONENTS_WANTED} EQUAL ${Boost_NUM_MISSING_COMPONENTS})
+      set(Boost_ERROR_REASON
+        "${Boost_ERROR_REASON}No Boost libraries were found. You may need to set BOOST_LIBRARYDIR to the directory containing Boost libraries or BOOST_ROOT to the location of Boost.")
+    else ()
+      set(Boost_ERROR_REASON
+        "${Boost_ERROR_REASON}Some (but not all) of the required Boost libraries were found. You may need to install these additional Boost libraries. Alternatively, set BOOST_LIBRARYDIR to the directory containing Boost libraries or BOOST_ROOT to the location of Boost.")
+    endif ()
+  endif ()
+
+  if( NOT Boost_LIBRARY_DIRS AND NOT _boost_CHECKED_COMPONENT )
+    # Compatibility Code for backwards compatibility with CMake
+    # 2.4's FindBoost module.
+
+    # Look for the boost library path.
+    # Note that the user may not have installed any libraries
+    # so it is quite possible the Boost_LIBRARY_DIRS may not exist.
+    set(_boost_LIB_DIR ${Boost_INCLUDE_DIR})
+
+    if("${_boost_LIB_DIR}" MATCHES "boost-[0-9]+")
+      get_filename_component(_boost_LIB_DIR ${_boost_LIB_DIR} PATH)
+    endif()
+
+    if("${_boost_LIB_DIR}" MATCHES "/include$")
+      # Strip off the trailing "/include" in the path.
+      get_filename_component(_boost_LIB_DIR ${_boost_LIB_DIR} PATH)
+    endif()
+
+    if(EXISTS "${_boost_LIB_DIR}/lib")
+      set(_boost_LIB_DIR ${_boost_LIB_DIR}/lib)
+    else()
+      if(EXISTS "${_boost_LIB_DIR}/stage/lib")
+        set(_boost_LIB_DIR ${_boost_LIB_DIR}/stage/lib)
+      else()
+        set(_boost_LIB_DIR "")
+      endif()
+    endif()
+
+    if(_boost_LIB_DIR AND EXISTS "${_boost_LIB_DIR}")
+      set(Boost_LIBRARY_DIRS ${_boost_LIB_DIR})
+    endif()
+
+  endif()
+else()
+  # Boost headers were not found so no components were found.
+  foreach(COMPONENT ${Boost_FIND_COMPONENTS})
+    string(TOUPPER ${COMPONENT} UPPERCOMPONENT)
+    set(Boost_${UPPERCOMPONENT}_FOUND 0)
+  endforeach()
+endif()
+
+# ------------------------------------------------------------------------
+#  Notification to end user about what was found
+# ------------------------------------------------------------------------
+
+set(Boost_LIBRARIES "")
+if(Boost_FOUND)
+  if(NOT Boost_FIND_QUIETLY)
+    message(STATUS "Boost version: ${Boost_MAJOR_VERSION}.${Boost_MINOR_VERSION}.${Boost_SUBMINOR_VERSION}")
+    if(Boost_FIND_COMPONENTS)
+      message(STATUS "Found the following Boost libraries:")
+    endif()
+  endif()
+  foreach( COMPONENT  ${Boost_FIND_COMPONENTS} )
+    string( TOUPPER ${COMPONENT} UPPERCOMPONENT )
+    if( Boost_${UPPERCOMPONENT}_FOUND )
+      if(NOT Boost_FIND_QUIETLY)
+        message (STATUS "  ${COMPONENT}")
+      endif()
+      list(APPEND Boost_LIBRARIES ${Boost_${UPPERCOMPONENT}_LIBRARY})
+    endif()
+  endforeach()
+else()
+  if(Boost_FIND_REQUIRED)
+    message(SEND_ERROR "Unable to find the requested Boost libraries.\n${Boost_ERROR_REASON}")
+  else()
+    if(NOT Boost_FIND_QUIETLY)
+      # we opt not to automatically output Boost_ERROR_REASON here as
+      # it could be quite lengthy and somewhat imposing in its requests
+      # Since Boost is not always a required dependency we'll leave this
+      # up to the end-user.
+      if(Boost_DEBUG OR Boost_DETAILED_FAILURE_MSG)
+        message(STATUS "Could NOT find Boost\n${Boost_ERROR_REASON}")
+      else()
+        message(STATUS "Could NOT find Boost")
+      endif()
+    endif()
+  endif()
+endif()
+
+# Configure display of cache entries in GUI.
+foreach(v BOOSTROOT BOOST_ROOT ${_Boost_VARS_INC} ${_Boost_VARS_LIB})
+  get_property(_type CACHE ${v} PROPERTY TYPE)
+  if(_type)
+    set_property(CACHE ${v} PROPERTY ADVANCED 1)
+    if("x${_type}" STREQUAL "xUNINITIALIZED")
+      if("x${v}" STREQUAL "xBoost_ADDITIONAL_VERSIONS")
+        set_property(CACHE ${v} PROPERTY TYPE STRING)
+      else()
+        set_property(CACHE ${v} PROPERTY TYPE PATH)
+      endif()
+    endif()
+  endif()
+endforeach()
+
+# Record last used values of input variables so we can
+# detect on the next run if the user changed them.
+foreach(v
+    ${_Boost_VARS_INC} ${_Boost_VARS_LIB}
+    ${_Boost_VARS_DIR} ${_Boost_VARS_NAME}
+    )
+  if(DEFINED ${v})
+    set(_${v}_LAST "${${v}}" CACHE INTERNAL "Last used ${v} value.")
+  else()
+    unset(_${v}_LAST CACHE)
+  endif()
+endforeach()
+
+# Maintain a persistent list of components requested anywhere since
+# the last flush.
+set(_Boost_COMPONENTS_SEARCHED "${_Boost_COMPONENTS_SEARCHED}")
+list(APPEND _Boost_COMPONENTS_SEARCHED ${Boost_FIND_COMPONENTS})
+list(REMOVE_DUPLICATES _Boost_COMPONENTS_SEARCHED)
+list(SORT _Boost_COMPONENTS_SEARCHED)
+set(_Boost_COMPONENTS_SEARCHED "${_Boost_COMPONENTS_SEARCHED}"
+  CACHE INTERNAL "Components requested for this build tree.")
diff --git a/Code/Mantid/Build/CMake/GNUSetup.cmake b/Code/Mantid/Build/CMake/GNUSetup.cmake
index 67b373b55a4bbe10b4e764cc16480e1ae960fa87..a29236d2fcfa9f947767ad27d78256c5f80076e7 100644
--- a/Code/Mantid/Build/CMake/GNUSetup.cmake
+++ b/Code/Mantid/Build/CMake/GNUSetup.cmake
@@ -37,9 +37,19 @@ endif()
 set( CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -fno-omit-frame-pointer" )
 set( CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -fno-omit-frame-pointer" )
 
+option(WITH_ASAN "Enable address sanitizer" OFF)
+if(WITH_ASAN)
+  message(STATUS "enabling address sanitizer")
+  add_compile_options(-fno-omit-frame-pointer -fno-common -fsanitize=address)
+  set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -fsanitize=address -lasan" )
+  set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fsanitize=address -lasan" )
+  set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -fsanitize=address -lasan" )
+endif()
+
 # Set the options for gcc and g++
 set( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${GNUFLAGS}" )
 # -Wno-overloaded-virtual is down here because it's not applicable to the C_FLAGS
 set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${GNUFLAGS} -Woverloaded-virtual -fno-operator-names -std=c++0x" )
+
 # Cleanup
 set ( GNUFLAGS )
diff --git a/Code/Mantid/Build/CMake/LinuxPackageScripts.cmake b/Code/Mantid/Build/CMake/LinuxPackageScripts.cmake
index 9a642a4d49bb2faf4bc79f8b623b99ef2d260d6e..2b7042f5e0abb18ce6ca819fbd63dc510be6e08e 100644
--- a/Code/Mantid/Build/CMake/LinuxPackageScripts.cmake
+++ b/Code/Mantid/Build/CMake/LinuxPackageScripts.cmake
@@ -82,11 +82,9 @@ set ( PRE_UNINSTALL_FILE ${CMAKE_CURRENT_BINARY_DIR}/prerm )
 set ( POST_UNINSTALL_FILE ${CMAKE_CURRENT_BINARY_DIR}/postrm )
 
 if ( "${UNIX_DIST}" MATCHES "RedHatEnterprise" OR "${UNIX_DIST}" MATCHES "^Fedora" ) # RHEL/Fedora
-  if ( "${UNIX_CODENAME}" MATCHES "Santiago" OR 
-       "${UNIX_CODENAME}" MATCHES "Maipo" ) 
-    set ( WRAPPER_PREFIX "scl enable mantidlibs \"" )
+  if ( "${UNIX_CODENAME}" MATCHES "Santiago" )
+    set ( WRAPPER_PREFIX "scl enable mantidlibs34 \"" )
     set ( WRAPPER_POSTFIX "\"" )
-    set ( EXTRA_LDPATH "/usr/lib64/paraview" )
   else()
     set ( WRAPPER_PREFIX "" )
     set ( WRAPPER_POSTFIX "" )
@@ -130,21 +128,23 @@ endif()
 # MantidPlot launcher script
 ############################################################################
 # Local dev version
+set ( EXTRA_LDPATH "${ParaView_DIR}/lib" )
 set ( MANTIDPLOT_EXEC MantidPlot )
-configure_file ( ${CMAKE_MODULE_PATH}/Packaging/launch_mantidplot.sh.in 
+configure_file ( ${CMAKE_MODULE_PATH}/Packaging/launch_mantidplot.sh.in
                  ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/launch_mantidplot.sh @ONLY )
 # Needs to be executable
 execute_process ( COMMAND "chmod" "+x" "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/launch_mantidplot.sh"
                   OUTPUT_QUIET ERROR_QUIET )
-configure_file ( ${CMAKE_MODULE_PATH}/Packaging/mantidpython.in 
+configure_file ( ${CMAKE_MODULE_PATH}/Packaging/mantidpython.in
                  ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/mantidpython @ONLY )
 # Needs to be executable
 execute_process ( COMMAND "chmod" "+x" "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/mantidpython"
                   OUTPUT_QUIET ERROR_QUIET )
 
 # Package version
+set ( EXTRA_LDPATH "\${INSTALLDIR}/../lib/paraview-4.3" )
 set ( MANTIDPLOT_EXEC MantidPlot_exe )
-configure_file ( ${CMAKE_MODULE_PATH}/Packaging/launch_mantidplot.sh.in 
+configure_file ( ${CMAKE_MODULE_PATH}/Packaging/launch_mantidplot.sh.in
                  ${CMAKE_CURRENT_BINARY_DIR}/launch_mantidplot.sh.install @ONLY )
 install ( FILES ${CMAKE_CURRENT_BINARY_DIR}/launch_mantidplot.sh.install
           DESTINATION ${BIN_DIR} RENAME launch_mantidplot.sh
@@ -152,7 +152,7 @@ install ( FILES ${CMAKE_CURRENT_BINARY_DIR}/launch_mantidplot.sh.install
           GROUP_EXECUTE GROUP_READ
           WORLD_EXECUTE WORLD_READ
 )
-configure_file ( ${CMAKE_MODULE_PATH}/Packaging/mantidpython.in 
+configure_file ( ${CMAKE_MODULE_PATH}/Packaging/mantidpython.in
                  ${CMAKE_CURRENT_BINARY_DIR}/mantidpython.install @ONLY )
 install ( FILES ${CMAKE_CURRENT_BINARY_DIR}/mantidpython.install
           DESTINATION ${BIN_DIR} RENAME mantidpython
diff --git a/Code/Mantid/Build/CMake/MPISetup.cmake b/Code/Mantid/Build/CMake/MPISetup.cmake
index 617d403709dcc53c31036a9ea1724266592d1ca9..bcc8602360efc199896fe176b4367d9726277fe9 100644
--- a/Code/Mantid/Build/CMake/MPISetup.cmake
+++ b/Code/Mantid/Build/CMake/MPISetup.cmake
@@ -16,18 +16,21 @@ set ( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}" ${MPI_CXX_COMPILE_FLAGS} )
 #set ( CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS}" ${MPI_CXX_LINK_FLAGS} ) 
   
 set ( BOOST_ROOT /usr/lib64/openmpi ) # This is where (boost-)openmpi winds up on rhel6
-find_package ( Boost REQUIRED mpi serialization )
+find_package ( Boost COMPONENTS mpi serialization REQUIRED )
 include_directories( ${Boost_INCLUDE_DIRS} )
-    
+#unset ( BOOST_ROOT )
+
 # Add a definition that's used to guard MPI-specific parts of the main code
 add_definitions ( -DMPI_BUILD )
     
+add_subdirectory( ${CMAKE_CURRENT_SOURCE_DIR}/Testing/SystemTests/scripts )
+    
 # Add the ability to build a 'mantid-mpi' rpm
 set ( CPACK_PACKAGE_NAME mantid-mpi )
 include ( CPackCommon )
 include ( CPackLinuxSetup )
 # Framework dependencies
-set ( CPACK_RPM_PACKAGE_REQUIRES "boost >= 1.34.1,nexus,gsl,glibc,OpenCASCADE-libs-modelling >= 6.3.0,OpenCASCADE-libs-foundation >= 6.3.0,muParser,numpy" )
+set ( CPACK_RPM_PACKAGE_REQUIRES "boost >= 1.34.1,nexus,gsl,glibc,OCE-modeling,OCE-foundation,muParser,numpy" )
 set ( CPACK_RPM_PACKAGE_REQUIRES "${CPACK_RPM_PACKAGE_REQUIRES},poco-crypto,poco-util,poco-xml,poco-net,poco-netssl,poco-foundation" )
 set ( CPACK_RPM_PACKAGE_REQUIRES "${CPACK_RPM_PACKAGE_REQUIRES},gperftools-libs >= 2.0" )
 set ( CPACK_RPM_PACKAGE_REQUIRES "${CPACK_RPM_PACKAGE_REQUIRES},boost-openmpi" )
diff --git a/Code/Mantid/Build/CMake/Packaging/launch_mantidplot.sh.in b/Code/Mantid/Build/CMake/Packaging/launch_mantidplot.sh.in
index 4e2ebe86daa2a069191c01d2b35cfa1fc3605f20..f26493a133120275e42f77fd51c4c9601d39ca29 100644
--- a/Code/Mantid/Build/CMake/Packaging/launch_mantidplot.sh.in
+++ b/Code/Mantid/Build/CMake/Packaging/launch_mantidplot.sh.in
@@ -20,11 +20,7 @@ else
     TCM_RELEASE=${TCMALLOC_RELEASE_RATE}
 fi
 
-# Define paraview information
-PV_PLUGIN_PATH="${INSTALLDIR}/pvplugins/pvplugins"
-
 # Launch
 LD_PRELOAD=${LOCAL_PRELOAD} TCMALLOC_RELEASE_RATE=${TCM_RELEASE} \
     LD_LIBRARY_PATH=${LOCAL_LDPATH} QT_API=pyqt \
-    PV_PLUGIN_PATH=${PV_PLUGIN_PATH} \
     @WRAPPER_PREFIX@$INSTALLDIR/@MANTIDPLOT_EXEC@ $*@WRAPPER_POSTFIX@
diff --git a/Code/Mantid/Build/CMake/ParaViewSetup.cmake b/Code/Mantid/Build/CMake/ParaViewSetup.cmake
index a4114d673e4280c675331bb57cc4e1e1b36241f1..06421815464c194899c27e74855d5813f4781ee8 100644
--- a/Code/Mantid/Build/CMake/ParaViewSetup.cmake
+++ b/Code/Mantid/Build/CMake/ParaViewSetup.cmake
@@ -1,7 +1,7 @@
 # This file will setup some common items that later setups depend on
 
 # Set the version of ParaView that is compatible with the Mantid code base
-set ( COMPATIBLE_PARAVIEW_VERSION "3.98.1" )
+set ( COMPATIBLE_PARAVIEW_VERSION "4.3.1" )
 
 # Set the name of the OSX application as this tends to be different
 set ( OSX_PARAVIEW_APP "paraview.app" )
diff --git a/Code/Mantid/Build/Jenkins/buildscript b/Code/Mantid/Build/Jenkins/buildscript
index 3a8cefa43ff4ae41be2228307a31ba31296e2c68..6018728f2859933ccedfac699a49f520a130543d 100755
--- a/Code/Mantid/Build/Jenkins/buildscript
+++ b/Code/Mantid/Build/Jenkins/buildscript
@@ -4,7 +4,7 @@
 #
 # Notes:
 #
-# WORKSPACE, JOB_NAME, NODE_LABEL GIT_COMMIT are environment variables that 
+# WORKSPACE, JOB_NAME, NODE_LABEL GIT_COMMIT are environment variables that
 # are set by Jenkins. The last one corresponds to any labels set on a slave.
 # BUILD_THREADS & PARAVIEW_DIR should be set in the configuration of each
 # slave.
@@ -13,6 +13,11 @@ SCRIPT_DIR=$(dirname "$0")
 # Package by default
 BUILDPKG=true
 
+###############################################################################
+# All node currently have PARAVIEW_DIR=3.98.1 and PARAVIEW_NEXT_DIR=4.3.1
+###############################################################################
+export PARAVIEW_DIR=${PARAVIEW_NEXT_DIR}
+
 ###############################################################################
 # Print out the versions of things we are using
 ###############################################################################
@@ -68,7 +73,7 @@ elif [[ $(uname) == 'Darwin' ]] ; then
   if [[ ! $(command -v icpc) ]] ; then
     USE_CLANG=true
   fi
-fi  
+fi
 
 if [[ $USE_CLANG ]]; then
   # Assuming we are using the clang compiler
@@ -77,14 +82,14 @@ if [[ $USE_CLANG ]]; then
   export CC=clang
   export CXX=clang++
   #check if CMakeCache.txt exists and if so that the cxx compiler is clang++
-  #only needed with incremental builds. Clean builds delete this directory in a later step. 
+  #only needed with incremental builds. Clean builds delete this directory in a later step.
   if [[ -e $BUILD_DIR/CMakeCache.txt ]] && [[ ${JOB_NAME} != *clean* ]]; then
-    COMPILERFILEPATH=`grep 'CMAKE_CXX_COMPILER:FILEPATH' $BUILD_DIR/CMakeCache.txt` 
-    if [[ $COMPILERFILEPATH != *clang++* ]]; then 
+    COMPILERFILEPATH=`grep 'CMAKE_CXX_COMPILER:FILEPATH' $BUILD_DIR/CMakeCache.txt`
+    if [[ $COMPILERFILEPATH != *clang++* ]]; then
       # Removing the build directory entirely guarantees clang is used.
       rm -rf $BUILD_DIR
     fi
-  fi 
+  fi
 fi
 
 ###############################################################################
@@ -119,7 +124,7 @@ fi
 # RHEL6 setup steps - nodes must have a "rhel6" label set (in lowercase)
 ###############################################################################
 if [[ ${NODE_LABELS} == *rhel6* ]]; then
-  SCL_ON_RHEL6="scl enable mantidlibs"
+  SCL_ON_RHEL6="scl enable mantidlibs34"
   ON_RHEL6=true
 else
   SCL_ON_RHEL6="eval"
@@ -140,6 +145,8 @@ if [[ "$BUILDPKG" == true ]]; then
       PACKAGINGVARS="-DENVVARS_ON_INSTALL=True -DCPACK_SET_DESTDIR=ON -DPACKAGE_DOCS=ON"
     elif [[ ${JOB_NAME} == *master* ]]; then
       PACKAGINGVARS="-DENVVARS_ON_INSTALL=False -DCMAKE_INSTALL_PREFIX=/opt/mantidnightly -DCPACK_PACKAGE_SUFFIX=nightly -DCPACK_SET_DESTDIR=OFF -DPACKAGE_DOCS=ON"
+    elif [[ ${JOB_NAME} == *pvnext* ]]; then
+      PACKAGINGVARS="-DENVVARS_ON_INSTALL=False -DCMAKE_INSTALL_PREFIX=/opt/mantidunstable-pvnext -DCPACK_PACKAGE_SUFFIX=unstable-pvnext -DCPACK_SET_DESTDIR=OFF"
     else
       PACKAGINGVARS="-DENVVARS_ON_INSTALL=False -DCMAKE_INSTALL_PREFIX=/opt/mantidunstable -DCPACK_PACKAGE_SUFFIX=unstable -DCPACK_SET_DESTDIR=OFF -DPACKAGE_DOCS=ON"
     fi
@@ -169,7 +176,7 @@ $SCL_ON_RHEL6 "cmake -DCMAKE_BUILD_TYPE=${BUILD_CONFIG} -DENABLE_CPACK=ON -DMAKE
 # Coverity build should exit early
 ###############################################################################
 if [[ ${JOB_NAME} == *coverity_build_and_submit* ]]; then
-  ${COVERITY_DIR}/cov-build --dir cov-int scl enable mantidlibs "make -j${BUILD_THREADS}"
+  ${COVERITY_DIR}/cov-build --dir cov-int scl enable mantidlibs34 "make -j${BUILD_THREADS}"
   tar czvf mantid.tgz cov-int
   status=$(curl --form token=$COVERITY_TOKEN --form email=mantidproject@gmail.com \
        --form file=@mantid.tgz --form version=$GIT_COMMIT \
diff --git a/Code/Mantid/Build/Jenkins/buildscript.bat b/Code/Mantid/Build/Jenkins/buildscript.bat
index 36552dbb9a40fc5bd22f2c2f7a1e02f4a306adc9..72ff740bb84e775c3889c8820911d7b97911032f 100755
--- a/Code/Mantid/Build/Jenkins/buildscript.bat
+++ b/Code/Mantid/Build/Jenkins/buildscript.bat
@@ -7,6 +7,12 @@ setlocal enableextensions enabledelayedexpansion
 :: WORKSPACE & JOB_NAME are environment variables that are set by Jenkins.
 :: BUILD_THREADS & PARAVIEW_DIR should be set in the configuration of each slave.
 :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+
+:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+:: All node currently have PARAVIEW_DIR=3.98.1 and PARAVIEW_NEXT_DIR=4.3.1
+:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+set PARAVIEW_DIR=%PARAVIEW_NEXT_DIR%
+
 set CMAKE_BIN_DIR=C:\Program Files (x86)\CMake 2.8\bin
 "%CMAKE_BIN_DIR%\cmake.exe" --version
 echo %sha1%
@@ -161,4 +167,3 @@ if not "%JOB_NAME%"=="%JOB_NAME:pull_requests=%" (
   python !SYSTEMTESTS_DIR!\scripts\mantidinstaller.py uninstall %BUILD_DIR%
   if !RETCODE! NEQ 0 exit /B 1
 )
-
diff --git a/Code/Mantid/Build/Jenkins/jenkins-slave.sh b/Code/Mantid/Build/Jenkins/jenkins-slave.sh
index 494e71e804737b7b5f2dfd2c6ccb4741c5da335c..cb2f03ebc0571077e0ce6dc44b4c674daae477f7 100755
--- a/Code/Mantid/Build/Jenkins/jenkins-slave.sh
+++ b/Code/Mantid/Build/Jenkins/jenkins-slave.sh
@@ -34,12 +34,14 @@ JAR_FILE=slave.jar
 # Some versions of cron don't set the USER environment variable
 # required by vnc
 [ -z "$USER" ] && export USER=$(whoami)
+# Put /usr/local/bin on the PATH if brew is installed
+[ -f /usr/local/bin/brew ] && export PATH=${PATH}:/usr/local/bin
 
 #####################################################################
 # Script
 #####################################################################
 # exit if it is already running
-RUNNING=$(ps u -u $(whoami) | grep java | grep ${JAR_FILE})
+RUNNING=$(ps u -U $(whoami) | grep java | grep ${JAR_FILE})
 if [ ! -z "${RUNNING}" ]; then
   echo "Slave process is already running"
   exit 0
diff --git a/Code/Mantid/Build/Jenkins/systemtests b/Code/Mantid/Build/Jenkins/systemtests
index e955eb7083e95096d51625a776bb43d61ca0d8de..9d1799b24180af97498c02241cd467f9b8b419b1 100755
--- a/Code/Mantid/Build/Jenkins/systemtests
+++ b/Code/Mantid/Build/Jenkins/systemtests
@@ -28,7 +28,7 @@ fi
 # RHEL6 setup steps - nodes must have a "rhel6" label set (in lowercase)
 ###############################################################################
 if [[ ${NODE_LABELS} == *rhel6* ]]; then
-  SCL_ON_RHEL6="scl enable mantidlibs"
+  SCL_ON_RHEL6="scl enable mantidlibs34"
   ON_RHEL6=true
 else
   SCL_ON_RHEL6="eval"
diff --git a/Code/Mantid/Build/dev-packages/rpm/mantid-developer/mantid-developer.spec b/Code/Mantid/Build/dev-packages/rpm/mantid-developer/mantid-developer.spec
index 39a9d019dff3cb93bc6fd1aedb2a0cb8db3ecf91..2ced1066488b81e8409ece1bea07d937dc4f166c 100644
--- a/Code/Mantid/Build/dev-packages/rpm/mantid-developer/mantid-developer.spec
+++ b/Code/Mantid/Build/dev-packages/rpm/mantid-developer/mantid-developer.spec
@@ -57,8 +57,8 @@ Requires: texlive-was
 Requires: tex-preview
 Requires: dvipng
 %if 0%{?el6}
-Requires: mantidlibs-qt-devel
-Requires: mantidlibs-qtwebkit-devel
+Requires: mantidlibs34-qt-devel
+Requires: mantidlibs34-qtwebkit-devel
 Requires: scl-utils
 %else
 Requires: qt-devel
diff --git a/Code/Mantid/CMakeLists.txt b/Code/Mantid/CMakeLists.txt
index 37e8763843f062003919fdb4f80a036305db62e8..f67b7b80837b267830d3294577e4ee0571460fc2 100644
--- a/Code/Mantid/CMakeLists.txt
+++ b/Code/Mantid/CMakeLists.txt
@@ -13,6 +13,9 @@ set ( CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/Build/CMake")
 # Define the project name.
 project ( Mantid )
 
+SET (CPACK_INSTALL_CMAKE_PROJECTS
+     "${CMAKE_BINARY_DIR}" "Mantid" "ALL" "/")
+
 ###########################################################################
 # Quick exit if we only want data targets
 ###########################################################################
@@ -151,6 +154,22 @@ set ( MAKE_VATES OFF CACHE BOOL "Switch for compiling the Vates project")
 
 if ( MAKE_VATES )
   add_subdirectory ( Vates )
+
+  if (NOT APPLE)
+    LIST( APPEND CPACK_INSTALL_CMAKE_PROJECTS
+          "${ParaView_DIR}" "ParaView Runtime Libs" "Runtime" "${INBUNDLE}/"
+    )
+    LIST( APPEND CPACK_INSTALL_CMAKE_PROJECTS
+          "${ParaView_DIR}" "VTK Runtime Libs" "RuntimeLibraries" "${INBUNDLE}/"
+    )
+    LIST( APPEND CPACK_INSTALL_CMAKE_PROJECTS
+          "${ParaView_DIR}" "HDF5 Core Library" "libraries" "${INBUNDLE}/"
+    )
+    LIST( APPEND CPACK_INSTALL_CMAKE_PROJECTS
+          "${ParaView_DIR}" "HDF5 HL Library" "hllibraries" "${INBUNDLE}/"
+    )
+  endif()
+
 endif ( MAKE_VATES )
 
 add_subdirectory ( MantidPlot )
@@ -220,7 +239,7 @@ if ( ENABLE_CPACK )
         # On RHEL6 we have to use an updated qscintilla to fix an auto complete bug
         set ( CPACK_RPM_PACKAGE_REQUIRES "${CPACK_RPM_PACKAGE_REQUIRES} qscintilla >= 2.4.6" )
         # On RHEL6 we are using SCL packages for Qt
-        set ( CPACK_RPM_PACKAGE_REQUIRES "${CPACK_RPM_PACKAGE_REQUIRES},scl-utils,mantidlibs,mantidlibs-runtime,mantidlibs-qt,mantidlibs-qt-x11" )
+        set ( CPACK_RPM_PACKAGE_REQUIRES "${CPACK_RPM_PACKAGE_REQUIRES},scl-utils,mantidlibs34,mantidlibs34-runtime,mantidlibs34-qt,mantidlibs34-qt-x11,mantidlibs34-qt-webkit" )
       else()
         set ( CPACK_RPM_PACKAGE_REQUIRES "${CPACK_RPM_PACKAGE_REQUIRES} qscintilla" )
       endif()
@@ -249,7 +268,7 @@ if ( ENABLE_CPACK )
                                      "libmuparser0debian1,"
                                      "ipython-qtconsole (>= 1.1),python-matplotlib,python-scipy,"
                                      "libpocofoundation9,libpocoutil9,libpoconet9,libpoconetssl9,libpococrypto9,libpocoxml9")
-        elseif( "${UNIX_CODENAME}" STREQUAL "trusty" )
+        elseif( "${UNIX_CODENAME}" STREQUAL "trusty" OR "${UNIX_CODENAME}" STREQUAL "utopic" OR "${UNIX_CODENAME}" STREQUAL "vivid")
           list ( APPEND DEPENDS_LIST ",libqscintilla2-11,"
                                      "liboce-foundation8,liboce-modeling8,"
                                      "libmuparser2,"
diff --git a/Code/Mantid/Framework/API/CMakeLists.txt b/Code/Mantid/Framework/API/CMakeLists.txt
index 8c24cfb88fecc34355c8fad07a0d006103cfc774..cb0f64f204dab590634520d2651c29554c5e17e3 100644
--- a/Code/Mantid/Framework/API/CMakeLists.txt
+++ b/Code/Mantid/Framework/API/CMakeLists.txt
@@ -56,6 +56,7 @@ set ( SRC_FILES
 	src/IFunction1DSpectrum.cpp
 	src/IFunctionMD.cpp
 	src/IFunctionMW.cpp
+	src/ILatticeFunction.cpp
 	src/ILiveListener.cpp
 	src/IMDEventWorkspace.cpp
 	src/IMDHistoWorkspace.cpp
@@ -76,6 +77,7 @@ set ( SRC_FILES
 	src/ImplicitFunctionParserFactory.cpp
 	src/InstrumentDataService.cpp
 	src/JointDomain.cpp
+	src/LatticeDomain.cpp
 	src/LinearScale.cpp
 	src/LiveListenerFactory.cpp
 	src/LogManager.cpp
@@ -212,6 +214,7 @@ set ( INC_FILES
 	inc/MantidAPI/IFunctionMD.h
 	inc/MantidAPI/IFunctionMW.h
 	inc/MantidAPI/IFunctionWithLocation.h
+	inc/MantidAPI/ILatticeFunction.h
 	inc/MantidAPI/ILiveListener.h
 	inc/MantidAPI/IMDEventWorkspace.h
 	inc/MantidAPI/IMDHistoWorkspace.h
@@ -242,6 +245,7 @@ set ( INC_FILES
 	inc/MantidAPI/InstrumentDataService.h
 	inc/MantidAPI/Jacobian.h
 	inc/MantidAPI/JointDomain.h
+	inc/MantidAPI/LatticeDomain.h
 	inc/MantidAPI/LinearScale.h
 	inc/MantidAPI/LiveListenerFactory.h
 	inc/MantidAPI/LogManager.h
@@ -340,6 +344,7 @@ set ( TEST_FILES
 	IFunction1DSpectrumTest.h
 	IFunction1DTest.h
 	IFunctionMDTest.h
+	ILatticeFunctionTest.h
 	ILiveListenerTest.h
 	IMDWorkspaceTest.h
 	ISpectrumTest.h
@@ -348,6 +353,7 @@ set ( TEST_FILES
 	ImplicitFunctionParserFactoryTest.h
 	IncreasingAxisValidatorTest.h
 	InstrumentDataServiceTest.h
+	LatticeDomainTest.h
 	LiveListenerFactoryTest.h
 	LogManagerTest.h
 	MDGeometryTest.h
diff --git a/Code/Mantid/Framework/API/inc/MantidAPI/ILatticeFunction.h b/Code/Mantid/Framework/API/inc/MantidAPI/ILatticeFunction.h
new file mode 100644
index 0000000000000000000000000000000000000000..ec65576109d6a10ba09412df9c207bad46897741
--- /dev/null
+++ b/Code/Mantid/Framework/API/inc/MantidAPI/ILatticeFunction.h
@@ -0,0 +1,74 @@
+#ifndef MANTID_API_ILATTICEFUNCTION_H_
+#define MANTID_API_ILATTICEFUNCTION_H_
+
+#include "MantidAPI/DllConfig.h"
+#include "MantidAPI/FunctionParameterDecorator.h"
+#include "MantidAPI/LatticeDomain.h"
+#include "MantidGeometry/Crystal/UnitCell.h"
+
+namespace Mantid {
+namespace API {
+
+/** ILatticeFunction
+
+  This abstract class defines the interface for a function that calculates
+  values based on HKL-values and a lattice. Currently the only implementation
+  is CurveFitting::LatticeFunction.
+
+    @author Michael Wedel, Paul Scherrer Institut - SINQ
+    @date 15/04/2015
+
+  Copyright © 2015 PSI-NXMM
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid 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 General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class MANTID_API_DLL ILatticeFunction : public FunctionParameterDecorator {
+public:
+  ILatticeFunction();
+  virtual ~ILatticeFunction() {}
+
+  void function(const FunctionDomain &domain, FunctionValues &values) const;
+  void functionDeriv(const FunctionDomain &domain, Jacobian &jacobian);
+
+  /// Function that should calculate d-values for the HKLs provided in the
+  /// domain.
+  virtual void functionLattice(const LatticeDomain &latticeDomain,
+                               FunctionValues &values) const = 0;
+
+  virtual void functionDerivLattice(const LatticeDomain &latticeDomain,
+                                    Jacobian &jacobian);
+
+  /// A string that names the crystal system.
+  virtual void setCrystalSystem(const std::string &crystalSystem) = 0;
+
+  /// Set the function parameters according to the supplied unit cell.
+  virtual void setUnitCell(const std::string &unitCellString) = 0;
+  /// Overload to set unit cell directly from UnitCell object.
+  virtual void setUnitCell(const Geometry::UnitCell &unitCell) = 0;
+
+  /// Returns a unit cell object created from the function parameters
+  virtual Geometry::UnitCell getUnitCell() const = 0;
+};
+
+typedef boost::shared_ptr<ILatticeFunction> ILatticeFunction_sptr;
+
+} // namespace API
+} // namespace Mantid
+
+#endif /* MANTID_API_ILATTICEFUNCTION_H_ */
diff --git a/Code/Mantid/Framework/API/inc/MantidAPI/LatticeDomain.h b/Code/Mantid/Framework/API/inc/MantidAPI/LatticeDomain.h
new file mode 100644
index 0000000000000000000000000000000000000000..6df77d39914a11068ef786830ce9ecffb4c25ef6
--- /dev/null
+++ b/Code/Mantid/Framework/API/inc/MantidAPI/LatticeDomain.h
@@ -0,0 +1,55 @@
+#ifndef MANTID_API_LATTICEDOMAIN_H_
+#define MANTID_API_LATTICEDOMAIN_H_
+
+#include "MantidAPI/DllConfig.h"
+#include "MantidAPI/FunctionDomain.h"
+#include "MantidKernel/V3D.h"
+
+namespace Mantid {
+namespace API {
+
+/** LatticeDomain
+
+  This domain stores V3D-objects as HKLs instead of double-values. It can be
+  used to refine lattice parameters from HKL/d-pairs.
+
+    @author Michael Wedel, Paul Scherrer Institut - SINQ
+    @date 15/04/2015
+
+  Copyright © 2015 PSI-NXMM
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid 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 General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class MANTID_API_DLL LatticeDomain : public FunctionDomain {
+public:
+  LatticeDomain(const std::vector<Kernel::V3D> &hkls);
+  virtual ~LatticeDomain() {}
+
+  size_t size() const;
+
+  const Kernel::V3D &operator[](size_t i) const;
+
+protected:
+  std::vector<Kernel::V3D> m_hkls;
+};
+
+} // namespace API
+} // namespace Mantid
+
+#endif /* MANTID_API_LATTICEDOMAIN_H_ */
diff --git a/Code/Mantid/Framework/API/inc/MantidAPI/WorkspaceProperty.h b/Code/Mantid/Framework/API/inc/MantidAPI/WorkspaceProperty.h
index a8abf3dcf9ec7ae13340dd10e5612c687fabf0e5..d1bf001ff050a1be0b7e379cd73190bc511e0a52 100644
--- a/Code/Mantid/Framework/API/inc/MantidAPI/WorkspaceProperty.h
+++ b/Code/Mantid/Framework/API/inc/MantidAPI/WorkspaceProperty.h
@@ -78,7 +78,7 @@ class WorkspaceProperty
       public IWorkspaceProperty {
 public:
   /** Constructor.
-  *  Sets the property and workspace names but initialises the workspace pointer
+  *  Sets the property and workspace names but initializes the workspace pointer
   * to null.
   *  @param name :: The name to assign to the property
   *  @param wsName :: The name of the workspace
diff --git a/Code/Mantid/Framework/API/src/Algorithm.cpp b/Code/Mantid/Framework/API/src/Algorithm.cpp
index 4a41e7e1182d395a9c5b5a5caf12883808328c7f..878f4b3abe717291ca545ce5da93526e912e0b94 100644
--- a/Code/Mantid/Framework/API/src/Algorithm.cpp
+++ b/Code/Mantid/Framework/API/src/Algorithm.cpp
@@ -884,7 +884,8 @@ IAlgorithm_sptr Algorithm::fromString(const std::string &input) {
       } catch (boost::bad_lexical_cast &) {
       }
     }
-    IAlgorithm_sptr alg = AlgorithmManager::Instance().create(algName, version);
+    IAlgorithm_sptr alg = AlgorithmManager::Instance().createUnmanaged(algName, version);
+    alg->initialize();
     if (boost::regex_search(input, what, propExp, boost::match_not_null)) {
       std::string _propStr = what[1];
 
diff --git a/Code/Mantid/Framework/API/src/BoxController.cpp b/Code/Mantid/Framework/API/src/BoxController.cpp
index 5b49ba41142d35346e32dcbb60a9eb67385acddb..766d992be19e06ed77fc0a10d71f05d3510fe4c0 100644
--- a/Code/Mantid/Framework/API/src/BoxController.cpp
+++ b/Code/Mantid/Framework/API/src/BoxController.cpp
@@ -251,7 +251,7 @@ void BoxController::fromXMLString(const std::string &xml) {
 
   // Need to make sure that we handle box controllers which did not have the SplitTopInto 
   // attribute 
-  Poco::XML::NodeList* nodes = pBoxElement->getElementsByTagName("SplitTopInto");
+  Poco::AutoPtr<NodeList> nodes = pBoxElement->getElementsByTagName("SplitTopInto");
   if (nodes->length() > 0) {
     s = pBoxElement->getChildElement("SplitTopInto")->innerText();
     if (s.empty()) {
diff --git a/Code/Mantid/Framework/API/src/ILatticeFunction.cpp b/Code/Mantid/Framework/API/src/ILatticeFunction.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..b9c9875567a085bec7ed5db19cf7b8da31773381
--- /dev/null
+++ b/Code/Mantid/Framework/API/src/ILatticeFunction.cpp
@@ -0,0 +1,71 @@
+#include "MantidAPI/ILatticeFunction.h"
+
+namespace Mantid {
+namespace API {
+
+using namespace Geometry;
+
+ILatticeFunction::ILatticeFunction() : FunctionParameterDecorator() {}
+
+/**
+ * Implementation of IFunction::function
+ *
+ * The implementation tries to cast the supplied domain to LatticeDomain,
+ * and calls functionLattice, which needs to be implemented in subclasses.
+ *
+ * @param domain :: A FunctionDomain of type LatticeDomain
+ * @param values :: Function values.
+ */
+void ILatticeFunction::function(const FunctionDomain &domain,
+                                FunctionValues &values) const {
+  try {
+    const LatticeDomain &latticeDomain =
+        dynamic_cast<const LatticeDomain &>(domain);
+
+    functionLattice(latticeDomain, values);
+  }
+  catch (std::bad_cast) {
+    throw std::invalid_argument(
+        "ILatticeFunction expects domain of type LatticeDomain.");
+  }
+}
+
+/**
+ * Implementation of IFunction::functionDeriv
+ *
+ * Just like the function-method, the domain is checked for correct type. If
+ * functionDerivLattice has not been implemented, numerical derivatives are
+ * calculated.
+ *
+ * @param domain :: A FunctionDomain of type LatticeDomain
+ * @param jacobian :: Jacobian matrix
+ */
+void ILatticeFunction::functionDeriv(const FunctionDomain &domain,
+                                     Jacobian &jacobian) {
+  try {
+    const LatticeDomain &latticeDomain =
+        dynamic_cast<const LatticeDomain &>(domain);
+
+    functionDerivLattice(latticeDomain, jacobian);
+  }
+  catch (std::bad_cast) {
+    throw std::invalid_argument(
+        "ILatticeFunction expects domain of type LatticeDomain.");
+  }
+  catch (Kernel::Exception::NotImplementedError) {
+    calNumericalDeriv(domain, jacobian);
+  }
+}
+
+/// Default implementation, throws NotImplementedError.
+void ILatticeFunction::functionDerivLattice(const LatticeDomain &latticeDomain,
+                                            Jacobian &jacobian) {
+  UNUSED_ARG(latticeDomain);
+  UNUSED_ARG(jacobian);
+
+  throw Kernel::Exception::NotImplementedError(
+      "FunctionLatticeDeriv is not implemented for this function.");
+}
+
+} // namespace API
+} // namespace Mantid
diff --git a/Code/Mantid/Framework/API/src/IMDEventWorkspace.cpp b/Code/Mantid/Framework/API/src/IMDEventWorkspace.cpp
index 7e2b05d853f9005f8bf6d5aa412c7fc56f8bf4c0..75ec797f8b7b8382d48a00b37d9dc3018779bca0 100644
--- a/Code/Mantid/Framework/API/src/IMDEventWorkspace.cpp
+++ b/Code/Mantid/Framework/API/src/IMDEventWorkspace.cpp
@@ -11,7 +11,7 @@ namespace API {
 //-----------------------------------------------------------------------------------------------
 /** Empty constructor */
 IMDEventWorkspace::IMDEventWorkspace()
-    : IMDWorkspace(), m_fileNeedsUpdating(false) {}
+    : IMDWorkspace(), MultipleExperimentInfos(), m_fileNeedsUpdating(false) {}
 
 //-----------------------------------------------------------------------------------------------
 /** Copy constructor */
diff --git a/Code/Mantid/Framework/API/src/LatticeDomain.cpp b/Code/Mantid/Framework/API/src/LatticeDomain.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..cff999587ecddf8444834f8625bf4f6eaf207efc
--- /dev/null
+++ b/Code/Mantid/Framework/API/src/LatticeDomain.cpp
@@ -0,0 +1,20 @@
+#include "MantidAPI/LatticeDomain.h"
+#include "MantidKernel/Exception.h"
+namespace Mantid {
+namespace API {
+
+LatticeDomain::LatticeDomain(const std::vector<Kernel::V3D> &hkls)
+    : m_hkls(hkls) {}
+
+size_t LatticeDomain::size() const { return m_hkls.size(); }
+
+const Kernel::V3D &LatticeDomain::operator[](size_t i) const {
+  if (i >= m_hkls.size()) {
+    throw Kernel::Exception::IndexError(i, m_hkls.size() - 1,
+                                        "Index exceeds size of LatticeDomain.");
+  }
+  return m_hkls[i];
+}
+
+} // namespace API
+} // namespace Mantid
diff --git a/Code/Mantid/Framework/API/src/MDGeometry.cpp b/Code/Mantid/Framework/API/src/MDGeometry.cpp
index 5b303f3405054fdc605c265591f6a5a045d11d37..1cc0f96fd307d2cc5b20a13cbfa2797b7c39b0ce 100644
--- a/Code/Mantid/Framework/API/src/MDGeometry.cpp
+++ b/Code/Mantid/Framework/API/src/MDGeometry.cpp
@@ -16,16 +16,16 @@ namespace API {
 /** Constructor
  */
 MDGeometry::MDGeometry()
-    : m_originalWorkspaces(), m_transforms_FromOriginal(),
+    : m_dimensions(), m_originalWorkspaces(), m_origin(), m_transforms_FromOriginal(),
       m_transforms_ToOriginal(),
       m_delete_observer(*this, &MDGeometry::deleteNotificationReceived),
-      m_observingDelete(false), m_Wtransf(3, 3, true) {}
+      m_observingDelete(false), m_Wtransf(3, 3, true), m_basisVectors() {}
 
 //----------------------------------------------------------------------------------------------
 /** Copy Constructor
  */
 MDGeometry::MDGeometry(const MDGeometry &other)
-    : m_originalWorkspaces(), m_origin(other.m_origin),
+    : m_dimensions(), m_originalWorkspaces(), m_origin(other.m_origin),
       m_transforms_FromOriginal(), m_transforms_ToOriginal(),
       m_delete_observer(*this, &MDGeometry::deleteNotificationReceived),
       m_observingDelete(false), m_Wtransf(other.m_Wtransf),
diff --git a/Code/Mantid/Framework/API/test/AlgorithmPropertyTest.h b/Code/Mantid/Framework/API/test/AlgorithmPropertyTest.h
index 5f6edfe417a3fea264827aec9397c95c05c506f8..56a9b45649ff16a0bce439b5f478338ff6d67356 100644
--- a/Code/Mantid/Framework/API/test/AlgorithmPropertyTest.h
+++ b/Code/Mantid/Framework/API/test/AlgorithmPropertyTest.h
@@ -114,7 +114,7 @@ public:
   {
     AlgorithmProperty testProp("CalculateStep");
     TS_ASSERT_EQUALS(testProp.setValue("ComplexSum()"),
-      "AlgorithmManager:: Unable to create algorithm ComplexSum Algorithm not registered ComplexSum");
+      "Algorithm not registered ComplexSum");
   }
 
   void test_Alg_With_An_AlgorithmProperty_Accepts_Another_Algorithm()
diff --git a/Code/Mantid/Framework/API/test/ILatticeFunctionTest.h b/Code/Mantid/Framework/API/test/ILatticeFunctionTest.h
new file mode 100644
index 0000000000000000000000000000000000000000..a1d67bac27580d9c701bc043d5d49c8e42331582
--- /dev/null
+++ b/Code/Mantid/Framework/API/test/ILatticeFunctionTest.h
@@ -0,0 +1,113 @@
+#ifndef MANTID_API_ILATTICEFUNCTIONTEST_H_
+#define MANTID_API_ILATTICEFUNCTIONTEST_H_
+
+#include <cxxtest/TestSuite.h>
+#include <gtest/gtest.h>
+#include <gmock/gmock.h>
+
+#include "MantidAPI/ILatticeFunction.h"
+
+using Mantid::API::ILatticeFunction;
+using Mantid::Kernel::V3D;
+
+using namespace Mantid::API;
+
+using ::testing::_;
+using ::testing::Mock;
+using ::testing::Return;
+
+class ILatticeFunctionTest : public CxxTest::TestSuite {
+public:
+  // This pair of boilerplate methods prevent the suite being created statically
+  // This means the constructor isn't called when running other tests
+  static ILatticeFunctionTest *createSuite() {
+    return new ILatticeFunctionTest();
+  }
+  static void destroySuite(ILatticeFunctionTest *suite) { delete suite; }
+
+  void testFunctionLatticeIsCalled() {
+    /* This test makes sure that functionLattice is called when the correct
+     * domain type is supplied. It uses the mock function defined below.
+     */
+    MockLatticeFunction fn;
+    EXPECT_CALL(fn, functionLattice(_, _)).Times(1);
+
+    LatticeDomain domain(getTestHKLs());
+    FunctionValues values(domain);
+
+    fn.function(domain, values);
+
+    TS_ASSERT(Mock::VerifyAndClearExpectations(&fn));
+  }
+
+  void testFunctionDerivLatticeIsCalled() {
+    /* Just as above, this test checks that functionDerivLattice is called
+     * correctly. In addition to the mocked function, also MockJacobian is used.
+     */
+    MockLatticeFunction fn;
+    EXPECT_CALL(fn, functionDerivLattice(_, _)).Times(1);
+
+    LatticeDomain domain(getTestHKLs());
+    MockJacobian jacobian;
+
+    fn.functionDeriv(domain, jacobian);
+
+    TS_ASSERT(Mock::VerifyAndClearExpectations(&fn));
+  }
+
+  void testWrongDomainTypeThrows() {
+    // This test makes sure that wrong domain types throw an exception.
+    MockLatticeFunction fn;
+
+    MockDomain wrongDomain;
+    EXPECT_CALL(wrongDomain, size()).WillRepeatedly(Return(1));
+    FunctionValues values(wrongDomain);
+
+    TS_ASSERT_THROWS(fn.function(wrongDomain, values), std::invalid_argument);
+
+    MockJacobian jacobian;
+    TS_ASSERT_THROWS(fn.functionDeriv(wrongDomain, jacobian),
+                     std::invalid_argument);
+  }
+
+private:
+  std::vector<V3D> getTestHKLs() {
+    std::vector<V3D> hkls;
+    hkls.push_back(V3D(1, 1, 0));
+
+    return hkls;
+  }
+
+  // Mock function to check whether the correct methods are called
+  class MockLatticeFunction : public ILatticeFunction {
+  public:
+    MockLatticeFunction() : ILatticeFunction() {}
+    ~MockLatticeFunction() {}
+
+    MOCK_CONST_METHOD0(name, std::string());
+    MOCK_CONST_METHOD2(functionLattice,
+                       void(const LatticeDomain &, FunctionValues &));
+
+    MOCK_METHOD2(functionDerivLattice, void(const LatticeDomain &, Jacobian &));
+
+    MOCK_METHOD1(setCrystalSystem, void(const std::string &));
+    MOCK_METHOD1(setUnitCell, void(const std::string &));
+    MOCK_METHOD1(setUnitCell, void(const Mantid::Geometry::UnitCell &));
+    MOCK_CONST_METHOD0(getUnitCell, Mantid::Geometry::UnitCell());
+  };
+
+  // Mock jacobian for being able to test derivative calls
+  class MockJacobian : public Jacobian {
+  public:
+    MOCK_METHOD3(set, void(size_t, size_t, double));
+    MOCK_METHOD2(get, double(size_t, size_t));
+  };
+
+  // Mock domain to simulate a wrong domain type
+  class MockDomain : public FunctionDomain {
+  public:
+    MOCK_CONST_METHOD0(size, size_t());
+  };
+};
+
+#endif /* MANTID_API_ILATTICEFUNCTIONTEST_H_ */
diff --git a/Code/Mantid/Framework/API/test/LatticeDomainTest.h b/Code/Mantid/Framework/API/test/LatticeDomainTest.h
new file mode 100644
index 0000000000000000000000000000000000000000..95c9f318e905e47edef732390c3d1eca433d8f5a
--- /dev/null
+++ b/Code/Mantid/Framework/API/test/LatticeDomainTest.h
@@ -0,0 +1,61 @@
+#ifndef MANTID_API_LATTICEDOMAINTEST_H_
+#define MANTID_API_LATTICEDOMAINTEST_H_
+
+#include <cxxtest/TestSuite.h>
+
+#include "MantidAPI/LatticeDomain.h"
+#include "MantidKernel/Exception.h"
+
+using Mantid::API::LatticeDomain;
+using Mantid::Kernel::V3D;
+using Mantid::Kernel::Exception::IndexError;
+
+using namespace Mantid::API;
+
+class LatticeDomainTest : public CxxTest::TestSuite {
+public:
+  // This pair of boilerplate methods prevent the suite being created statically
+  // This means the constructor isn't called when running other tests
+  static LatticeDomainTest *createSuite() { return new LatticeDomainTest(); }
+  static void destroySuite(LatticeDomainTest *suite) { delete suite; }
+
+  void testConstruction() {
+    std::vector<V3D> hkls;
+    hkls.push_back(V3D(1, 1, 1));
+    hkls.push_back(V3D(2, 1, 0));
+    hkls.push_back(V3D(0, 0, 1));
+
+    TS_ASSERT_THROWS_NOTHING(LatticeDomain domain(hkls));
+
+    std::vector<V3D> empty;
+    TS_ASSERT_THROWS_NOTHING(LatticeDomain domain(empty));
+  }
+
+  void testSize() {
+    std::vector<V3D> hkls;
+    hkls.push_back(V3D(1, 1, 1));
+    hkls.push_back(V3D(2, 1, 0));
+    hkls.push_back(V3D(0, 0, 1));
+
+    LatticeDomain domain(hkls);
+
+    TS_ASSERT_EQUALS(domain.size(), hkls.size());
+  }
+
+  void testAccess() {
+    std::vector<V3D> hkls;
+    hkls.push_back(V3D(1, 1, 1));
+    hkls.push_back(V3D(2, 1, 0));
+    hkls.push_back(V3D(0, 0, 1));
+
+    LatticeDomain domain(hkls);
+
+    TS_ASSERT_THROWS_NOTHING(domain[0]);
+    TS_ASSERT_THROWS_NOTHING(domain[1]);
+    TS_ASSERT_THROWS_NOTHING(domain[2]);
+
+    TS_ASSERT_THROWS(domain[3], IndexError)
+  }
+};
+
+#endif /* MANTID_API_LATTICEDOMAINTEST_H_ */
diff --git a/Code/Mantid/Framework/API/test/WorkspaceHistoryIOTest.h b/Code/Mantid/Framework/API/test/WorkspaceHistoryIOTest.h
index e62fa4a2278c526bf5a37de602627c2fd88f52d5..78c51526bfd96919210f4a8dbc6ad0b7b421f47e 100644
--- a/Code/Mantid/Framework/API/test/WorkspaceHistoryIOTest.h
+++ b/Code/Mantid/Framework/API/test/WorkspaceHistoryIOTest.h
@@ -152,11 +152,15 @@ public:
       testHistory.addHistory(boost::make_shared<AlgorithmHistory>(algHist));
     }
 
+    // clang-format off
     auto savehandle = boost::make_shared< ::NeXus::File >("WorkspaceHistoryTest_test_SaveNexus.nxs",NXACC_CREATE5);
+    // clang-format on
     TS_ASSERT_THROWS_NOTHING(testHistory.saveNexus(savehandle.get()));
     savehandle->close();
 
+    // clang-format off
     auto loadhandle = boost::make_shared< ::NeXus::File >("WorkspaceHistoryTest_test_SaveNexus.nxs");
+    // clang-format on
     std::string rootstring = "/process/";
     for (int i = 1; i < 5; i++)
     {
@@ -181,11 +185,15 @@ public:
     algHist.addChildHistory(boost::make_shared<AlgorithmHistory>(childHist));
     testHistory.addHistory(boost::make_shared<AlgorithmHistory>(algHist));
 
+    // clang-format off
     auto savehandle = boost::make_shared< ::NeXus::File >("WorkspaceHistoryTest_test_SaveNexus.nxs",NXACC_CREATE5);
+    // clang-format on
     TS_ASSERT_THROWS_NOTHING(testHistory.saveNexus(savehandle.get()));
     savehandle->close();
 
+    // clang-format off
     auto loadhandle = boost::make_shared< ::NeXus::File >("WorkspaceHistoryTest_test_SaveNexus.nxs");
+    // clang-format on
     std::string rootstring = "/process/";
     TS_ASSERT_THROWS_NOTHING(loadhandle->openPath(rootstring + "MantidAlgorithm_1/"));
     TS_ASSERT_THROWS_NOTHING(loadhandle->openPath(rootstring + "MantidAlgorithm_1/author"));
@@ -205,11 +213,15 @@ public:
   {
     WorkspaceHistory testHistory;
 
+    // clang-format off
     auto savehandle = boost::make_shared< ::NeXus::File >("WorkspaceHistoryTest_test_SaveNexus.nxs",NXACC_CREATE5);
+    // clang-format on
     TS_ASSERT_THROWS_NOTHING(testHistory.saveNexus(savehandle.get()));
     savehandle->close();
 
+    // clang-format off
     auto loadhandle = boost::make_shared< ::NeXus::File >("WorkspaceHistoryTest_test_SaveNexus.nxs");
+    // clang-format on
     std::string rootstring = "/process/";
     TS_ASSERT_THROWS_NOTHING(loadhandle->openPath(rootstring));
     TS_ASSERT_THROWS_NOTHING(loadhandle->openPath(rootstring + "MantidEnvironment"));
@@ -222,7 +234,9 @@ public:
   void test_LoadNexus()
   {
     std::string filename = FileFinder::Instance().getFullPath("GEM38370_Focussed_Legacy.nxs");
+    // clang-format off
     auto loadhandle = boost::make_shared< ::NeXus::File >(filename);
+    // clang-format on
     loadhandle->openPath("/mantid_workspace_1");
 
     WorkspaceHistory emptyHistory;
@@ -243,7 +257,9 @@ public:
   void test_LoadNexus_NestedHistory()
   {
     std::string filename = FileFinder::Instance().getFullPath("HistoryTest_CreateTransmissionAuto.nxs");
+    // clang-format off
     auto loadhandle = boost::make_shared< ::NeXus::File >(filename);
+    // clang-format on
     loadhandle->openPath("/mantid_workspace_1");
 
     WorkspaceHistory wsHistory;
@@ -368,4 +384,4 @@ public:
   }
 };
 
-#endif
\ No newline at end of file
+#endif
diff --git a/Code/Mantid/Framework/Algorithms/CMakeLists.txt b/Code/Mantid/Framework/Algorithms/CMakeLists.txt
index ea536a1082015bea509940732186af2392dd1408..998032e0216af09c2d044d7207dce14546202df4 100644
--- a/Code/Mantid/Framework/Algorithms/CMakeLists.txt
+++ b/Code/Mantid/Framework/Algorithms/CMakeLists.txt
@@ -52,6 +52,7 @@ set ( SRC_FILES
 	src/ConvertToMatrixWorkspace.cpp
 	src/ConvertToPointData.cpp
 	src/ConvertUnits.cpp
+	src/ConvertUnitsUsingDetectorTable.cpp
 	src/CopyDetectorMapping.cpp
 	src/CopyInstrumentParameters.cpp
 	src/CopyLogs.cpp
@@ -99,6 +100,7 @@ set ( SRC_FILES
 	src/ExtractMask.cpp
 	src/ExtractMaskToTable.cpp
 	src/ExtractSingleSpectrum.cpp
+	src/ExtractSpectra.cpp
 	src/FFT.cpp
 	src/FFTDerivative.cpp
 	src/FFTSmooth.cpp
@@ -197,6 +199,7 @@ set ( SRC_FILES
 	src/RemoveBins.cpp
 	src/RemoveExpDecay.cpp
 	src/RemoveLowResTOF.cpp
+	src/RemoveMaskedSpectra.cpp
 	src/RemovePromptPulse.cpp
 	src/RemoveWorkspaceHistory.cpp
 	src/RenameWorkspace.cpp
@@ -309,6 +312,7 @@ set ( INC_FILES
 	inc/MantidAlgorithms/ConvertToMatrixWorkspace.h
 	inc/MantidAlgorithms/ConvertToPointData.h
 	inc/MantidAlgorithms/ConvertUnits.h
+	inc/MantidAlgorithms/ConvertUnitsUsingDetectorTable.h
 	inc/MantidAlgorithms/CopyDetectorMapping.h
 	inc/MantidAlgorithms/CopyInstrumentParameters.h
 	inc/MantidAlgorithms/CopyLogs.h
@@ -356,6 +360,7 @@ set ( INC_FILES
 	inc/MantidAlgorithms/ExtractMask.h
 	inc/MantidAlgorithms/ExtractMaskToTable.h
 	inc/MantidAlgorithms/ExtractSingleSpectrum.h
+	inc/MantidAlgorithms/ExtractSpectra.h
 	inc/MantidAlgorithms/FFT.h
 	inc/MantidAlgorithms/FFTDerivative.h
 	inc/MantidAlgorithms/FFTSmooth.h
@@ -455,6 +460,7 @@ set ( INC_FILES
 	inc/MantidAlgorithms/RemoveBins.h
 	inc/MantidAlgorithms/RemoveExpDecay.h
 	inc/MantidAlgorithms/RemoveLowResTOF.h
+	inc/MantidAlgorithms/RemoveMaskedSpectra.h
 	inc/MantidAlgorithms/RemovePromptPulse.h
 	inc/MantidAlgorithms/RemoveWorkspaceHistory.h
 	inc/MantidAlgorithms/RenameWorkspace.h
@@ -577,6 +583,7 @@ set ( TEST_FILES
 	ConvertToMatrixWorkspaceTest.h
 	ConvertToPointDataTest.h
 	ConvertUnitsTest.h
+	ConvertUnitsUsingDetectorTableTest.h
 	CopyDetectorMappingTest.h
 	CopyInstrumentParametersTest.h
 	CopyLogsTest.h
@@ -620,6 +627,7 @@ set ( TEST_FILES
 	ExtractMaskTest.h
 	ExtractMaskToTableTest.h
 	ExtractSingleSpectrumTest.h
+	ExtractSpectraTest.h
 	FFTDerivativeTest.h
 	FFTSmooth2Test.h
 	FFTTest.h
@@ -706,6 +714,7 @@ set ( TEST_FILES
 	RemoveBinsTest.h
 	RemoveExpDecayTest.h
 	RemoveLowResTOFTest.h
+	RemoveMaskedSpectraTest.h
 	RemovePromptPulseTest.h
 	RemoveWorkspaceHistoryTest.h
 	RenameWorkspaceTest.h
diff --git a/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/ConvertUnitsUsingDetectorTable.h b/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/ConvertUnitsUsingDetectorTable.h
new file mode 100644
index 0000000000000000000000000000000000000000..02d511f3a46e4a2739843199d00b6fc46176fce5
--- /dev/null
+++ b/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/ConvertUnitsUsingDetectorTable.h
@@ -0,0 +1,83 @@
+#ifndef MANTID_ALGORITHMS_CONVERTUNITSUSINGDETECTORTABLE_H_
+#define MANTID_ALGORITHMS_CONVERTUNITSUSINGDETECTORTABLE_H_
+
+#include "MantidKernel/System.h"
+#include "MantidAPI/Algorithm.h"
+
+namespace Mantid
+{
+namespace Algorithms
+{
+
+  /** ConvertUnitsUsingDetectorTable : Converts the units in which a workspace is represented.
+
+    Copyright &copy; 2015 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+
+    This file is part of Mantid.
+
+    Mantid is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 3 of the License, or
+    (at your option) any later version.
+
+    Mantid 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 General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+    File change history is stored at: <https://github.com/mantidproject/mantid>
+    Code Documentation is available at: <http://doxygen.mantidproject.org>
+  */
+  class DLLExport ConvertUnitsUsingDetectorTable  : public API::Algorithm
+  {
+  public:
+    ConvertUnitsUsingDetectorTable();
+    virtual ~ConvertUnitsUsingDetectorTable();
+    
+    virtual const std::string name() const;
+    virtual int version() const;
+    virtual const std::string category() const;
+    virtual const std::string summary() const;
+
+  private:
+    void init();
+    void exec();
+
+    void setupMemberVariables(const API::MatrixWorkspace_const_sptr inputWS);
+    API::MatrixWorkspace_sptr setupOutputWorkspace(const API::MatrixWorkspace_const_sptr inputWS);
+    void fillOutputHist(const API::MatrixWorkspace_const_sptr inputWS, const API::MatrixWorkspace_sptr outputWS);
+
+    void putBackBinWidth(const API::MatrixWorkspace_sptr outputWS);
+
+
+    /// Convert the workspace units according to a simple output = a * (input^b) relationship
+    void convertQuickly(API::MatrixWorkspace_sptr outputWS, const double& factor, const double& power);
+    /// Convert the workspace units using TOF as an intermediate step in the conversion
+    void convertViaTOF(Kernel::Unit_const_sptr fromUnit, API::MatrixWorkspace_sptr outputWS);
+
+    // Calls Rebin as a Child Algorithm to align the bins of the output workspace
+    API::MatrixWorkspace_sptr alignBins(const API::MatrixWorkspace_sptr workspace);
+    const std::vector<double> calculateRebinParams(const API::MatrixWorkspace_const_sptr workspace) const;
+
+    /// Reverses the workspace if X values are in descending order
+    void reverse(API::MatrixWorkspace_sptr workspace);
+
+    /// For conversions to energy transfer, removes bins corresponding to inaccessible values
+    API::MatrixWorkspace_sptr removeUnphysicalBins(const API::MatrixWorkspace_const_sptr workspace);
+
+    std::size_t m_numberOfSpectra;     ///< The number of spectra in the input workspace
+    bool m_distribution;       ///< Whether input is a distribution. Only applies to histogram workspaces.
+    bool m_inputEvents;        ///< Flag indicating whether input workspace is an EventWorkspace
+    Kernel::Unit_const_sptr m_inputUnit;  ///< The unit of the input workspace
+    Kernel::Unit_sptr m_outputUnit;       ///< The unit we're going to
+
+  };
+
+
+} // namespace Algorithms
+} // namespace Mantid
+
+#endif  /* MANTID_ALGORITHMS_CONVERTUNITSUSINGDETECTORTABLE_H_ */
diff --git a/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/CropWorkspace.h b/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/CropWorkspace.h
index 4ed4b5a03cbe2403829e7c65bb4cfce805e420f4..52c0bc9aa7ea61116191b989a6b375a5eb3fa6bd 100644
--- a/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/CropWorkspace.h
+++ b/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/CropWorkspace.h
@@ -5,9 +5,6 @@
 // Includes
 //----------------------------------------------------------------------
 #include "MantidAPI/Algorithm.h"
-#include "MantidDataObjects/EventWorkspace.h"
-
-#include <climits>
 
 namespace Mantid {
 namespace Algorithms {
@@ -91,31 +88,6 @@ private:
   void init();
   /// Execution code
   void exec();
-  void execEvent();
-
-  void checkProperties();
-  std::size_t getXMin(const int wsIndex = 0);
-  std::size_t getXMax(const int wsIndex = 0);
-  void cropRagged(API::MatrixWorkspace_sptr outputWorkspace, int inIndex,
-                  int outIndex);
-
-  /// The input workspace
-  API::MatrixWorkspace_sptr m_inputWorkspace;
-  DataObjects::EventWorkspace_sptr eventW;
-  /// The bin index to start the cropped workspace from
-  std::size_t m_minX;
-  /// The bin index to end the cropped workspace at
-  std::size_t m_maxX;
-  /// The spectrum index to start the cropped workspace from
-  specid_t m_minSpec;
-  /// The spectrum index to end the cropped workspace at
-  specid_t m_maxSpec;
-  /// Flag indicating whether the input workspace has common boundaries
-  bool m_commonBoundaries;
-  /// Flag indicating whether we're dealing with histogram data
-  bool m_histogram;
-  /// Flag indicating whether XMin and/or XMax has been set
-  bool m_croppingInX;
 };
 
 } // namespace Algorithms
diff --git a/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/ExtractSpectra.h b/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/ExtractSpectra.h
new file mode 100644
index 0000000000000000000000000000000000000000..86fbaaa6a318e599ff36bda49bd235abf9d7b682
--- /dev/null
+++ b/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/ExtractSpectra.h
@@ -0,0 +1,78 @@
+#ifndef MANTID_ALGORITHMS_EXTRACTSPECTRA_H_
+#define MANTID_ALGORITHMS_EXTRACTSPECTRA_H_
+
+#include "MantidKernel/System.h"
+#include "MantidAPI/Algorithm.h"
+#include "MantidDataObjects/EventWorkspace.h"
+
+namespace Mantid {
+namespace Algorithms {
+
+/** Extracts specified spectra from a workspace and places them in a new
+  workspace.
+
+
+  Copyright &copy; 2015 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid 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 General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport ExtractSpectra : public API::Algorithm {
+public:
+  ExtractSpectra();
+  virtual ~ExtractSpectra();
+
+  virtual const std::string name() const;
+  virtual int version() const;
+  virtual const std::string category() const;
+  virtual const std::string summary() const;
+
+private:
+  void init();
+  void exec();
+  void execHistogram();
+  void execEvent();
+
+  void checkProperties();
+  std::size_t getXMin(const int wsIndex = 0);
+  std::size_t getXMax(const int wsIndex = 0);
+  void cropRagged(API::MatrixWorkspace_sptr outputWorkspace, int inIndex,
+                  int outIndex);
+
+  /// The input workspace
+  API::MatrixWorkspace_sptr m_inputWorkspace;
+  DataObjects::EventWorkspace_sptr eventW;
+  /// The bin index to start the cropped workspace from
+  std::size_t m_minX;
+  /// The bin index to end the cropped workspace at
+  std::size_t m_maxX;
+  /// Flag indicating whether the input workspace has common boundaries
+  bool m_commonBoundaries;
+  /// Flag indicating whether we're dealing with histogram data
+  bool m_histogram;
+  /// Flag indicating whether XMin and/or XMax has been set
+  bool m_croppingInX;
+  /// The list of spectra to extract.
+  std::vector<specid_t> m_spectrumList;
+};
+
+} // namespace Algorithms
+} // namespace Mantid
+
+#endif /* MANTID_ALGORITHMS_EXTRACTSPECTRA_H_ */
\ No newline at end of file
diff --git a/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/PlotAsymmetryByLogValue.h b/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/PlotAsymmetryByLogValue.h
index d743d1c93a7a7960333f6e5c2dac94bf06598a49..ee102609209f23ec59711321bfa3c77b9642baea 100644
--- a/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/PlotAsymmetryByLogValue.h
+++ b/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/PlotAsymmetryByLogValue.h
@@ -84,8 +84,6 @@ private:
   void doAnalysis (API::Workspace_sptr loadedWs, int64_t index);
   // Parse run names
   void parseRunNames (std::string& firstFN, std::string& lastFN, std::string& fnBase, std::string& fnExt, int& fnZeros);
-  // Resize vectors
-  void resizeVectors (size_t size);
   // Load dead-time corrections from specified file
   void loadCorrectionsFromFile (API::Workspace_sptr &customDeadTimes, std::string deadTimeFile );
   // Apply dead-time corrections
@@ -102,40 +100,60 @@ private:
   double getLogValue(API::MatrixWorkspace &ws);
   /// Populate output workspace with results
   void populateOutputWorkspace (API::MatrixWorkspace_sptr &outWS, int nplots);
+  /// Check input properties
+  void checkProperties (size_t &is, size_t &ie);
+  /// Clear previous results
+  void clearResultsFromTo (size_t is, size_t ie);
 
   /// Stores base name shared by all runs
-  std::string m_filenameBase;
+  static std::string g_filenameBase;
   /// Stores extension shared by all runs
-  std::string m_filenameExt;
+  static std::string g_filenameExt;
   /// Sotres number of zeros in run name
-  int m_filenameZeros;
+  static int g_filenameZeros;
   /// Stores property "Int"
   bool m_int;
   /// Store forward spectra
-  std::vector<int> m_forward_list;
+  static std::vector<int> g_forward_list;
   /// Store backward spectra
-  std::vector<int> m_backward_list;
+  static std::vector<int> g_backward_list;
   /// If true call LoadMuonNexus with Autogroup on
   bool m_autogroup;
   /// Store type of dead time corrections
-  std::string m_dtcType;
+  static std::string g_dtcType;
+  /// File to read corrections from
+  static std::string g_dtcFile;
   /// Store red period
-  int m_red;
+  static int g_red;
   /// Store green period
-  int m_green;
+  static int g_green;
   // Mantid vectors to store results
   // Red mantid vectors
-  MantidVec m_redX, m_redY, m_redE;
+  static std::map<int64_t, double> g_redX;
+  static std::map<int64_t, double> g_redY;
+  static std::map<int64_t, double> g_redE;
   // Green mantid vectors
-  MantidVec m_greenX, m_greenY, m_greenE;
+  static std::map<int64_t, double> g_greenX;
+  static std::map<int64_t, double> g_greenY;
+  static std::map<int64_t, double> g_greenE;
   // Mantid vectors to store Red + Green
-  MantidVec m_sumX, m_sumY, m_sumE;
+  static std::map<int64_t, double> g_sumX;
+  static std::map<int64_t, double> g_sumY;
+  static std::map<int64_t, double> g_sumE;
   // Mantid vectors to store Red - Green
-  MantidVec m_diffX, m_diffY, m_diffE;
+  static std::map<int64_t, double> g_diffX;
+  static std::map<int64_t, double> g_diffY;
+  static std::map<int64_t, double> g_diffE;
   // LogValue name
-  std::string m_logName;
+  static std::string g_logName;
   // LogValue function
-  std::string m_logFunc;
+  static std::string g_logFunc;
+  // Type of computation: integral or differential
+  static std::string g_stype;
+  // Minimum time for the analysis
+  static double g_minTime;
+  // Maximum time for the analysis
+  static double g_maxTime;
 };
 
 } // namespace Algorithm
diff --git a/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/RemoveMaskedSpectra.h b/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/RemoveMaskedSpectra.h
new file mode 100644
index 0000000000000000000000000000000000000000..03354c75b5bd4eaf64be9bc204261171496cd2c8
--- /dev/null
+++ b/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/RemoveMaskedSpectra.h
@@ -0,0 +1,53 @@
+#ifndef MANTID_ALGORITHMS_REMOVEMASKEDSPECTRA_H_
+#define MANTID_ALGORITHMS_REMOVEMASKEDSPECTRA_H_
+
+#include "MantidKernel/System.h"
+#include "MantidAPI/Algorithm.h"
+
+namespace Mantid {
+namespace Algorithms {
+
+/** RemoveMaskedSpectra removes all masked spectra.
+
+  Copyright &copy; 2015 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid 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 General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport RemoveMaskedSpectra : public API::Algorithm {
+public:
+  RemoveMaskedSpectra();
+  virtual ~RemoveMaskedSpectra();
+
+  virtual const std::string name() const;
+  virtual int version() const;
+  virtual const std::string category() const;
+  virtual const std::string summary() const;
+
+private:
+  void init();
+  void exec();
+  void makeIndexList(std::vector<specid_t> &indices,
+                     const API::MatrixWorkspace *maskedWorkspace);
+};
+
+} // namespace Algorithms
+} // namespace Mantid
+
+#endif /* MANTID_ALGORITHMS_REMOVEMASKEDSPECTRA_H_ */
\ No newline at end of file
diff --git a/Code/Mantid/Framework/Algorithms/src/ConvertUnitsUsingDetectorTable.cpp b/Code/Mantid/Framework/Algorithms/src/ConvertUnitsUsingDetectorTable.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..c8447407931b792bd825d043a7be83db28ab16f5
--- /dev/null
+++ b/Code/Mantid/Framework/Algorithms/src/ConvertUnitsUsingDetectorTable.cpp
@@ -0,0 +1,701 @@
+#include "MantidAlgorithms/ConvertUnitsUsingDetectorTable.h"
+
+#include "MantidAPI/ITableWorkspace.h"
+#include "MantidAPI/AlgorithmFactory.h"
+
+#include "MantidKernel/ListValidator.h"
+#include "MantidKernel/UnitFactory.h"
+
+
+#include "MantidAlgorithms/ConvertUnitsUsingDetectorTable.h"
+#include "MantidAPI/WorkspaceValidators.h"
+#include "MantidAPI/ITableWorkspace.h"
+#include "MantidAPI/AlgorithmFactory.h"
+#include "MantidAPI/Run.h"
+#include "MantidKernel/UnitFactory.h"
+#include "MantidDataObjects/Workspace2D.h"
+#include "MantidDataObjects/TableWorkspace.h"
+#include "MantidDataObjects/EventWorkspace.h"
+#include <boost/function.hpp>
+#include <boost/bind.hpp>
+#include <boost/math/special_functions/fpclassify.hpp>
+#include <cfloat>
+#include <iostream>
+#include <limits>
+#include "MantidKernel/BoundedValidator.h"
+#include "MantidKernel/ListValidator.h"
+
+namespace Mantid
+{
+namespace Algorithms
+{
+
+  using Mantid::Kernel::Direction;
+  using Mantid::API::WorkspaceProperty;
+  using namespace Kernel;
+  using namespace API;
+  using namespace DataObjects;
+  using boost::function;
+  using boost::bind;
+
+  // Register the algorithm into the AlgorithmFactory
+  DECLARE_ALGORITHM(ConvertUnitsUsingDetectorTable)
+
+
+
+  //----------------------------------------------------------------------------------------------
+  /** Constructor
+   */
+  ConvertUnitsUsingDetectorTable::ConvertUnitsUsingDetectorTable() : Algorithm(),
+      m_numberOfSpectra(0), m_distribution(false), m_inputEvents(false)
+  {
+  }
+
+  //----------------------------------------------------------------------------------------------
+  /** Destructor
+   */
+  ConvertUnitsUsingDetectorTable::~ConvertUnitsUsingDetectorTable()
+  {
+  }
+
+
+  //----------------------------------------------------------------------------------------------
+
+  /// Algorithms name for identification. @see Algorithm::name
+  const std::string ConvertUnitsUsingDetectorTable::name() const { return "ConvertUnitsUsingDetectorTable"; }
+
+  /// Algorithm's version for identification. @see Algorithm::version
+  int ConvertUnitsUsingDetectorTable::version() const { return 1;}
+
+  /// Algorithm's category for identification. @see Algorithm::category
+  const std::string ConvertUnitsUsingDetectorTable::category() const { return "Utility\\Development";}
+
+  /// Algorithm's summary for use in the GUI and help. @see Algorithm::summary
+  const std::string ConvertUnitsUsingDetectorTable::summary() const { return " *** Warning - This Routine is under development *** \n"
+                                                                             "Performs a unit change on the X values of a workspace";}
+
+  //----------------------------------------------------------------------------------------------
+  /** Initialize the algorithm's properties.
+   */
+  void ConvertUnitsUsingDetectorTable::init()
+  {
+    declareProperty(new WorkspaceProperty<>("InputWorkspace","",Direction::Input), "An input workspace.");
+    declareProperty(new WorkspaceProperty<>("OutputWorkspace","",Direction::Output), "An output workspace.");
+    declareProperty("Target","",boost::make_shared<StringListValidator>(UnitFactory::Instance().getKeys()),
+                    "The name of the units to convert to (must be one of those registered in\n"
+                    "the Unit Factory)");
+    declareProperty(new WorkspaceProperty<ITableWorkspace>("DetectorParameters", "", Direction::Input, PropertyMode::Optional),
+                    "Name of a TableWorkspace containing the detector parameters to use instead of the IDF.");
+
+    // TODO: Do we need this ?
+    declareProperty("AlignBins",false,
+        "If true (default is false), rebins after conversion to ensure that all spectra in the output workspace\n"
+        "have identical bin boundaries. This option is not recommended (see http://www.mantidproject.org/ConvertUnits).");
+  }
+
+  //----------------------------------------------------------------------------------------------
+  /** Execute the algorithm.
+   */
+  void ConvertUnitsUsingDetectorTable::exec()
+  {
+      // Get the workspaces
+      MatrixWorkspace_sptr inputWS = getProperty("InputWorkspace");
+      this->setupMemberVariables(inputWS);
+
+      if (m_inputUnit->unitID() == m_outputUnit->unitID())
+      {
+          const std::string outputWSName = getPropertyValue("OutputWorkspace");
+          const std::string inputWSName = getPropertyValue("InputWorkspace");
+          if (outputWSName == inputWSName)
+          {
+              // If it does, just set the output workspace to point to the input one and be done.
+              g_log.information() << "Input workspace already has target unit (" << m_outputUnit->unitID() << "), so just pointing the output workspace property to the input workspace."<< std::endl;
+              setProperty("OutputWorkspace", boost::const_pointer_cast<MatrixWorkspace>(inputWS));
+              return;
+          }
+          else
+          {
+              // Clone the workspace.
+              IAlgorithm_sptr duplicate = createChildAlgorithm("CloneWorkspace",0.0,0.6);
+              duplicate->initialize();
+              duplicate->setProperty("InputWorkspace",  inputWS);
+              duplicate->execute();
+              Workspace_sptr temp = duplicate->getProperty("OutputWorkspace");
+              auto outputWs = boost::dynamic_pointer_cast<MatrixWorkspace>(temp);
+              setProperty("OutputWorkspace", outputWs);
+              return;
+          }
+      }
+
+      if (inputWS->dataX(0).size() < 2)
+      {
+          std::stringstream msg;
+          msg << "Input workspace has invalid X axis binning parameters. Should have at least 2 values. Found "
+              << inputWS->dataX(0).size() << ".";
+          throw std::runtime_error(msg.str());
+      }
+      if (   inputWS->dataX(0).front() > inputWS->dataX(0).back()
+             || inputWS->dataX(m_numberOfSpectra/2).front() > inputWS->dataX(m_numberOfSpectra/2).back())
+          throw std::runtime_error("Input workspace has invalid X axis binning parameters. X values should be increasing.");
+
+      MatrixWorkspace_sptr outputWS = this->setupOutputWorkspace(inputWS);
+
+
+      // Check whether there is a quick conversion available
+      double factor, power;
+      if ( m_inputUnit->quickConversion(*m_outputUnit,factor,power) )
+      // If test fails, could also check whether a quick conversion in the opposite direction has been entered
+      {
+        this->convertQuickly(outputWS,factor,power);
+      }
+      else
+      {
+        this->convertViaTOF(m_inputUnit,outputWS);
+      }
+
+      // If the units conversion has flipped the ascending direction of X, reverse all the vectors
+      if (outputWS->dataX(0).size() && ( outputWS->dataX(0).front() > outputWS->dataX(0).back()
+            || outputWS->dataX(m_numberOfSpectra/2).front() > outputWS->dataX(m_numberOfSpectra/2).back() ) )
+      {
+        this->reverse(outputWS);
+      }
+
+      // Need to lop bins off if converting to energy transfer.
+      // Don't do for EventWorkspaces, where you can easily rebin to recover the situation without losing information
+      /* This is an ugly test - could be made more general by testing for DBL_MAX
+         values at the ends of all spectra, but that would be less efficient */
+      if ( m_outputUnit->unitID().find("Delta")==0 && !m_inputEvents ) outputWS = this->removeUnphysicalBins(outputWS);
+
+      // Rebin the data to common bins if requested, and if necessary
+      bool alignBins = getProperty("AlignBins");
+      if (alignBins && !WorkspaceHelpers::commonBoundaries(outputWS))
+        outputWS = this->alignBins(outputWS);
+
+      // If appropriate, put back the bin width division into Y/E.
+      if (m_distribution && !m_inputEvents)  // Never do this for event workspaces
+      {
+        this->putBackBinWidth(outputWS);
+      }
+
+      // Point the output property to the right place.
+      // Do right at end (workspace could could change in removeUnphysicalBins or alignBins methods)
+      setProperty("OutputWorkspace",outputWS);
+      return;
+  }
+
+
+
+  /** Initialise the member variables
+   *  @param inputWS The input workspace
+   */
+  void ConvertUnitsUsingDetectorTable::setupMemberVariables(const API::MatrixWorkspace_const_sptr inputWS)
+  {
+    m_numberOfSpectra = inputWS->getNumberHistograms();
+    // In the context of this algorithm, we treat things as a distribution if the flag is set
+    // AND the data are not dimensionless
+    m_distribution = inputWS->isDistribution() && !inputWS->YUnit().empty();
+    //Check if its an event workspace
+    m_inputEvents = ( boost::dynamic_pointer_cast<const EventWorkspace>(inputWS) != NULL );
+
+    m_inputUnit = inputWS->getAxis(0)->unit();
+    const std::string targetUnit = getPropertyValue("Target");
+    m_outputUnit = UnitFactory::Instance().create(targetUnit);
+  }
+
+  /** Create an output workspace of the appropriate (histogram or event) type and copy over the data
+   *  @param inputWS The input workspace
+   */
+  API::MatrixWorkspace_sptr ConvertUnitsUsingDetectorTable::setupOutputWorkspace(const API::MatrixWorkspace_const_sptr inputWS)
+  {
+    MatrixWorkspace_sptr outputWS = getProperty("OutputWorkspace");
+
+    // If input and output workspaces are NOT the same, create a new workspace for the output
+    if (outputWS != inputWS )
+    {
+      if ( m_inputEvents )
+      {
+        // Need to create by name as WorkspaceFactory otherwise spits out Workspace2D when EventWS passed in
+        outputWS = WorkspaceFactory::Instance().create("EventWorkspace", inputWS->getNumberHistograms(), 2, 1);
+        // Copy geometry etc. over
+        WorkspaceFactory::Instance().initializeFromParent(inputWS, outputWS, false);
+        // Need to copy over the data as well
+        EventWorkspace_const_sptr inputEventWS = boost::dynamic_pointer_cast<const EventWorkspace>(inputWS);
+        boost::dynamic_pointer_cast<EventWorkspace>(outputWS)->copyDataFrom( *inputEventWS );
+      }
+      else
+      {
+        // Create the output workspace
+        outputWS = WorkspaceFactory::Instance().create(inputWS);
+        // Copy the data over
+        this->fillOutputHist(inputWS, outputWS);
+      }
+    }
+
+    // Set the final unit that our output workspace will have
+    outputWS->getAxis(0)->unit() = m_outputUnit;
+
+    return outputWS;
+  }
+
+
+  /** Do the initial copy of the data from the input to the output workspace for histogram workspaces.
+   *  Takes out the bin width if necessary.
+   *  @param inputWS  The input workspace
+   *  @param outputWS The output workspace
+   */
+  void ConvertUnitsUsingDetectorTable::fillOutputHist(const API::MatrixWorkspace_const_sptr inputWS, const API::MatrixWorkspace_sptr outputWS)
+  {
+    const int size = static_cast<int>(inputWS->blocksize());
+
+    // Loop over the histograms (detector spectra)
+    Progress prog(this,0.0,0.2,m_numberOfSpectra);
+    int64_t numberOfSpectra_i = static_cast<int64_t>(m_numberOfSpectra); // cast to make openmp happy
+    PARALLEL_FOR2(inputWS,outputWS)
+    for (int64_t i = 0; i < numberOfSpectra_i; ++i)
+    {
+      PARALLEL_START_INTERUPT_REGION
+      // Take the bin width dependency out of the Y & E data
+      if (m_distribution)
+      {
+        for (int j = 0; j < size; ++j)
+        {
+          const double width = std::abs( inputWS->dataX(i)[j+1] - inputWS->dataX(i)[j] );
+          outputWS->dataY(i)[j] = inputWS->dataY(i)[j]*width;
+          outputWS->dataE(i)[j] = inputWS->dataE(i)[j]*width;
+        }
+      }
+      else
+      {
+        // Just copy over
+        outputWS->dataY(i) = inputWS->readY(i);
+        outputWS->dataE(i) = inputWS->readE(i);
+      }
+      // Copy over the X data
+      outputWS->setX( i, inputWS->refX(i) );
+
+      prog.report("Convert to " + m_outputUnit->unitID());
+      PARALLEL_END_INTERUPT_REGION
+    }
+    PARALLEL_CHECK_INTERUPT_REGION
+  }
+
+
+  /** Convert the workspace units using TOF as an intermediate step in the conversion
+   * @param fromUnit :: The unit of the input workspace
+   * @param outputWS :: The output workspace
+   */
+  void ConvertUnitsUsingDetectorTable::convertViaTOF(Kernel::Unit_const_sptr fromUnit, API::MatrixWorkspace_sptr outputWS)
+  {
+    using namespace Geometry;
+
+      // Let's see if we are using a TableWorkspace to override parameters
+      ITableWorkspace_sptr paramWS = getProperty("DetectorParameters");
+
+      // See if we have supplied a DetectorParameters Workspace
+      // TODO: Check if paramWS is NULL and if so throw an exception
+
+      // Some variables to hold our values
+      Column_const_sptr l1Column;
+      Column_const_sptr l2Column;
+      Column_const_sptr spectraColumn;
+      Column_const_sptr twoThetaColumn;
+      Column_const_sptr efixedColumn;
+      Column_const_sptr emodeColumn;
+
+      //std::vector<std::string> columnNames = paramWS->getColumnNames();
+
+      // Now lets read the parameters
+      try {
+          l1Column = paramWS->getColumn("l1");
+          l2Column = paramWS->getColumn("l2");
+          spectraColumn = paramWS->getColumn("spectra");
+          twoThetaColumn = paramWS->getColumn("twotheta");
+          efixedColumn = paramWS->getColumn("efixed");
+          emodeColumn = paramWS->getColumn("emode");
+      } catch (...) {
+          throw Exception::InstrumentDefinitionError("DetectorParameter TableWorkspace is not defined correctly.");
+      }
+
+
+      EventWorkspace_sptr eventWS = boost::dynamic_pointer_cast<EventWorkspace>(outputWS);
+      assert ( static_cast<bool>(eventWS) == m_inputEvents ); // Sanity check
+
+      Progress prog(this,0.2,1.0,m_numberOfSpectra);
+      int64_t numberOfSpectra_i = static_cast<int64_t>(m_numberOfSpectra); // cast to make openmp happy
+
+      // Get the unit object for each workspace
+      Kernel::Unit_const_sptr outputUnit = outputWS->getAxis(0)->unit();
+
+      int emode = 0;
+      double l1, l2, twoTheta, efixed;
+
+      std::vector<double> emptyVec;
+      int failedDetectorCount = 0;
+
+//      std::vector<std::string> parameters = outputWS->getInstrument()->getStringParameter("show-signed-theta");
+//      bool bUseSignedVersion = (!parameters.empty()) && find(parameters.begin(), parameters.end(), "Always") != parameters.end();
+//      function<double(IDetector_const_sptr)> thetaFunction = bUseSignedVersion ? bind(&MatrixWorkspace::detectorSignedTwoTheta, outputWS, _1) : bind(&MatrixWorkspace::detectorTwoTheta, outputWS, _1);
+
+
+      // TODO: Check why this parallel stuff breaks
+      // Loop over the histograms (detector spectra)
+      //PARALLEL_FOR1(outputWS)
+              for (int64_t i = 0; i < numberOfSpectra_i; ++i)
+      {
+          //PARALLEL_START_INTERUPT_REGION
+
+          std::size_t wsid = i;
+
+          try
+          {
+              double deg2rad = M_PI / 180.;
+              specid_t spectraNumber = static_cast<specid_t>(spectraColumn->toDouble(i));
+              wsid = outputWS->getIndexFromSpectrumNumber(spectraNumber);
+              g_log.debug() << "###### Spectra #" << spectraNumber << " ==> Workspace ID:" << wsid << std::endl;
+              l1 = l1Column->toDouble(wsid);
+              l2 = l2Column->toDouble(wsid);
+              twoTheta = deg2rad * twoThetaColumn->toDouble(wsid);
+              efixed = efixedColumn->toDouble(wsid);
+              emode = static_cast<int>(emodeColumn->toDouble(wsid));
+
+              g_log.debug() << "\tL1=" << l1 << ",L2=" << l2 << ",TT=" << twoTheta << ",EF=" << efixed
+                            << ",EM=" << emode << std::endl;
+
+              // Make local copies of the units. This allows running the loop in parallel
+              Unit * localFromUnit = fromUnit->clone();
+              Unit * localOutputUnit = outputUnit->clone();
+              /// @todo Don't yet consider hold-off (delta)
+              const double delta = 0.0;
+              // Convert the input unit to time-of-flight
+              localFromUnit->toTOF(outputWS->dataX(wsid),emptyVec,l1,l2,twoTheta,emode,efixed,delta);
+              // Convert from time-of-flight to the desired unit
+              localOutputUnit->fromTOF(outputWS->dataX(wsid),emptyVec,l1,l2,twoTheta,emode,efixed,delta);
+              // EventWorkspace part, modifying the EventLists.
+              if ( m_inputEvents )
+              {
+                  eventWS->getEventList(wsid).convertUnitsViaTof(localFromUnit, localOutputUnit);
+              }
+              // Clear unit memory
+              delete localFromUnit;
+              delete localOutputUnit;
+
+          } catch (Exception::NotFoundError&) {
+              // Get to here if exception thrown when calculating distance to detector
+              failedDetectorCount++;
+              // Since you usually (always?) get to here when there's no attached detectors, this call is
+              // the same as just zeroing out the data (calling clearData on the spectrum)
+              outputWS->maskWorkspaceIndex(i);
+          }
+
+          prog.report("Convert to " + m_outputUnit->unitID());
+          //PARALLEL_END_INTERUPT_REGION
+      } // loop over spectra
+      //PARALLEL_CHECK_INTERUPT_REGION
+
+              if (failedDetectorCount != 0)
+      {
+          g_log.information() << "Something went wrong for " << failedDetectorCount << " spectra. Masking spectrum." << std::endl;
+      }
+      if (m_inputEvents)
+          eventWS->clearMRU();
+
+  }
+
+  /** Convert the workspace units according to a simple output = a * (input^b) relationship
+   *  @param outputWS :: the output workspace
+   *  @param factor :: the conversion factor a to apply
+   *  @param power :: the Power b to apply to the conversion
+   */
+  void ConvertUnitsUsingDetectorTable::convertQuickly(API::MatrixWorkspace_sptr outputWS, const double& factor, const double& power)
+  {
+    Progress prog(this,0.2,1.0,m_numberOfSpectra);
+    int64_t numberOfSpectra_i = static_cast<int64_t>(m_numberOfSpectra); // cast to make openmp happy
+
+    // See if the workspace has common bins - if so the X vector can be common
+    // First a quick check using the validator
+    CommonBinsValidator sameBins;
+    bool commonBoundaries = false;
+    if ( sameBins.isValid(outputWS) == "" )
+    {
+      commonBoundaries =  WorkspaceHelpers::commonBoundaries(outputWS);
+      // Only do the full check if the quick one passes
+      if (commonBoundaries)
+      {
+        // Calculate the new (common) X values
+        MantidVec::iterator iter;
+        for (iter = outputWS->dataX(0).begin(); iter != outputWS->dataX(0).end(); ++iter)
+        {
+          *iter = factor * std::pow(*iter,power);
+        }
+
+        MantidVecPtr xVals;
+        xVals.access() = outputWS->dataX(0);
+
+        PARALLEL_FOR1(outputWS)
+        for (int64_t j = 1; j < numberOfSpectra_i; ++j)
+        {
+          PARALLEL_START_INTERUPT_REGION
+          outputWS->setX(j,xVals);
+          prog.report("Convert to " + m_outputUnit->unitID());
+          PARALLEL_END_INTERUPT_REGION
+        }
+        PARALLEL_CHECK_INTERUPT_REGION
+        if (!m_inputEvents) // if in event mode the work is done
+          return;
+      }
+    }
+
+    EventWorkspace_sptr eventWS = boost::dynamic_pointer_cast<EventWorkspace>(outputWS);
+    assert ( static_cast<bool>(eventWS) == m_inputEvents ); // Sanity check
+
+    // If we get to here then the bins weren't aligned and each spectrum is unique
+    // Loop over the histograms (detector spectra)
+    PARALLEL_FOR1(outputWS)
+    for (int64_t k = 0; k < numberOfSpectra_i; ++k) {
+      PARALLEL_START_INTERUPT_REGION
+      if (!commonBoundaries) {
+        MantidVec::iterator it;
+        for (it = outputWS->dataX(k).begin(); it != outputWS->dataX(k).end(); ++it)
+        {
+          *it = factor * std::pow(*it,power);
+        }
+      }
+      // Convert the events themselves if necessary. Inefficiently.
+      if ( m_inputEvents )
+      {
+        eventWS->getEventList(k).convertUnitsQuickly(factor, power);
+      }
+      prog.report("Convert to " + m_outputUnit->unitID());
+      PARALLEL_END_INTERUPT_REGION
+    }
+    PARALLEL_CHECK_INTERUPT_REGION
+
+    if (m_inputEvents)
+      eventWS->clearMRU();
+    return;
+  }
+
+
+
+
+  /// Calls Rebin as a Child Algorithm to align the bins
+  API::MatrixWorkspace_sptr ConvertUnitsUsingDetectorTable::alignBins(API::MatrixWorkspace_sptr workspace)
+  {
+    // Create a Rebin child algorithm
+    IAlgorithm_sptr childAlg = createChildAlgorithm("Rebin");
+    childAlg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", workspace);
+    // Next line for EventWorkspaces - needed for as long as in/out set same keeps as events.
+    childAlg->setProperty<MatrixWorkspace_sptr>("OutputWorkspace", workspace);
+    childAlg->setProperty<std::vector<double> >("Params",this->calculateRebinParams(workspace));
+    childAlg->executeAsChildAlg();
+    return childAlg->getProperty("OutputWorkspace");
+  }
+
+  /// The Rebin parameters should cover the full range of the converted unit, with the same number of bins
+  const std::vector<double> ConvertUnitsUsingDetectorTable::calculateRebinParams(const API::MatrixWorkspace_const_sptr workspace) const
+  {
+    // Need to loop round and find the full range
+    double XMin = DBL_MAX, XMax = DBL_MIN;
+    const size_t numSpec = workspace->getNumberHistograms();
+    for (size_t i = 0; i < numSpec; ++i)
+    {
+      try {
+        Geometry::IDetector_const_sptr det = workspace->getDetector(i);
+        if ( !det->isMasked() )
+        {
+          const MantidVec & XData = workspace->readX(i);
+          double xfront = XData.front();
+          double xback = XData.back();
+          if (boost::math::isfinite(xfront) && boost::math::isfinite(xback))
+          {
+            if ( xfront < XMin ) XMin = xfront;
+            if ( xback > XMax )  XMax = xback;
+          }
+        }
+      } catch (Exception::NotFoundError &) {} //Do nothing
+    }
+    const double step = ( XMax - XMin ) / static_cast<double>(workspace->blocksize());
+
+    std::vector<double> retval;
+    retval.push_back(XMin);
+    retval.push_back(step);
+    retval.push_back(XMax);
+
+    return retval;
+  }
+
+
+
+
+  /** Reverses the workspace if X values are in descending order
+   *  @param WS The workspace to operate on
+   */
+  void ConvertUnitsUsingDetectorTable::reverse(API::MatrixWorkspace_sptr WS)
+  {
+    if ( WorkspaceHelpers::commonBoundaries(WS) && !m_inputEvents )
+    {
+      std::reverse(WS->dataX(0).begin(),WS->dataX(0).end());
+      std::reverse(WS->dataY(0).begin(),WS->dataY(0).end());
+      std::reverse(WS->dataE(0).begin(),WS->dataE(0).end());
+
+      MantidVecPtr xVals;
+      xVals.access() = WS->dataX(0);
+      for (size_t j = 1; j < m_numberOfSpectra; ++j)
+      {
+        WS->setX(j,xVals);
+        std::reverse(WS->dataY(j).begin(),WS->dataY(j).end());
+        std::reverse(WS->dataE(j).begin(),WS->dataE(j).end());
+        if ( j % 100 == 0) interruption_point();
+      }
+    }
+    else
+    {
+      EventWorkspace_sptr eventWS = boost::dynamic_pointer_cast<EventWorkspace>(WS);
+      assert ( static_cast<bool>(eventWS) == m_inputEvents ); // Sanity check
+
+      int m_numberOfSpectra_i = static_cast<int>(m_numberOfSpectra);
+      PARALLEL_FOR1(WS)
+      for (int j = 0; j < m_numberOfSpectra_i; ++j)
+      {
+        PARALLEL_START_INTERUPT_REGION
+        if ( m_inputEvents )
+        {
+          eventWS->getEventList(j).reverse();
+        }
+        else
+        {
+          std::reverse(WS->dataX(j).begin(),WS->dataX(j).end());
+          std::reverse(WS->dataY(j).begin(),WS->dataY(j).end());
+          std::reverse(WS->dataE(j).begin(),WS->dataE(j).end());
+        }
+        PARALLEL_END_INTERUPT_REGION
+      }
+      PARALLEL_CHECK_INTERUPT_REGION
+    }
+  }
+
+  /** Unwieldy method which removes bins which lie in a physically inaccessible region.
+   *  This presently only occurs in conversions to energy transfer, where the initial
+   *  unit conversion sets them to +/-DBL_MAX. This method removes those bins, leading
+   *  to a workspace which is smaller than the input one.
+   *  As presently implemented, it unfortunately requires testing for and knowledge of
+   *  aspects of the particular units conversion instead of keeping all that in the
+   *  units class. It could be made more general, but that would be less efficient.
+   *  @param workspace :: The workspace after initial unit conversion
+   *  @return The workspace after bins have been removed
+   */
+  API::MatrixWorkspace_sptr ConvertUnitsUsingDetectorTable::removeUnphysicalBins(const Mantid::API::MatrixWorkspace_const_sptr workspace)
+  {
+    MatrixWorkspace_sptr result;
+
+    const size_t numSpec = workspace->getNumberHistograms();
+    const std::string emode = getProperty("Emode");
+    if (emode=="Direct")
+    {
+      // First the easy case of direct instruments, where all spectra will need the
+      // same number of bins removed
+      // Need to make sure we don't pick a monitor as the 'reference' X spectrum (X0)
+      size_t i = 0;
+      for ( ; i < numSpec; ++i )
+      {
+        try {
+          Geometry::IDetector_const_sptr det = workspace->getDetector(i);
+          if ( !det->isMonitor() ) break;
+        } catch (Exception::NotFoundError &) { /* Do nothing */ }
+      }
+      // Get an X spectrum to search (they're all the same, monitors excepted)
+      const MantidVec& X0 = workspace->readX(i);
+      MantidVec::const_iterator start = std::lower_bound(X0.begin(),X0.end(),-1.0e-10*DBL_MAX);
+      if ( start == X0.end() )
+      {
+        const std::string e("Check the input EFixed: the one given leads to all bins being in the physically inaccessible region.");
+        g_log.error(e);
+        throw std::invalid_argument(e);
+      }
+      MantidVec::difference_type bins = X0.end() - start;
+      MantidVec::difference_type first = start - X0.begin();
+
+      result = WorkspaceFactory::Instance().create(workspace,numSpec,bins,bins-1);
+
+      for (size_t i = 0; i < numSpec; ++i)
+      {
+        const MantidVec& X = workspace->readX(i);
+        const MantidVec& Y = workspace->readY(i);
+        const MantidVec& E = workspace->readE(i);
+        result->dataX(i).assign(X.begin()+first,X.end());
+        result->dataY(i).assign(Y.begin()+first,Y.end());
+        result->dataE(i).assign(E.begin()+first,E.end());
+      }
+    }
+    else if (emode=="Indirect")
+    {
+      // Now the indirect instruments. In this case we could want to keep a different
+      // number of bins in each spectrum because, in general L2 is different for each
+      // one.
+      // Thus, we first need to loop to find largest 'good' range
+      std::vector<MantidVec::difference_type> lastBins(numSpec);
+      int maxBins = 0;
+      for (size_t i = 0; i < numSpec; ++i)
+      {
+        const MantidVec& X = workspace->readX(i);
+        MantidVec::const_iterator end = std::lower_bound(X.begin(),X.end(),1.0e-10*DBL_MAX);
+        MantidVec::difference_type bins = end - X.begin();
+        lastBins[i] = bins;
+        if (bins > maxBins) maxBins = static_cast<int>(bins);
+      }
+      g_log.debug() << maxBins << std::endl;
+      // Now create an output workspace large enough for the longest 'good' range
+      result = WorkspaceFactory::Instance().create(workspace,numSpec,maxBins,maxBins-1);
+      // Next, loop again copying in the correct range for each spectrum
+      for (int64_t j = 0; j < int64_t(numSpec); ++j)
+      {
+        const MantidVec& X = workspace->readX(j);
+        const MantidVec& Y = workspace->readY(j);
+        const MantidVec& E = workspace->readE(j);
+        MantidVec& Xnew = result->dataX(j);
+        MantidVec& Ynew = result->dataY(j);
+        MantidVec& Enew = result->dataE(j);
+        int k;
+        for (k = 0; k < lastBins[j]-1; ++k)
+        {
+          Xnew[k] = X[k];
+          Ynew[k] = Y[k];
+          Enew[k] = E[k];
+        }
+        Xnew[k] = X[k];
+        ++k;
+        // If necessary, add on some fake values to the end of the X array (Y&E will be zero)
+        if (k < maxBins)
+        {
+          for (int l=k; l < maxBins; ++l)
+          {
+            Xnew[l] = X[k]+1+l-k;
+          }
+        }
+      }
+    }
+
+    return result;
+  }
+
+
+  /** Divide by the bin width if workspace is a distribution
+   *  @param outputWS The workspace to operate on
+   */
+  void ConvertUnitsUsingDetectorTable::putBackBinWidth(const API::MatrixWorkspace_sptr outputWS)
+  {
+    const size_t outSize = outputWS->blocksize();
+
+    for (size_t i = 0; i < m_numberOfSpectra; ++i)
+    {
+      for (size_t j = 0; j < outSize; ++j)
+      {
+        const double width = std::abs( outputWS->dataX(i)[j+1] - outputWS->dataX(i)[j] );
+        outputWS->dataY(i)[j] = outputWS->dataY(i)[j]/width;
+        outputWS->dataE(i)[j] = outputWS->dataE(i)[j]/width;
+      }
+    }
+  }
+
+} // namespace Algorithms
+} // namespace Mantid
diff --git a/Code/Mantid/Framework/Algorithms/src/CropWorkspace.cpp b/Code/Mantid/Framework/Algorithms/src/CropWorkspace.cpp
index e7a0dbed7793e2988a9882e24f444c34c66f35a5..db5158521425db48174963a55c42b3be837589a4 100644
--- a/Code/Mantid/Framework/Algorithms/src/CropWorkspace.cpp
+++ b/Code/Mantid/Framework/Algorithms/src/CropWorkspace.cpp
@@ -2,6 +2,7 @@
 // Includes
 //----------------------------------------------------------------------
 #include "MantidAlgorithms/CropWorkspace.h"
+
 #include "MantidAPI/WorkspaceValidators.h"
 #include "MantidAPI/NumericAxis.h"
 #include "MantidAPI/TextAxis.h"
@@ -10,11 +11,6 @@
 #include "MantidAPI/MemoryManager.h"
 #include "MantidKernel/BoundedValidator.h"
 
-namespace {
-/// The percentage 'fuzziness' to use when comparing to bin boundaries
-const double xBoundaryTolerance = 1.0e-15;
-}
-
 namespace Mantid {
 namespace Algorithms {
 
@@ -25,12 +21,9 @@ DECLARE_ALGORITHM(CropWorkspace)
 
 using namespace Kernel;
 using namespace API;
-using namespace DataObjects;
 
 /// Default constructor
-CropWorkspace::CropWorkspace()
-    : Algorithm(), m_minX(0), m_maxX(0), m_minSpec(-1), m_maxSpec(-1),
-      m_commonBoundaries(false), m_histogram(false), m_croppingInX(false) {}
+CropWorkspace::CropWorkspace(): Algorithm() {}
 
 /// Destructor
 CropWorkspace::~CropWorkspace() {}
@@ -70,408 +63,32 @@ void CropWorkspace::init() {
  * input workspace
  */
 void CropWorkspace::exec() {
-  // Get the input workspace
-  m_inputWorkspace = getProperty("InputWorkspace");
-
-  eventW = boost::dynamic_pointer_cast<EventWorkspace>(m_inputWorkspace);
-  if (eventW != NULL) {
-    // Input workspace is an event workspace. Use the other exec method
-    this->execEvent();
-    return;
-  }
-
-  m_histogram = m_inputWorkspace->isHistogramData();
-  // Check for common boundaries in input workspace
-  m_commonBoundaries = WorkspaceHelpers::commonBoundaries(m_inputWorkspace);
-
-  // Retrieve and validate the input properties
-  this->checkProperties();
 
-  // Create the output workspace
-  MatrixWorkspace_sptr outputWorkspace = WorkspaceFactory::Instance().create(
-      m_inputWorkspace, m_maxSpec - m_minSpec + 1, m_maxX - m_minX,
-      m_maxX - m_minX - m_histogram);
+  auto extract = createChildAlgorithm("ExtractSpectra", 0, 1);
+  extract->initialize();
+  extract->setRethrows(true);
 
-  // If this is a Workspace2D, get the spectra axes for copying in the spectraNo
-  // later
-  Axis *inAxis1(NULL), *outAxis1(NULL);
-  TextAxis *outTxtAxis(NULL);
-  if (m_inputWorkspace->axes() > 1) {
-    inAxis1 = m_inputWorkspace->getAxis(1);
-    outAxis1 = outputWorkspace->getAxis(1);
-    outTxtAxis = dynamic_cast<TextAxis *>(outAxis1);
-  }
+  MatrixWorkspace_sptr inputWorkspace = getProperty("InputWorkspace");
+  extract->setProperty("InputWorkspace", inputWorkspace);
 
-  cow_ptr<MantidVec> newX;
-  if (m_commonBoundaries) {
-    const MantidVec &oldX = m_inputWorkspace->readX(m_minSpec);
-    newX.access().assign(oldX.begin() + m_minX, oldX.begin() + m_maxX);
-  }
-  Progress prog(this, 0.0, 1.0, (m_maxSpec - m_minSpec));
-  // Loop over the required spectra, copying in the desired bins
-  for (int i = m_minSpec, j = 0; i <= m_maxSpec; ++i, ++j) {
-    // Preserve/restore sharing if X vectors are the same
-    if (m_commonBoundaries) {
-      outputWorkspace->setX(j, newX);
-    } else {
-      // Safe to just copy whole vector 'cos can't be cropping in X if not
-      // common
-      outputWorkspace->setX(j, m_inputWorkspace->refX(i));
-    }
+  double xmin = getProperty("XMin");
+  extract->setProperty("XMin", xmin);
 
-    const MantidVec &oldY = m_inputWorkspace->readY(i);
-    outputWorkspace->dataY(j)
-        .assign(oldY.begin() + m_minX, oldY.begin() + (m_maxX - m_histogram));
-    const MantidVec &oldE = m_inputWorkspace->readE(i);
-    outputWorkspace->dataE(j)
-        .assign(oldE.begin() + m_minX, oldE.begin() + (m_maxX - m_histogram));
+  double xmax = getProperty("XMax");
+  extract->setProperty("XMax", xmax);
 
-    // copy over the axis entry for each spectrum, regardless of the type of
-    // axes present
-    if (inAxis1) {
-      if (outAxis1->isText()) {
-        outTxtAxis->setLabel(j, inAxis1->label(i));
-      } else if (!outAxis1->isSpectra()) // handled by copyInfoFrom line
-      {
-        dynamic_cast<NumericAxis *>(outAxis1)
-            ->setValue(j, inAxis1->operator()(i));
-      }
-    }
-    // Copy spectrum number & detectors
-    outputWorkspace->getSpectrum(j)
-        ->copyInfoFrom(*m_inputWorkspace->getSpectrum(i));
+  int start = getProperty("StartWorkspaceIndex");
+  extract->setProperty("StartWorkspaceIndex", start);
 
-    if (!m_commonBoundaries)
-      this->cropRagged(outputWorkspace, i, j);
+  int end = getProperty("EndWorkspaceIndex");
+  extract->setProperty("EndWorkspaceIndex", end);
 
-    // Propagate bin masking if there is any
-    if (m_inputWorkspace->hasMaskedBins(i)) {
-      const MatrixWorkspace::MaskList &inputMasks =
-          m_inputWorkspace->maskedBins(i);
-      MatrixWorkspace::MaskList::const_iterator it;
-      for (it = inputMasks.begin(); it != inputMasks.end(); ++it) {
-        const size_t maskIndex = (*it).first;
-        if (maskIndex >= m_minX && maskIndex < m_maxX - m_histogram)
-          outputWorkspace->flagMasked(j, maskIndex - m_minX, (*it).second);
-      }
-    }
-    prog.report();
-  }
+  extract->execute();
 
+  MatrixWorkspace_sptr outputWorkspace = extract->getProperty("OutputWorkspace");
   setProperty("OutputWorkspace", outputWorkspace);
 }
 
-template <typename T>
-std::size_t lowerBound(const std::vector<T> &events, const double tof) {
-  typename std::vector<T>::const_iterator first = events.begin();
-  typename std::vector<T>::const_iterator last = events.end();
-  typename std::vector<T>::const_iterator it;
-  typename std::vector<T>::difference_type count = distance(first, last);
-  typename std::vector<T>::difference_type step;
-
-  while (count > 0) {
-    it = first;
-    step = count / 2;
-    advance(it, step);
-    if (it->tof() < tof) // or: if (comp(*it,value)), for the comp version
-    {
-      first = ++it;
-      count -= step + 1;
-    } else
-      count = step;
-  }
-  if (first == events.end())
-    return events.size();
-  else
-    return distance(events.begin(), first);
-}
-
-/** Executes the algorithm
- *  @throw std::out_of_range If a property is set to an invalid value for the
- * input workspace
- */
-void CropWorkspace::execEvent() {
-  m_histogram = m_inputWorkspace->isHistogramData();
-  double minX_val = getProperty("XMin");
-  double maxX_val = getProperty("XMax");
-  if (isEmpty(minX_val))
-    minX_val = eventW->getTofMin();
-  if (isEmpty(maxX_val))
-    maxX_val = eventW->getTofMax();
-
-  // Check for common boundaries in input workspace
-  m_commonBoundaries = WorkspaceHelpers::commonBoundaries(m_inputWorkspace);
-
-  // Retrieve and validate the input properties
-  this->checkProperties();
-  cow_ptr<MantidVec> XValues_new;
-  if (m_commonBoundaries) {
-    const MantidVec &oldX = m_inputWorkspace->readX(m_minSpec);
-    XValues_new.access().assign(oldX.begin() + m_minX, oldX.begin() + m_maxX);
-  }
-  size_t ntcnew = m_maxX - m_minX;
-
-  if (ntcnew < 2) {
-    // create new output X axis
-    std::vector<double> rb_params;
-    rb_params.push_back(minX_val);
-    rb_params.push_back(maxX_val - minX_val);
-    rb_params.push_back(maxX_val);
-    ntcnew = VectorHelper::createAxisFromRebinParams(rb_params,
-                                                     XValues_new.access());
-  }
-
-  // run inplace branch if appropriate
-  MatrixWorkspace_sptr OutputWorkspace = this->getProperty("OutputWorkspace");
-  bool inPlace = (OutputWorkspace == m_inputWorkspace);
-  if (inPlace)
-    g_log.debug("Cropping EventWorkspace in-place.");
-
-  // Create the output workspace
-  EventWorkspace_sptr outputWorkspace =
-      boost::dynamic_pointer_cast<EventWorkspace>(
-          API::WorkspaceFactory::Instance().create(
-              "EventWorkspace", m_maxSpec - m_minSpec + 1, ntcnew,
-              ntcnew - m_histogram));
-  eventW->sortAll(TOF_SORT, NULL);
-  outputWorkspace->sortAll(TOF_SORT, NULL);
-  // Copy required stuff from it
-  API::WorkspaceFactory::Instance().initializeFromParent(m_inputWorkspace,
-                                                         outputWorkspace, true);
-
-  Progress prog(this, 0.0, 1.0, 2 * (m_maxSpec - m_minSpec));
-  eventW->sortAll(Mantid::DataObjects::TOF_SORT, &prog);
-  // Loop over the required spectra, copying in the desired bins
-  PARALLEL_FOR2(m_inputWorkspace, outputWorkspace)
-  for (int i = m_minSpec; i <= m_maxSpec; ++i) {
-    PARALLEL_START_INTERUPT_REGION
-    int j = i - m_minSpec;
-    const EventList &el = eventW->getEventList(i);
-    // The output event list
-    EventList &outEL = outputWorkspace->getOrAddEventList(j);
-    //    // left side of the crop - will erase 0 -> endLeft
-    //    std::size_t endLeft;
-    //    // right side of the crop - will erase endRight->numEvents+1
-    //    std::size_t endRight;
-
-    switch (el.getEventType()) {
-    case TOF: {
-      std::vector<TofEvent>::const_iterator itev = el.getEvents().begin();
-      std::vector<TofEvent>::const_iterator end = el.getEvents().end();
-      std::vector<TofEvent> moreevents;
-      moreevents.reserve(el.getNumberEvents()); // assume all will make it
-      for (; itev != end; ++itev) {
-        const double tof = itev->tof();
-        if (tof <= maxX_val && tof >= minX_val)
-          moreevents.push_back(*itev);
-      }
-      outEL += moreevents;
-      break;
-    }
-    case WEIGHTED: {
-      std::vector<WeightedEvent>::const_iterator itev =
-          el.getWeightedEvents().begin();
-      std::vector<WeightedEvent>::const_iterator end =
-          el.getWeightedEvents().end();
-      std::vector<WeightedEvent> moreevents;
-      moreevents.reserve(el.getNumberEvents()); // assume all will make it
-      for (; itev != end; ++itev) {
-        const double tof = itev->tof();
-        if (tof <= maxX_val && tof >= minX_val)
-          moreevents.push_back(*itev);
-      }
-      outEL += moreevents;
-      break;
-    }
-    case WEIGHTED_NOTIME: {
-      std::vector<WeightedEventNoTime>::const_iterator itev =
-          el.getWeightedEventsNoTime().begin();
-      std::vector<WeightedEventNoTime>::const_iterator end =
-          el.getWeightedEventsNoTime().end();
-      std::vector<WeightedEventNoTime> moreevents;
-      moreevents.reserve(el.getNumberEvents()); // assume all will make it
-      for (; itev != end; ++itev) {
-        const double tof = itev->tof();
-        if (tof <= maxX_val && tof >= minX_val)
-          moreevents.push_back(*itev);
-      }
-      outEL += moreevents;
-      break;
-    }
-    }
-    outEL.setSortOrder(el.getSortType());
-
-    // Copy spectrum number & detector IDs
-    outEL.copyInfoFrom(el);
-
-    if (!m_commonBoundaries)
-      // If the X axis is NOT common, then keep the initial X axis, just clear
-      // the events
-      outEL.setX(el.dataX());
-    else
-      // Common bin boundaries get all set to the same value
-      outEL.setX(XValues_new);
-
-    // Propagate bin masking if there is any
-    if (m_inputWorkspace->hasMaskedBins(i)) {
-      const MatrixWorkspace::MaskList &inputMasks =
-          m_inputWorkspace->maskedBins(i);
-      MatrixWorkspace::MaskList::const_iterator it;
-      for (it = inputMasks.begin(); it != inputMasks.end(); ++it) {
-        const size_t maskIndex = (*it).first;
-        if (maskIndex >= m_minX && maskIndex < m_maxX - m_histogram)
-          outputWorkspace->flagMasked(j, maskIndex - m_minX, (*it).second);
-      }
-    }
-    // When cropping in place, you can clear out old memory from the input one!
-    if (inPlace) {
-      eventW->getEventList(i).clear();
-      Mantid::API::MemoryManager::Instance().releaseFreeMemory();
-    }
-    prog.report();
-    PARALLEL_END_INTERUPT_REGION
-  }
-  PARALLEL_CHECK_INTERUPT_REGION
-
-  setProperty("OutputWorkspace",
-              boost::dynamic_pointer_cast<MatrixWorkspace>(outputWorkspace));
-}
-
-/** Retrieves the optional input properties and checks that they have valid
- * values.
- *  Assigns to the defaults if any property has not been set.
- *  @throw std::invalid_argument If the input workspace does not have common
- * binning
- *  @throw std::out_of_range If a property is set to an invalid value for the
- * input workspace
- */
-void CropWorkspace::checkProperties() {
-  m_minX = this->getXMin();
-  m_maxX = this->getXMax();
-  const size_t xSize = m_inputWorkspace->readX(0).size();
-  if (m_minX > 0 || m_maxX < xSize) {
-    if (m_minX > m_maxX) {
-      g_log.error("XMin must be less than XMax");
-      throw std::out_of_range("XMin must be less than XMax");
-    }
-    if (m_minX == m_maxX && m_commonBoundaries && eventW == NULL) {
-      g_log.error("The X range given lies entirely within a single bin");
-      throw std::out_of_range(
-          "The X range given lies entirely within a single bin");
-    }
-    m_croppingInX = true;
-  }
-  if (!m_commonBoundaries)
-    m_minX = 0;
-  if (!m_commonBoundaries)
-    m_maxX = static_cast<int>(m_inputWorkspace->readX(0).size());
-
-  m_minSpec = getProperty("StartWorkspaceIndex");
-  const int numberOfSpectra =
-      static_cast<int>(m_inputWorkspace->getNumberHistograms());
-  m_maxSpec = getProperty("EndWorkspaceIndex");
-  if (isEmpty(m_maxSpec))
-    m_maxSpec = numberOfSpectra - 1;
-
-  // Check 'StartSpectrum' is in range 0-numberOfSpectra
-  if (m_minSpec > numberOfSpectra - 1) {
-    g_log.error("StartWorkspaceIndex out of range!");
-    throw std::out_of_range("StartSpectrum out of range!");
-  }
-  if (m_maxSpec > numberOfSpectra - 1) {
-    g_log.error("EndWorkspaceIndex out of range!");
-    throw std::out_of_range("EndWorkspaceIndex out of range!");
-  }
-  if (m_maxSpec < m_minSpec) {
-    g_log.error(
-        "StartWorkspaceIndex must be less than or equal to EndWorkspaceIndex");
-    throw std::out_of_range(
-        "StartWorkspaceIndex must be less than or equal to EndWorkspaceIndex");
-  }
-}
-
-/** Find the X index corresponding to (or just within) the value given in the
- * XMin property.
- *  Sets the default if the property has not been set.
- *  @param  wsIndex The workspace index to check (default 0).
- *  @return The X index corresponding to the XMin value.
- */
-size_t CropWorkspace::getXMin(const int wsIndex) {
-  double minX_val = getProperty("XMin");
-  size_t xIndex = 0;
-  if (!isEmpty(minX_val)) { // A value has been passed to the algorithm, check
-                            // it and maybe store it
-    const MantidVec &X = m_inputWorkspace->readX(wsIndex);
-    if (m_commonBoundaries && minX_val > X.back()) {
-      std::stringstream msg;
-      msg << "XMin is greater than the largest X value (" << minX_val << " > "
-          << X.back() << ")";
-      g_log.error(msg.str());
-      throw std::out_of_range(msg.str());
-    }
-    // Reduce cut-off value slightly to allow for rounding errors
-    // when trying to exactly hit a bin boundary.
-    minX_val -= std::abs(minX_val * xBoundaryTolerance);
-    xIndex = std::lower_bound(X.begin(), X.end(), minX_val) - X.begin();
-  }
-  return xIndex;
-}
-
-/** Find the X index corresponding to (or just within) the value given in the
- * XMax property.
- *  Sets the default if the property has not been set.
- *  @param  wsIndex The workspace index to check (default 0).
- *  @return The X index corresponding to the XMax value.
- */
-size_t CropWorkspace::getXMax(const int wsIndex) {
-  const MantidVec &X = m_inputWorkspace->readX(wsIndex);
-  size_t xIndex = X.size();
-  // get the value that the user entered if they entered one at all
-  double maxX_val = getProperty("XMax");
-  if (!isEmpty(maxX_val)) { // we have a user value, check it and maybe store it
-    if (m_commonBoundaries && maxX_val < X.front()) {
-      std::stringstream msg;
-      msg << "XMax is less than the smallest X value (" << maxX_val << " < "
-          << X.front() << ")";
-      g_log.error(msg.str());
-      throw std::out_of_range(msg.str());
-    }
-    // Increase cut-off value slightly to allow for rounding errors
-    // when trying to exactly hit a bin boundary.
-    maxX_val += std::abs(maxX_val * xBoundaryTolerance);
-    xIndex = std::upper_bound(X.begin(), X.end(), maxX_val) - X.begin();
-  }
-  return xIndex;
-}
-
-/** Zeroes all data points outside the X values given
- *  @param outputWorkspace :: The output workspace - data has already been
- * copied
- *  @param inIndex ::         The workspace index of the spectrum in the input
- * workspace
- *  @param outIndex ::        The workspace index of the spectrum in the output
- * workspace
- */
-void CropWorkspace::cropRagged(API::MatrixWorkspace_sptr outputWorkspace,
-                               int inIndex, int outIndex) {
-  MantidVec &Y = outputWorkspace->dataY(outIndex);
-  MantidVec &E = outputWorkspace->dataE(outIndex);
-  const size_t size = Y.size();
-  size_t startX = this->getXMin(inIndex);
-  if (startX > size)
-    startX = size;
-  for (size_t i = 0; i < startX; ++i) {
-    Y[i] = 0.0;
-    E[i] = 0.0;
-  }
-  size_t endX = this->getXMax(inIndex);
-  if (endX > 0)
-    endX -= m_histogram;
-  for (size_t i = endX; i < size; ++i) {
-    Y[i] = 0.0;
-    E[i] = 0.0;
-  }
-}
 
 } // namespace Algorithms
 } // namespace Mantid
diff --git a/Code/Mantid/Framework/Algorithms/src/ExtractSpectra.cpp b/Code/Mantid/Framework/Algorithms/src/ExtractSpectra.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..2c88e207d9e74e4676452a58ccef3c2b3b511d11
--- /dev/null
+++ b/Code/Mantid/Framework/Algorithms/src/ExtractSpectra.cpp
@@ -0,0 +1,495 @@
+#include "MantidAlgorithms/ExtractSpectra.h"
+
+#include "MantidAPI/MemoryManager.h"
+#include "MantidAPI/NumericAxis.h"
+#include "MantidAPI/TextAxis.h"
+#include "MantidAPI/WorkspaceValidators.h"
+#include "MantidKernel/ArrayProperty.h"
+#include "MantidKernel/BoundedValidator.h"
+#include "MantidKernel/VectorHelper.h"
+
+#include <iostream>
+
+namespace {
+/// The percentage 'fuzziness' to use when comparing to bin boundaries
+const double xBoundaryTolerance = 1.0e-15;
+}
+
+namespace Mantid {
+namespace Algorithms {
+
+using namespace Kernel;
+using namespace API;
+using namespace DataObjects;
+
+// Register the algorithm into the AlgorithmFactory
+DECLARE_ALGORITHM(ExtractSpectra)
+
+//----------------------------------------------------------------------------------------------
+/** Constructor
+ */
+ExtractSpectra::ExtractSpectra()
+    : Algorithm(), m_minX(0), m_maxX(0),
+      m_commonBoundaries(false), m_histogram(false), m_croppingInX(false) {}
+
+//----------------------------------------------------------------------------------------------
+/** Destructor
+ */
+ExtractSpectra::~ExtractSpectra() {}
+
+//----------------------------------------------------------------------------------------------
+
+/// Algorithms name for identification. @see Algorithm::name
+const std::string ExtractSpectra::name() const { return "ExtractSpectra"; }
+
+/// Algorithm's version for identification. @see Algorithm::version
+int ExtractSpectra::version() const { return 1; }
+
+/// Algorithm's category for identification. @see Algorithm::category
+const std::string ExtractSpectra::category() const {
+  return "Transforms\\Splitting";
+}
+
+/// Algorithm's summary for use in the GUI and help. @see Algorithm::summary
+const std::string ExtractSpectra::summary() const {
+  return "Extracts a list of spectra from a workspace and places them in a new "
+         "workspace.";
+}
+
+//----------------------------------------------------------------------------------------------
+/** Initialize the algorithm's properties.
+ */
+void ExtractSpectra::init() {
+  declareProperty(
+      new WorkspaceProperty<>("InputWorkspace", "", Direction::Input),
+      "The input workspace");
+  declareProperty(
+      new WorkspaceProperty<>("OutputWorkspace", "", Direction::Output),
+      "Name of the output workspace");
+
+  declareProperty("XMin", EMPTY_DBL(), "An X value that is within the first "
+                                       "(lowest X value) bin that will be "
+                                       "retained\n"
+                                       "(default: workspace min)");
+  declareProperty("XMax", EMPTY_DBL(), "An X value that is in the highest X "
+                                       "value bin to be retained (default: max "
+                                       "X)");
+  auto mustBePositive = boost::make_shared<BoundedValidator<int>>();
+  mustBePositive->setLower(0);
+  declareProperty("StartWorkspaceIndex", 0, mustBePositive,
+                  "The index number of the first entry in the Workspace that "
+                  "will be loaded\n"
+                  "(default: first entry in the Workspace)");
+  // As the property takes ownership of the validator pointer, have to take care
+  // to pass in a unique pointer to each property.
+  declareProperty(
+      "EndWorkspaceIndex", EMPTY_INT(), mustBePositive,
+      "The index number of the last entry in the Workspace to be loaded\n"
+      "(default: last entry in the Workspace)");
+  declareProperty(
+      new ArrayProperty<specid_t>("SpectrumList"),
+      "A comma-separated list of individual spectra to read.  Only used if\n"
+      "explicitly set.");
+}
+
+//----------------------------------------------------------------------------------------------
+/** Executes the algorithm
+ *  @throw std::out_of_range If a property is set to an invalid value for the
+ * input workspace
+ */
+void ExtractSpectra::exec() {
+  // Get the input workspace
+  m_inputWorkspace = getProperty("InputWorkspace");
+
+  eventW = boost::dynamic_pointer_cast<EventWorkspace>(m_inputWorkspace);
+  if (eventW != NULL) {
+    // Input workspace is an event workspace. Use the other exec method
+    this->execEvent();
+  } else {
+    // Otherwise it's a Workspace2D
+    this->execHistogram();
+  }
+}
+
+/// Execute the algorithm in case of a histogrammed data.
+void ExtractSpectra::execHistogram() {
+  m_histogram = m_inputWorkspace->isHistogramData();
+  // Check for common boundaries in input workspace
+  m_commonBoundaries = WorkspaceHelpers::commonBoundaries(m_inputWorkspace);
+
+  // Retrieve and validate the input properties
+  this->checkProperties();
+
+  // Create the output workspace
+  MatrixWorkspace_sptr outputWorkspace = WorkspaceFactory::Instance().create(
+    m_inputWorkspace, m_spectrumList.size(), m_maxX - m_minX,
+      m_maxX - m_minX - m_histogram);
+
+  // If this is a Workspace2D, get the spectra axes for copying in the spectraNo
+  // later
+  Axis *inAxis1(NULL);
+  TextAxis *outTxtAxis(NULL);
+  NumericAxis *outNumAxis(NULL);
+  if (m_inputWorkspace->axes() > 1) {
+    inAxis1 = m_inputWorkspace->getAxis(1);
+    auto outAxis1 = outputWorkspace->getAxis(1);
+    outTxtAxis = dynamic_cast<TextAxis *>(outAxis1);
+    if (!outTxtAxis) outNumAxis = dynamic_cast<NumericAxis *>(outAxis1);
+  }
+
+  cow_ptr<MantidVec> newX;
+  if (m_commonBoundaries) {
+    const MantidVec &oldX = m_inputWorkspace->readX(m_spectrumList.front());
+    newX.access().assign(oldX.begin() + m_minX, oldX.begin() + m_maxX);
+  }
+  Progress prog(this, 0.0, 1.0, (m_spectrumList.size()));
+  // Loop over the required spectra, copying in the desired bins
+  for (int j = 0; j < static_cast<int>(m_spectrumList.size()); ++j) {
+    auto i = m_spectrumList[j];
+    // Preserve/restore sharing if X vectors are the same
+    if (m_commonBoundaries) {
+      outputWorkspace->setX(j, newX);
+    } else {
+      // Safe to just copy whole vector 'cos can't be cropping in X if not
+      // common
+      outputWorkspace->setX(j, m_inputWorkspace->refX(i));
+    }
+
+    const MantidVec &oldY = m_inputWorkspace->readY(i);
+    outputWorkspace->dataY(j)
+        .assign(oldY.begin() + m_minX, oldY.begin() + (m_maxX - m_histogram));
+    const MantidVec &oldE = m_inputWorkspace->readE(i);
+    outputWorkspace->dataE(j)
+        .assign(oldE.begin() + m_minX, oldE.begin() + (m_maxX - m_histogram));
+
+    // copy over the axis entry for each spectrum, regardless of the type of
+    // axes present
+    if (inAxis1) {
+      if (outTxtAxis) {
+        outTxtAxis->setLabel(j, inAxis1->label(i));
+      } else if (outNumAxis) {
+        outNumAxis->setValue(j, inAxis1->operator()(i));
+      }
+      // spectra axis is handled by copyInfoFrom line
+    }
+    // Copy spectrum number & detectors
+    outputWorkspace->getSpectrum(j)
+        ->copyInfoFrom(*m_inputWorkspace->getSpectrum(i));
+
+    if (!m_commonBoundaries)
+      this->cropRagged(outputWorkspace, i, j);
+
+    // Propagate bin masking if there is any
+    if (m_inputWorkspace->hasMaskedBins(i)) {
+      const MatrixWorkspace::MaskList &inputMasks =
+          m_inputWorkspace->maskedBins(i);
+      MatrixWorkspace::MaskList::const_iterator it;
+      for (it = inputMasks.begin(); it != inputMasks.end(); ++it) {
+        const size_t maskIndex = (*it).first;
+        if (maskIndex >= m_minX && maskIndex < m_maxX - m_histogram)
+          outputWorkspace->flagMasked(j, maskIndex - m_minX, (*it).second);
+      }
+    }
+    prog.report();
+  }
+
+  setProperty("OutputWorkspace", outputWorkspace);
+}
+
+/** Executes the algorithm
+ *  @throw std::out_of_range If a property is set to an invalid value for the
+ * input workspace
+ */
+void ExtractSpectra::execEvent() {
+  m_histogram = m_inputWorkspace->isHistogramData();
+  double minX_val = getProperty("XMin");
+  double maxX_val = getProperty("XMax");
+  if (isEmpty(minX_val))
+    minX_val = eventW->getTofMin();
+  if (isEmpty(maxX_val))
+    maxX_val = eventW->getTofMax();
+
+  // Check for common boundaries in input workspace
+  m_commonBoundaries = WorkspaceHelpers::commonBoundaries(m_inputWorkspace);
+
+  // Retrieve and validate the input properties
+  this->checkProperties();
+  cow_ptr<MantidVec> XValues_new;
+  if (m_commonBoundaries) {
+    const MantidVec &oldX = m_inputWorkspace->readX(m_spectrumList.front());
+    XValues_new.access().assign(oldX.begin() + m_minX, oldX.begin() + m_maxX);
+  }
+  size_t ntcnew = m_maxX - m_minX;
+
+  if (ntcnew < 2) {
+    // create new output X axis
+    std::vector<double> rb_params;
+    rb_params.push_back(minX_val);
+    rb_params.push_back(maxX_val - minX_val);
+    rb_params.push_back(maxX_val);
+    ntcnew = VectorHelper::createAxisFromRebinParams(rb_params,
+                                                     XValues_new.access());
+  }
+
+  // run inplace branch if appropriate
+  MatrixWorkspace_sptr OutputWorkspace = this->getProperty("OutputWorkspace");
+  bool inPlace = (OutputWorkspace == m_inputWorkspace);
+  if (inPlace)
+    g_log.debug("Cropping EventWorkspace in-place.");
+
+  // Create the output workspace
+  EventWorkspace_sptr outputWorkspace =
+      boost::dynamic_pointer_cast<EventWorkspace>(
+          API::WorkspaceFactory::Instance().create(
+              "EventWorkspace", m_spectrumList.size(), ntcnew,
+              ntcnew - m_histogram));
+  eventW->sortAll(TOF_SORT, NULL);
+  outputWorkspace->sortAll(TOF_SORT, NULL);
+  // Copy required stuff from it
+  API::WorkspaceFactory::Instance().initializeFromParent(m_inputWorkspace,
+                                                         outputWorkspace, true);
+
+  Progress prog(this, 0.0, 1.0, 2 * m_spectrumList.size());
+  eventW->sortAll(Mantid::DataObjects::TOF_SORT, &prog);
+  // Loop over the required spectra, copying in the desired bins
+  PARALLEL_FOR2(m_inputWorkspace, outputWorkspace)
+  for (int j = 0; j < static_cast<int>(m_spectrumList.size()); ++j) {
+    PARALLEL_START_INTERUPT_REGION
+    auto i = m_spectrumList[j];
+    const EventList &el = eventW->getEventList(i);
+    // The output event list
+    EventList &outEL = outputWorkspace->getOrAddEventList(j);
+    //    // left side of the crop - will erase 0 -> endLeft
+    //    std::size_t endLeft;
+    //    // right side of the crop - will erase endRight->numEvents+1
+    //    std::size_t endRight;
+
+    switch (el.getEventType()) {
+    case TOF: {
+      std::vector<TofEvent>::const_iterator itev = el.getEvents().begin();
+      std::vector<TofEvent>::const_iterator end = el.getEvents().end();
+      std::vector<TofEvent> moreevents;
+      moreevents.reserve(el.getNumberEvents()); // assume all will make it
+      for (; itev != end; ++itev) {
+        const double tof = itev->tof();
+        if (tof <= maxX_val && tof >= minX_val)
+          moreevents.push_back(*itev);
+      }
+      outEL += moreevents;
+      break;
+    }
+    case WEIGHTED: {
+      std::vector<WeightedEvent>::const_iterator itev =
+          el.getWeightedEvents().begin();
+      std::vector<WeightedEvent>::const_iterator end =
+          el.getWeightedEvents().end();
+      std::vector<WeightedEvent> moreevents;
+      moreevents.reserve(el.getNumberEvents()); // assume all will make it
+      for (; itev != end; ++itev) {
+        const double tof = itev->tof();
+        if (tof <= maxX_val && tof >= minX_val)
+          moreevents.push_back(*itev);
+      }
+      outEL += moreevents;
+      break;
+    }
+    case WEIGHTED_NOTIME: {
+      std::vector<WeightedEventNoTime>::const_iterator itev =
+          el.getWeightedEventsNoTime().begin();
+      std::vector<WeightedEventNoTime>::const_iterator end =
+          el.getWeightedEventsNoTime().end();
+      std::vector<WeightedEventNoTime> moreevents;
+      moreevents.reserve(el.getNumberEvents()); // assume all will make it
+      for (; itev != end; ++itev) {
+        const double tof = itev->tof();
+        if (tof <= maxX_val && tof >= minX_val)
+          moreevents.push_back(*itev);
+      }
+      outEL += moreevents;
+      break;
+    }
+    }
+    outEL.setSortOrder(el.getSortType());
+
+    // Copy spectrum number & detector IDs
+    outEL.copyInfoFrom(el);
+
+    if (!m_commonBoundaries)
+      // If the X axis is NOT common, then keep the initial X axis, just clear
+      // the events
+      outEL.setX(el.dataX());
+    else
+      // Common bin boundaries get all set to the same value
+      outEL.setX(XValues_new);
+
+    // Propagate bin masking if there is any
+    if (m_inputWorkspace->hasMaskedBins(i)) {
+      const MatrixWorkspace::MaskList &inputMasks =
+          m_inputWorkspace->maskedBins(i);
+      MatrixWorkspace::MaskList::const_iterator it;
+      for (it = inputMasks.begin(); it != inputMasks.end(); ++it) {
+        const size_t maskIndex = (*it).first;
+        if (maskIndex >= m_minX && maskIndex < m_maxX - m_histogram)
+          outputWorkspace->flagMasked(j, maskIndex - m_minX, (*it).second);
+      }
+    }
+    // When cropping in place, you can clear out old memory from the input one!
+    if (inPlace) {
+      eventW->getEventList(i).clear();
+      Mantid::API::MemoryManager::Instance().releaseFreeMemory();
+    }
+    prog.report();
+    PARALLEL_END_INTERUPT_REGION
+  }
+  PARALLEL_CHECK_INTERUPT_REGION
+
+  setProperty("OutputWorkspace",
+              boost::dynamic_pointer_cast<MatrixWorkspace>(outputWorkspace));
+}
+
+/** Retrieves the optional input properties and checks that they have valid
+ * values.
+ *  Assigns to the defaults if any property has not been set.
+ *  @throw std::invalid_argument If the input workspace does not have common
+ * binning
+ *  @throw std::out_of_range If a property is set to an invalid value for the
+ * input workspace
+ */
+void ExtractSpectra::checkProperties() {
+  m_minX = this->getXMin();
+  m_maxX = this->getXMax();
+  const size_t xSize = m_inputWorkspace->readX(0).size();
+  if (m_minX > 0 || m_maxX < xSize) {
+    if (m_minX > m_maxX) {
+      g_log.error("XMin must be less than XMax");
+      throw std::out_of_range("XMin must be less than XMax");
+    }
+    if (m_minX == m_maxX && m_commonBoundaries && eventW == NULL) {
+      g_log.error("The X range given lies entirely within a single bin");
+      throw std::out_of_range(
+          "The X range given lies entirely within a single bin");
+    }
+    m_croppingInX = true;
+  }
+  if (!m_commonBoundaries)
+    m_minX = 0;
+  if (!m_commonBoundaries)
+    m_maxX = static_cast<int>(m_inputWorkspace->readX(0).size());
+
+  m_spectrumList = getProperty("SpectrumList");
+
+  if (m_spectrumList.empty()) {
+    int minSpec = getProperty("StartWorkspaceIndex");
+    const int numberOfSpectra =
+        static_cast<int>(m_inputWorkspace->getNumberHistograms());
+    int maxSpec = getProperty("EndWorkspaceIndex");
+    if (isEmpty(maxSpec))
+      maxSpec = numberOfSpectra - 1;
+
+    // Check 'StartSpectrum' is in range 0-numberOfSpectra
+    if (minSpec > numberOfSpectra - 1) {
+      g_log.error("StartWorkspaceIndex out of range!");
+      throw std::out_of_range("StartSpectrum out of range!");
+    }
+    if (maxSpec > numberOfSpectra - 1) {
+      g_log.error("EndWorkspaceIndex out of range!");
+      throw std::out_of_range("EndWorkspaceIndex out of range!");
+    }
+    if (maxSpec < minSpec) {
+      g_log.error("StartWorkspaceIndex must be less than or equal to "
+                  "EndWorkspaceIndex");
+      throw std::out_of_range("StartWorkspaceIndex must be less than or equal "
+                              "to EndWorkspaceIndex");
+    }
+    m_spectrumList.reserve(maxSpec - minSpec + 1);
+    for (specid_t i = minSpec; i <= maxSpec; ++i) {
+      m_spectrumList.push_back(i);
+    }
+  }
+}
+
+/** Find the X index corresponding to (or just within) the value given in the
+ * XMin property.
+ *  Sets the default if the property has not been set.
+ *  @param  wsIndex The workspace index to check (default 0).
+ *  @return The X index corresponding to the XMin value.
+ */
+size_t ExtractSpectra::getXMin(const int wsIndex) {
+  double minX_val = getProperty("XMin");
+  size_t xIndex = 0;
+  if (!isEmpty(minX_val)) { // A value has been passed to the algorithm, check
+                            // it and maybe store it
+    const MantidVec &X = m_inputWorkspace->readX(wsIndex);
+    if (m_commonBoundaries && minX_val > X.back()) {
+      std::stringstream msg;
+      msg << "XMin is greater than the largest X value (" << minX_val << " > "
+          << X.back() << ")";
+      g_log.error(msg.str());
+      throw std::out_of_range(msg.str());
+    }
+    // Reduce cut-off value slightly to allow for rounding errors
+    // when trying to exactly hit a bin boundary.
+    minX_val -= std::abs(minX_val * xBoundaryTolerance);
+    xIndex = std::lower_bound(X.begin(), X.end(), minX_val) - X.begin();
+  }
+  return xIndex;
+}
+
+/** Find the X index corresponding to (or just within) the value given in the
+ * XMax property.
+ *  Sets the default if the property has not been set.
+ *  @param  wsIndex The workspace index to check (default 0).
+ *  @return The X index corresponding to the XMax value.
+ */
+size_t ExtractSpectra::getXMax(const int wsIndex) {
+  const MantidVec &X = m_inputWorkspace->readX(wsIndex);
+  size_t xIndex = X.size();
+  // get the value that the user entered if they entered one at all
+  double maxX_val = getProperty("XMax");
+  if (!isEmpty(maxX_val)) { // we have a user value, check it and maybe store it
+    if (m_commonBoundaries && maxX_val < X.front()) {
+      std::stringstream msg;
+      msg << "XMax is less than the smallest X value (" << maxX_val << " < "
+          << X.front() << ")";
+      g_log.error(msg.str());
+      throw std::out_of_range(msg.str());
+    }
+    // Increase cut-off value slightly to allow for rounding errors
+    // when trying to exactly hit a bin boundary.
+    maxX_val += std::abs(maxX_val * xBoundaryTolerance);
+    xIndex = std::upper_bound(X.begin(), X.end(), maxX_val) - X.begin();
+  }
+  return xIndex;
+}
+
+/** Zeroes all data points outside the X values given
+ *  @param outputWorkspace :: The output workspace - data has already been
+ * copied
+ *  @param inIndex ::         The workspace index of the spectrum in the input
+ * workspace
+ *  @param outIndex ::        The workspace index of the spectrum in the output
+ * workspace
+ */
+void ExtractSpectra::cropRagged(API::MatrixWorkspace_sptr outputWorkspace,
+                                int inIndex, int outIndex) {
+  MantidVec &Y = outputWorkspace->dataY(outIndex);
+  MantidVec &E = outputWorkspace->dataE(outIndex);
+  const size_t size = Y.size();
+  size_t startX = this->getXMin(inIndex);
+  if (startX > size)
+    startX = size;
+  for (size_t i = 0; i < startX; ++i) {
+    Y[i] = 0.0;
+    E[i] = 0.0;
+  }
+  size_t endX = this->getXMax(inIndex);
+  if (endX > 0)
+    endX -= m_histogram;
+  for (size_t i = endX; i < size; ++i) {
+    Y[i] = 0.0;
+    E[i] = 0.0;
+  }
+}
+
+} // namespace Algorithms
+} // namespace Mantid
\ No newline at end of file
diff --git a/Code/Mantid/Framework/Algorithms/src/PDFFourierTransform.cpp b/Code/Mantid/Framework/Algorithms/src/PDFFourierTransform.cpp
index 8cd3cd2118f43f54ed7469f014aefe8930e4d86c..41219d20557743ef17e89f324f9d373a48fc65cf 100644
--- a/Code/Mantid/Framework/Algorithms/src/PDFFourierTransform.cpp
+++ b/Code/Mantid/Framework/Algorithms/src/PDFFourierTransform.cpp
@@ -284,6 +284,10 @@ void PDFFourierTransform::exec() {
       boost::dynamic_pointer_cast<Units::Label>(unit);
   label->setLabel("AtomicDistance", "Angstrom");
   outputWS->setYUnitLabel("PDF");
+
+  outputWS->mutableRun().addProperty("Qmin", qmin, "Angstroms^-1", true);
+  outputWS->mutableRun().addProperty("Qmax", qmax, "Angstroms^-1", true);
+
   MantidVec &outputR = outputWS->dataX(0);
   for (size_t i = 0; i < sizer; i++) {
     outputR[i] = rdelta * static_cast<double>(1 + i);
diff --git a/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp b/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp
index 981b88bad533213d049a998032015861c62c8369..63211e6460e1891541244eb1fd65292140ea4fa4 100644
--- a/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp
+++ b/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp
@@ -77,6 +77,34 @@ using namespace DataObjects;
 // Register the class into the algorithm factory
 DECLARE_ALGORITHM(PlotAsymmetryByLogValue)
 
+// Static member variables
+std::map<int64_t, double> PlotAsymmetryByLogValue::g_redX;
+std::map<int64_t, double> PlotAsymmetryByLogValue::g_redY;
+std::map<int64_t, double> PlotAsymmetryByLogValue::g_redE;
+std::map<int64_t, double> PlotAsymmetryByLogValue::g_greenX;
+std::map<int64_t, double> PlotAsymmetryByLogValue::g_greenY;
+std::map<int64_t, double> PlotAsymmetryByLogValue::g_greenE;
+std::map<int64_t, double> PlotAsymmetryByLogValue::g_sumX;
+std::map<int64_t, double> PlotAsymmetryByLogValue::g_sumY;
+std::map<int64_t, double> PlotAsymmetryByLogValue::g_sumE;
+std::map<int64_t, double> PlotAsymmetryByLogValue::g_diffX;
+std::map<int64_t, double> PlotAsymmetryByLogValue::g_diffY;
+std::map<int64_t, double> PlotAsymmetryByLogValue::g_diffE;
+std::string PlotAsymmetryByLogValue::g_logName;
+std::string PlotAsymmetryByLogValue::g_logFunc;
+std::string PlotAsymmetryByLogValue::g_stype;
+std::vector<int> PlotAsymmetryByLogValue::g_forward_list;
+std::vector<int> PlotAsymmetryByLogValue::g_backward_list;
+int PlotAsymmetryByLogValue::g_red = 1;
+int PlotAsymmetryByLogValue::g_green = EMPTY_INT();
+std::string PlotAsymmetryByLogValue::g_dtcType;
+std::string PlotAsymmetryByLogValue::g_dtcFile;
+std::string PlotAsymmetryByLogValue::g_filenameBase;
+std::string PlotAsymmetryByLogValue::g_filenameExt;
+int PlotAsymmetryByLogValue::g_filenameZeros = 0;
+double PlotAsymmetryByLogValue::g_minTime = EMPTY_DBL();
+double PlotAsymmetryByLogValue::g_maxTime = EMPTY_DBL();
+
 /** Initialisation method. Declares properties to be used in algorithm.
 *
 */
@@ -154,52 +182,34 @@ void PlotAsymmetryByLogValue::init() {
 */
 void PlotAsymmetryByLogValue::exec() {
 
-  // Get properties
-  // Get grouping property
-  m_forward_list = getProperty("ForwardSpectra");
-  m_backward_list = getProperty("BackwardSpectra");
-  m_autogroup = (m_forward_list.size() == 0 && m_backward_list.size() == 0);
-  // Get log value
-  m_logName = getPropertyValue("LogValue");
-  // Get green and red periods
-  m_red = getProperty("Red");
-  m_green = getProperty("Green");
-  // Get type of computation
-  std::string stype = getProperty("Type");
-  m_int = stype == "Integral";
-  // Get type of dead-time corrections
-  m_dtcType = getPropertyValue("DeadTimeCorrType");
-  // Get runs
-  std::string firstFN = getProperty("FirstRun");
-  std::string lastFN = getProperty("LastRun");
-  // Get function to apply to logValue
-  m_logFunc = getPropertyValue("Function");
+  // Check input properties to decide whether or not we can reuse previous
+  // results, if any
+  size_t is, ie;
+  checkProperties(is,ie);
 
-  // Parse run names and get the number of runs
-  parseRunNames( firstFN, lastFN, m_filenameBase, m_filenameExt, m_filenameZeros);
-  size_t is = atoi(firstFN.c_str()); // starting run number
-  size_t ie = atoi(lastFN.c_str());  // last run number
-
-  // Resize vectors that will store results
-  resizeVectors(ie-is+1);
-
-  Progress progress(this, 0, 1, ie - is + 2);
+  Progress progress(this, 0, 1, ie - is + 1);
 
   // Loop through runs
   for (size_t i = is; i <= ie; i++) {
 
-    // Load run, apply dead time corrections and detector grouping
-    Workspace_sptr loadedWs = doLoad(i);
+    // Check if run i was already loaded
+    if ( !g_redX.count(i) ) {
 
-    // Analyse loadedWs
-    doAnalysis (loadedWs, i-is);
+      // Load run, apply dead time corrections and detector grouping
+      Workspace_sptr loadedWs = doLoad(i);
+
+      if ( loadedWs ) {
+        // Analyse loadedWs
+        doAnalysis (loadedWs, i);
+      }
+    }
 
     progress.report();
   }
 
 
   // Create the 2D workspace for the output
-  int nplots = (m_green!= EMPTY_INT()) ? 4 : 1;
+  int nplots = (g_green!= EMPTY_INT()) ? 4 : 1;
   size_t npoints = ie - is + 1;
   MatrixWorkspace_sptr outWS = WorkspaceFactory::Instance().create(
       "Workspace2D",
@@ -211,6 +221,143 @@ void PlotAsymmetryByLogValue::exec() {
   populateOutputWorkspace(outWS,nplots);
   // Assign the result to the output workspace property
   setProperty("OutputWorkspace", outWS);
+
+}
+
+/**  Checks input properties and compares them to previous values
+*   @param is :: [output] Number of the first run
+*   @param ie :: [output] Number of the last run
+*/
+void PlotAsymmetryByLogValue::checkProperties (size_t &is, size_t &ie) {
+
+  // If any of the following properties has a different value from the
+  // previous call, we need to re-do all the computations, which means
+  // clearing static maps that store previous results
+
+  // Log Value
+  std::string logName = getPropertyValue("LogValue");
+  // Get function to apply to logValue
+  std::string logFunc = getPropertyValue("Function");
+  // Get type of computation
+  std::string stype = getPropertyValue("Type");
+  // Get grouping properties
+  std::vector<int> forward_list = getProperty("ForwardSpectra");
+  std::vector<int> backward_list = getProperty("BackwardSpectra");
+  // Get green and red periods
+  int red = getProperty("Red");
+  int green = getProperty("Green");
+  // Get time min and time max
+  double minTime = getProperty("TimeMin");
+  double maxTime = getProperty("TimeMax");
+  // Get type of dead-time corrections
+  std::string dtcType = getPropertyValue("DeadTimeCorrType");
+  std::string dtcFile = getPropertyValue("DeadTimeCorrFile");
+  // Get runs
+  std::string firstFN = getProperty("FirstRun");
+  std::string lastFN = getProperty("LastRun");
+
+  // Parse run names and get the number of runs
+  std::string filenameBase, filenameExt;
+  int filenameZeros;
+  parseRunNames( firstFN, lastFN, filenameBase, filenameExt, filenameZeros);
+  is = atoi(firstFN.c_str()); // starting run number
+  ie = atoi(lastFN.c_str());  // last run number
+  if ( ie < is ) {
+    throw std::runtime_error("First run number is greater than last run number");
+  }
+
+
+  // Skip checks if there are no previous results
+  if ( !g_redX.empty() ) {
+
+    size_t isOld = g_redX.begin()->first; // Old first run number
+    size_t ieOld = g_redX.rbegin()->first; // Old last run number
+
+    // Check if any property has changed
+    if ( g_logName != logName ||
+      g_logFunc != logFunc ||
+      g_stype != stype ||
+      g_forward_list != forward_list ||
+      g_backward_list != backward_list ||
+      g_green != green ||
+      g_red != red ||
+      g_dtcType != dtcType ||
+      g_dtcFile != dtcFile ||
+      g_filenameBase != filenameBase ||
+      g_filenameExt != filenameExt ||
+      g_filenameZeros != filenameZeros ||
+      g_minTime != minTime ||
+      g_maxTime != maxTime) {
+
+        // If so, clear previous results
+        clearResultsFromTo(isOld,ieOld);
+
+    } else {
+
+      // If all of the above are the same, we may re-use previous
+      // results, provided that new run numbers are 'appropriate'
+
+      if ( is > ieOld || ie < isOld ) {
+        // Completely new set of runs
+        clearResultsFromTo(isOld,ieOld);
+
+      } else {
+
+        if ( is > isOld ) {
+          // Remove runs from isOld to is-1
+          clearResultsFromTo(isOld,is-1);
+        }
+        if ( ie < ieOld ) {
+          // Remove runs from ie+1 to ieOld
+          clearResultsFromTo(ie+1,ieOld);
+        }
+
+      } // else
+    } // else
+
+  } // !g_redX.empty()
+
+  // Asign new values to static variables
+  g_logName = logName;
+  g_logFunc = logFunc;
+  g_stype = stype;
+  m_int = g_stype == "Integral";
+  g_forward_list = forward_list;
+  g_backward_list = backward_list;
+  m_autogroup = (g_forward_list.size() == 0 && g_backward_list.size() == 0);
+  g_green = green;
+  g_red = red;
+  g_dtcType = dtcType;
+  g_dtcFile = dtcFile;
+  g_filenameBase = filenameBase;
+  g_filenameExt = filenameExt;
+  g_filenameZeros = filenameZeros;
+  g_minTime = minTime;
+  g_maxTime = maxTime;
+
+}
+
+/**  Clears any possible result from previous call
+*   @param is :: [input] Run number to clear resulst from
+*   @param ie :: [input] Run number to clear results to
+*/
+void PlotAsymmetryByLogValue::clearResultsFromTo(size_t is, size_t ie) {
+
+  for (size_t i=is; i<=ie; i++) {
+    g_redX.erase(i);
+    g_redY.erase(i);
+    g_redE.erase(i);
+    g_greenX.erase(i);
+    g_greenY.erase(i);
+    g_greenE.erase(i);
+    g_sumX.erase(i);
+    g_sumY.erase(i);
+    g_sumE.erase(i);
+    g_diffX.erase(i);
+    g_diffY.erase(i);
+    g_diffE.erase(i);
+  }
+
 }
 
 /**  Loads one run and applies dead-time corrections and detector grouping if required
@@ -220,8 +367,14 @@ Workspace_sptr PlotAsymmetryByLogValue::doLoad (int64_t runNumber ) {
 
   // Get complete run name
   std::ostringstream fn, fnn;
-  fnn << std::setw(m_filenameZeros) << std::setfill('0') << runNumber;
-  fn << m_filenameBase << fnn.str() << m_filenameExt;
+  fnn << std::setw(g_filenameZeros) << std::setfill('0') << runNumber;
+  fn << g_filenameBase << fnn.str() << g_filenameExt;
+
+  // Check if file exists
+  if ( !Poco::File(fn.str()).exists() ) {
+    g_log.warning() << "File " << fn.str() << " not found" << std::endl;
+    return Workspace_sptr();
+  }
 
   // Load run
   IAlgorithm_sptr load = createChildAlgorithm("LoadMuonNexus");
@@ -230,12 +383,12 @@ Workspace_sptr PlotAsymmetryByLogValue::doLoad (int64_t runNumber ) {
   Workspace_sptr loadedWs = load->getProperty("OutputWorkspace");
 
   // Check if dead-time corrections have to be applied
-  if (m_dtcType != "None") {
-    if (m_dtcType == "FromSpecifiedFile") {
+  if (g_dtcType != "None") {
+    if (g_dtcType == "FromSpecifiedFile") {
 
       // If user specifies a file, load corrections now
       Workspace_sptr customDeadTimes;
-      loadCorrectionsFromFile (customDeadTimes, getPropertyValue("DeadTimeCorrFile"));
+      loadCorrectionsFromFile (customDeadTimes, g_dtcFile);
       applyDeadtimeCorr (loadedWs, customDeadTimes);
     } else {
       // Load corrections from run
@@ -276,30 +429,60 @@ void PlotAsymmetryByLogValue::populateOutputWorkspace (MatrixWorkspace_sptr &out
 {
   TextAxis *tAxis = new TextAxis(nplots);
   if (nplots == 1) {
+
+    std::vector<double> vecRedX, vecRedY, vecRedE;
+    for (auto it=g_redX.begin(); it!=g_redX.end(); ++it)
+    {
+      vecRedX.push_back( g_redX[ it->first ] );
+      vecRedY.push_back( g_redY[ it->first ] );
+      vecRedE.push_back( g_redE[ it->first ] );
+    }
+
     tAxis->setLabel(0, "Asymmetry");
-    outWS->dataX(0) = m_redX;
-    outWS->dataY(0) = m_redY;
-    outWS->dataE(0) = m_redE;
+    outWS->dataX(0) = vecRedX;
+    outWS->dataY(0) = vecRedY;
+    outWS->dataE(0) = vecRedE;
   } else {
+
+    std::vector<double> vecRedX, vecRedY, vecRedE;
+    std::vector<double> vecGreenX, vecGreenY, vecGreenE;
+    std::vector<double> vecSumX, vecSumY, vecSumE;
+    std::vector<double> vecDiffX, vecDiffY, vecDiffE;
+    for (auto it=g_redX.begin(); it!=g_redX.end(); ++it)
+    {
+      vecRedX.push_back( g_redX[ it->first ] );
+      vecRedY.push_back( g_redY[ it->first ] );
+      vecRedE.push_back( g_redE[ it->first ] );
+      vecGreenX.push_back( g_greenX[ it->first ] );
+      vecGreenY.push_back( g_greenY[ it->first ] );
+      vecGreenE.push_back( g_greenE[ it->first ] );
+      vecSumX.push_back( g_sumX[ it->first ] );
+      vecSumY.push_back( g_sumY[ it->first ] );
+      vecSumE.push_back( g_sumE[ it->first ] );
+      vecDiffX.push_back( g_diffX[ it->first ] );
+      vecDiffY.push_back( g_diffY[ it->first ] );
+      vecDiffE.push_back( g_diffE[ it->first ] );
+    }
+
     tAxis->setLabel(0, "Red-Green");
     tAxis->setLabel(1, "Red");
     tAxis->setLabel(2, "Green");
     tAxis->setLabel(3, "Red+Green");
-    outWS->dataX(0) = m_diffX;
-    outWS->dataY(0) = m_diffY;
-    outWS->dataE(0) = m_diffE;
-    outWS->dataX(1) = m_redX;
-    outWS->dataY(1) = m_redY;
-    outWS->dataE(1) = m_redE;
-    outWS->dataX(2) = m_greenX;
-    outWS->dataY(2) = m_greenY;
-    outWS->dataE(2) = m_greenE;
-    outWS->dataX(3) = m_sumX;
-    outWS->dataY(3) = m_sumY;
-    outWS->dataE(3) = m_sumE;
+    outWS->dataX(0) = vecDiffX;
+    outWS->dataY(0) = vecDiffY;
+    outWS->dataE(0) = vecDiffE;
+    outWS->dataX(1) = vecRedX;
+    outWS->dataY(1) = vecRedY;
+    outWS->dataE(1) = vecRedE;
+    outWS->dataX(2) = vecGreenX;
+    outWS->dataY(2) = vecGreenY;
+    outWS->dataE(2) = vecGreenE;
+    outWS->dataX(3) = vecSumX;
+    outWS->dataY(3) = vecSumY;
+    outWS->dataE(3) = vecSumE;
   }
   outWS->replaceAxis(1, tAxis);
-  outWS->getAxis(0)->title() = m_logName;
+  outWS->getAxis(0)->title() = g_logName;
   outWS->setYUnitLabel("Asymmetry");
 }
 /**  Parse run names
@@ -442,9 +625,9 @@ void PlotAsymmetryByLogValue::doAnalysis (Workspace_sptr loadedWs, int64_t index
 
       double Y, E;
       calcIntAsymmetry(loadedWs2D, Y, E);
-      m_redX[index]=getLogValue(*loadedWs2D);
-      m_redY[index]=Y;
-      m_redE[index]=E;
+      g_redX[index]=getLogValue(*loadedWs2D);
+      g_redY[index]=Y;
+      g_redE[index]=E;
 
     } else {
 
@@ -457,11 +640,11 @@ void PlotAsymmetryByLogValue::doAnalysis (Workspace_sptr loadedWs, int64_t index
         Workspace2D_sptr memberWs =
             boost::dynamic_pointer_cast<Workspace2D>(loadedGroup->getItem(mi));
         int period = mi + 1;
-        if ( period == m_red ){
+        if ( period == g_red ){
           ws_red = memberWs;
         }
-        if ( m_green!= EMPTY_INT() ){
-          if ( period == m_green ){
+        if ( g_green!= EMPTY_INT() ){
+          if ( period == g_green ){
             ws_green = memberWs;
           }
         }
@@ -472,16 +655,16 @@ void PlotAsymmetryByLogValue::doAnalysis (Workspace_sptr loadedWs, int64_t index
         throw std::invalid_argument("Red period is out of range");
       }
       // Check ws_green
-      if ( (m_green!=EMPTY_INT()) && (!ws_green) ){
+      if ( (g_green!=EMPTY_INT()) && (!ws_green) ){
         throw std::invalid_argument("Green period is out of range");
       }
 
-      if ( m_green==EMPTY_INT() ){
+      if ( g_green==EMPTY_INT() ){
         double Y, E;
         calcIntAsymmetry(ws_red, Y, E);
-        m_redX[index] = getLogValue(*ws_red);
-        m_redY[index] = Y;
-        m_redE[index] = E;
+        g_redX[index] = getLogValue(*ws_red);
+        g_redY[index] = Y;
+        g_redE[index] = E;
 
       } else{
       
@@ -491,23 +674,23 @@ void PlotAsymmetryByLogValue::doAnalysis (Workspace_sptr loadedWs, int64_t index
         calcIntAsymmetry(ws_red, YR, ER);
         calcIntAsymmetry(ws_green, YG, EG);
         // Red data
-        m_redX[index] = logValue;
-        m_redY[index] = YR;
-        m_redE[index] = ER;
+        g_redX[index] = logValue;
+        g_redY[index] = YR;
+        g_redE[index] = ER;
         // Green data
-        m_greenX[index] = logValue;
-        m_greenY[index] = YG;
-        m_greenE[index] = EG;
+        g_greenX[index] = logValue;
+        g_greenY[index] = YG;
+        g_greenE[index] = EG;
         // Sum
-        m_sumX[index] = logValue;
-        m_sumY[index] = YR+YG;
-        m_sumE[index] = sqrt(ER * ER + EG * EG);
+        g_sumX[index] = logValue;
+        g_sumY[index] = YR+YG;
+        g_sumE[index] = sqrt(ER * ER + EG * EG);
         // move to last for safety since some grouping takes place in the
         // calcIntAsymmetry call below
         calcIntAsymmetry(ws_red, ws_green, YR, ER);
-        m_diffX[index] = logValue;
-        m_diffY[index] = YR;
-        m_diffE[index] = ER;
+        g_diffX[index] = logValue;
+        g_diffY[index] = YR;
+        g_diffE[index] = ER;
       }
     } // else loadedGroup
 
@@ -536,8 +719,8 @@ void PlotAsymmetryByLogValue::calcIntAsymmetry(API::MatrixWorkspace_sptr ws,
     asym->setProperty("InputWorkspace", ws);
     asym->setPropertyValue("OutputWorkspace", "tmp");
     if (!m_autogroup) {
-      asym->setProperty("ForwardSpectra", m_forward_list);
-      asym->setProperty("BackwardSpectra", m_backward_list);
+      asym->setProperty("ForwardSpectra", g_forward_list);
+      asym->setProperty("BackwardSpectra", g_backward_list);
     }
     asym->execute();
     MatrixWorkspace_sptr asymWS = asym->getProperty("OutputWorkspace");
@@ -571,8 +754,8 @@ void PlotAsymmetryByLogValue::calcIntAsymmetry(API::MatrixWorkspace_sptr ws,
     asym->setProperty("InputWorkspace", intWS);
     asym->setPropertyValue("OutputWorkspace", "tmp");
     if (!m_autogroup) {
-      asym->setProperty("ForwardSpectra", m_forward_list);
-      asym->setProperty("BackwardSpectra", m_backward_list);
+      asym->setProperty("ForwardSpectra", g_forward_list);
+      asym->setProperty("BackwardSpectra", g_backward_list);
     }
     asym->execute();
     MatrixWorkspace_sptr out = asym->getProperty("OutputWorkspace");
@@ -595,10 +778,10 @@ PlotAsymmetryByLogValue::calcIntAsymmetry(API::MatrixWorkspace_sptr ws_red,
                                           API::MatrixWorkspace_sptr ws_green,
                                           double &Y, double &E) {
   if (!m_autogroup) {
-    groupDetectors(ws_red, m_backward_list);
-    groupDetectors(ws_red, m_forward_list);
-    groupDetectors(ws_green, m_backward_list);
-    groupDetectors(ws_green, m_forward_list);
+    groupDetectors(ws_red, g_backward_list);
+    groupDetectors(ws_red, g_forward_list);
+    groupDetectors(ws_green, g_backward_list);
+    groupDetectors(ws_green, g_forward_list);
   }
 
   Property *startXprop = getProperty("TimeMin");
@@ -692,28 +875,6 @@ PlotAsymmetryByLogValue::groupDetectors(API::MatrixWorkspace_sptr &ws,
   ws = group->getProperty("OutputWorkspace");
 }
 
-/**  Resize vectors that will store results.
- *  @param size :: The size of the vectors
- */
-void PlotAsymmetryByLogValue::resizeVectors(size_t size) {
-
-  // Red vectors
-  m_redX.resize(size);
-  m_redY.resize(size);
-  m_redE.resize(size);
-  // Green vectors
-  m_greenX.resize(size);
-  m_greenY.resize(size);
-  m_greenE.resize(size);
-  // Diff vectors
-  m_diffX.resize(size);
-  m_diffY.resize(size);
-  m_diffE.resize(size);
-  // Sum vectors
-  m_sumX.resize(size);
-  m_sumY.resize(size);
-  m_sumE.resize(size);
-}
 /**
  * Get log value from a workspace. Convert to double if possible.
  *
@@ -723,27 +884,40 @@ void PlotAsymmetryByLogValue::resizeVectors(size_t size) {
  *doesn't exist.
  */
 double PlotAsymmetryByLogValue::getLogValue(MatrixWorkspace &ws) {
-  auto *property = ws.run().getLogData(m_logName);
+
+  const Run& run = ws.run();
+
+  // Get the start & end time for the run
+  Mantid::Kernel::DateAndTime start, end;
+  if ( run.hasProperty("run_start") && run.hasProperty("run_end") )
+  {
+    start = run.getProperty("run_start")->value();
+    end = run.getProperty("run_end")->value();
+  }
+
+  auto *property = run.getLogData(g_logName);
   if (!property) {
-    throw std::invalid_argument("Log " + m_logName + " does not exist.");
+    throw std::invalid_argument("Log " + g_logName + " does not exist.");
   }
+  property->filterByTime(start, end);
+
   double value = 0;
   // try different property types
-  if (convertLogToDouble<double>(property, value, m_logFunc))
+  if (convertLogToDouble<double>(property, value, g_logFunc))
     return value;
-  if (convertLogToDouble<float>(property, value, m_logFunc))
+  if (convertLogToDouble<float>(property, value, g_logFunc))
     return value;
-  if (convertLogToDouble<int>(property, value, m_logFunc))
+  if (convertLogToDouble<int>(property, value, g_logFunc))
     return value;
-  if (convertLogToDouble<long>(property, value, m_logFunc))
+  if (convertLogToDouble<long>(property, value, g_logFunc))
     return value;
-  if (convertLogToDouble<long long>(property, value, m_logFunc))
+  if (convertLogToDouble<long long>(property, value, g_logFunc))
     return value;
-  if (convertLogToDouble<unsigned int>(property, value, m_logFunc))
+  if (convertLogToDouble<unsigned int>(property, value, g_logFunc))
     return value;
-  if (convertLogToDouble<unsigned long>(property, value, m_logFunc))
+  if (convertLogToDouble<unsigned long>(property, value, g_logFunc))
     return value;
-  if (convertLogToDouble<unsigned long long>(property, value, m_logFunc))
+  if (convertLogToDouble<unsigned long long>(property, value, g_logFunc))
     return value;
   // try if it's a string and can be lexically cast to double
   auto slog =
@@ -758,7 +932,7 @@ double PlotAsymmetryByLogValue::getLogValue(MatrixWorkspace &ws) {
     }
   }
 
-  throw std::invalid_argument("Log " + m_logName +
+  throw std::invalid_argument("Log " + g_logName +
                               " cannot be converted to a double type.");
 }
 
diff --git a/Code/Mantid/Framework/Algorithms/src/RemoveMaskedSpectra.cpp b/Code/Mantid/Framework/Algorithms/src/RemoveMaskedSpectra.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..d6961fc18e1e96c75cc9a0a2cd59f787e20a6428
--- /dev/null
+++ b/Code/Mantid/Framework/Algorithms/src/RemoveMaskedSpectra.cpp
@@ -0,0 +1,125 @@
+#include "MantidAlgorithms/RemoveMaskedSpectra.h"
+
+#include "MantidAPI/NumericAxis.h"
+#include "MantidAPI/TextAxis.h"
+#include "MantidAPI/WorkspaceFactory.h"
+#include "MantidDataObjects/MaskWorkspace.h"
+
+namespace Mantid {
+namespace Algorithms {
+
+using namespace Kernel;
+using namespace API;
+
+// Register the algorithm into the AlgorithmFactory
+DECLARE_ALGORITHM(RemoveMaskedSpectra)
+
+//----------------------------------------------------------------------------------------------
+/** Constructor
+ */
+RemoveMaskedSpectra::RemoveMaskedSpectra() {}
+
+//----------------------------------------------------------------------------------------------
+/** Destructor
+ */
+RemoveMaskedSpectra::~RemoveMaskedSpectra() {}
+
+//----------------------------------------------------------------------------------------------
+
+/// Algorithms name for identification. @see Algorithm::name
+const std::string RemoveMaskedSpectra::name() const {
+  return "RemoveMaskedSpectra";
+}
+
+/// Algorithm's version for identification. @see Algorithm::version
+int RemoveMaskedSpectra::version() const { return 1; }
+
+/// Algorithm's category for identification. @see Algorithm::category
+const std::string RemoveMaskedSpectra::category() const {
+  return "Transforms\\Splitting";
+}
+
+/// Algorithm's summary for use in the GUI and help. @see Algorithm::summary
+const std::string RemoveMaskedSpectra::summary() const {
+  return "Extracts unmasked spectra from a workspace and places them in a new "
+         "workspace.";
+}
+
+//----------------------------------------------------------------------------------------------
+/** Initialize the algorithm's properties.
+ */
+void RemoveMaskedSpectra::init() {
+  declareProperty(
+      new WorkspaceProperty<>("InputWorkspace", "", Direction::Input),
+      "An input workspace.");
+  declareProperty(new WorkspaceProperty<>("MaskedWorkspace", "",
+                                          Direction::Input,
+                                          PropertyMode::Optional),
+                  "If given but not as a MaskWorkspace, the masking from "
+                  "this workspace will be used. If given as a "
+                  "MaskWorkspace, the masking is read from its Y values.");
+  declareProperty(
+      new WorkspaceProperty<>("OutputWorkspace", "", Direction::Output),
+      "An output workspace.");
+}
+
+//----------------------------------------------------------------------------------------------
+/** Execute the algorithm.
+ */
+void RemoveMaskedSpectra::exec() {
+  MatrixWorkspace_sptr inputWorkspace = getProperty("InputWorkspace");
+  MatrixWorkspace_sptr maskedWorkspace = getProperty("MaskedWorkspace");
+
+  if (!maskedWorkspace){
+    maskedWorkspace = inputWorkspace;
+  } else if (inputWorkspace->getNumberHistograms() != maskedWorkspace->getNumberHistograms()) {
+    throw std::runtime_error("Masked workspace has a different number of spectra.");
+  }
+
+  // Find indices of the unmasked spectra.
+  std::vector<specid_t> indices;
+  makeIndexList(indices, maskedWorkspace.get());
+
+  auto extract = createChildAlgorithm("ExtractSpectra", 0, 1);
+  extract->initialize();
+  extract->setRethrows(true);
+
+  extract->setProperty("InputWorkspace", inputWorkspace);
+  extract->setProperty("SpectrumList", indices);
+
+  extract->execute();
+
+  MatrixWorkspace_sptr outputWorkspace = extract->getProperty("OutputWorkspace");
+  setProperty("OutputWorkspace", outputWorkspace);
+}
+
+//----------------------------------------------------------------------------------------------
+/// Fill in a vector with spectra indices to be extracted.
+/// @param indices :: A reference to a vector to fill with the indices.
+/// @param maskedWorkspace :: A workspace with masking information.
+void RemoveMaskedSpectra::makeIndexList(
+    std::vector<specid_t> &indices, const API::MatrixWorkspace *maskedWorkspace) {
+  auto mask = dynamic_cast<const DataObjects::MaskWorkspace *>(maskedWorkspace);
+  if (mask) {
+    for (size_t i = 0; i < mask->getNumberHistograms(); ++i) {
+      if (mask->readY(i)[0] == 0.0) {
+        indices.push_back(static_cast<specid_t>(i));
+      }
+    }
+  } else {
+    for (size_t i = 0; i < maskedWorkspace->getNumberHistograms(); ++i) {
+      Geometry::IDetector_const_sptr det;
+      try {
+        det = maskedWorkspace->getDetector(i);
+      } catch (Exception::NotFoundError &) {
+        continue;
+      }
+      if (!det->isMasked()) {
+        indices.push_back(static_cast<specid_t>(i));
+      }
+    }
+  }
+}
+
+} // namespace Algorithms
+} // namespace Mantid
\ No newline at end of file
diff --git a/Code/Mantid/Framework/Algorithms/src/SofQW.cpp b/Code/Mantid/Framework/Algorithms/src/SofQW.cpp
index 7ff76a9141a3584e78e176806e9649600cfe0645..6e78382c7a7ca3194014c658e54544e04cd43fee 100644
--- a/Code/Mantid/Framework/Algorithms/src/SofQW.cpp
+++ b/Code/Mantid/Framework/Algorithms/src/SofQW.cpp
@@ -162,6 +162,9 @@ SofQW::setUpOutputWorkspace(API::MatrixWorkspace_const_sptr inputWorkspace,
   // Set the X axis title (for conversion to MD)
   outputWorkspace->getAxis(0)->title() = "Energy transfer";
 
+  outputWorkspace->setYUnit("");
+  outputWorkspace->setYUnitLabel("Intensity");
+
   return outputWorkspace;
 }
 
diff --git a/Code/Mantid/Framework/Algorithms/src/SofQWCentre.cpp b/Code/Mantid/Framework/Algorithms/src/SofQWCentre.cpp
index 6e9fb5a0e8e5a949ff0a0f4ac1abda92f78b8fd0..191d8fccd0f7df69356ed956eb33a99f1425c31c 100644
--- a/Code/Mantid/Framework/Algorithms/src/SofQWCentre.cpp
+++ b/Code/Mantid/Framework/Algorithms/src/SofQWCentre.cpp
@@ -291,6 +291,9 @@ SofQWCentre::setUpOutputWorkspace(API::MatrixWorkspace_const_sptr inputWorkspace
   // Set the X axis title (for conversion to MD)
   outputWorkspace->getAxis(0)->title() = "Energy transfer";
 
+  outputWorkspace->setYUnit("");
+  outputWorkspace->setYUnitLabel("Intensity");
+
   return outputWorkspace;
 }
 
diff --git a/Code/Mantid/Framework/Algorithms/src/SofQWNormalisedPolygon.cpp b/Code/Mantid/Framework/Algorithms/src/SofQWNormalisedPolygon.cpp
index 3058d0290961ba745250b308066608f5222d044b..08aac98e65bce79dda83cf9cbae9348c3a58127c 100644
--- a/Code/Mantid/Framework/Algorithms/src/SofQWNormalisedPolygon.cpp
+++ b/Code/Mantid/Framework/Algorithms/src/SofQWNormalisedPolygon.cpp
@@ -411,6 +411,9 @@ SofQWNormalisedPolygon::setUpOutputWorkspace(API::MatrixWorkspace_const_sptr inp
   // Set the X axis title (for conversion to MD)
   outputWorkspace->getAxis(0)->title() = "Energy transfer";
 
+  outputWorkspace->setYUnit("");
+  outputWorkspace->setYUnitLabel("Intensity");
+
   return outputWorkspace;
 }
 
diff --git a/Code/Mantid/Framework/Algorithms/test/ConvertUnitsUsingDetectorTableTest.h b/Code/Mantid/Framework/Algorithms/test/ConvertUnitsUsingDetectorTableTest.h
new file mode 100644
index 0000000000000000000000000000000000000000..e17df8dd0c4c3e420a96dbff43bc8f9bf8fce023
--- /dev/null
+++ b/Code/Mantid/Framework/Algorithms/test/ConvertUnitsUsingDetectorTableTest.h
@@ -0,0 +1,98 @@
+#ifndef MANTID_ALGORITHMS_CONVERTUNITSUSINGDETECTORTABLETEST_H_
+#define MANTID_ALGORITHMS_CONVERTUNITSUSINGDETECTORTABLETEST_H_
+
+#include <cxxtest/TestSuite.h>
+
+#include "MantidAlgorithms/ConvertUnitsUsingDetectorTable.h"
+
+#include "MantidTestHelpers/WorkspaceCreationHelper.h"
+
+#include "MantidAPI/AnalysisDataService.h"
+#include "MantidAPI/TableRow.h"
+#include "MantidKernel/UnitFactory.h"
+
+using Mantid::Algorithms::ConvertUnitsUsingDetectorTable;
+using namespace Mantid;
+using namespace Mantid::Kernel;
+using namespace Mantid::API;
+using namespace Mantid::Algorithms;
+using namespace Mantid::DataObjects;
+using namespace Mantid::Geometry;
+
+class ConvertUnitsUsingDetectorTableTest : public CxxTest::TestSuite
+{
+public:
+  // This pair of boilerplate methods prevent the suite being created statically
+  // This means the constructor isn't called when running other tests
+  static ConvertUnitsUsingDetectorTableTest *createSuite() { return new ConvertUnitsUsingDetectorTableTest(); }
+  static void destroySuite( ConvertUnitsUsingDetectorTableTest *suite ) { delete suite; }
+
+
+  void test_Init()
+  {
+    ConvertUnitsUsingDetectorTable alg;
+    TS_ASSERT_THROWS_NOTHING( alg.initialize() );
+    TS_ASSERT( alg.isInitialized() );
+  }
+
+
+  // TODO: Make this test useful
+  void test_TofToLambda()
+  {
+     ConvertUnitsUsingDetectorTable myAlg;
+     myAlg.initialize();
+     TS_ASSERT(myAlg.isInitialized());
+
+     const std::string workspaceName("_ws_testConvertUsingDetectorTable");
+     int nBins = 10;
+     MatrixWorkspace_sptr WS = WorkspaceCreationHelper::Create2DWorkspaceBinned(2, nBins, 500.0, 50.0);
+     WS->getAxis(0)->unit() = UnitFactory::Instance().create("TOF");
+
+     AnalysisDataService::Instance().add(workspaceName,WS);
+
+      // Create TableWorkspace with values in it
+
+      ITableWorkspace_sptr pars = WorkspaceFactory::Instance().createTable("TableWorkspace");
+      pars->addColumn("int", "spectra");
+      pars->addColumn("double", "l1");
+      pars->addColumn("double", "l2");
+      pars->addColumn("double", "twotheta");
+      pars->addColumn("double", "efixed");
+      pars->addColumn("int", "emode");
+
+      API::TableRow row0 = pars->appendRow();
+      row0 << 1 << 100.0 << 10.0 << 90.0 << 7.0 << 0;
+
+      API::TableRow row1 = pars->appendRow();
+      row1 << 2 << 1.0 << 1.0 << 90.0 << 7.0 << 0;
+
+      // Set the properties
+      myAlg.setRethrows(true);
+      myAlg.setPropertyValue("InputWorkspace", workspaceName);
+      myAlg.setPropertyValue("OutputWorkspace", workspaceName);
+      myAlg.setPropertyValue("Target", "Wavelength");
+      myAlg.setProperty("DetectorParameters", pars);
+
+      myAlg.execute();
+
+      auto outWS = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(workspaceName);
+
+//      for (int j=0; j < outWS->getNumberHistograms(); ++j) {
+//          for (int i=0; i < outWS->blocksize(); ++i) {
+//              std::cout << "dataX[" << j << "]["<< i << "] = " << outWS->dataX(j)[i] << std::endl;
+//          }
+//      }
+
+      TS_ASSERT_DELTA( outWS->dataX(0)[0], 0.017982, 0.000001 );
+      TS_ASSERT_DELTA( outWS->dataX(0)[9], 0.034166, 0.000001 );
+//      TS_ASSERT_DELTA( outWS->dataX(1)[0], 0.179818, 0.000001 );
+//      TS_ASSERT_DELTA( outWS->dataX(1)[9], 0.017982, 0.000001 );
+
+      AnalysisDataService::Instance().remove(workspaceName);
+  }
+
+
+};
+
+
+#endif /* MANTID_ALGORITHMS_CONVERTUNITSUSINGDETECTORTABLETEST_H_ */
diff --git a/Code/Mantid/Framework/Algorithms/test/CropWorkspaceTest.h b/Code/Mantid/Framework/Algorithms/test/CropWorkspaceTest.h
index 3f75fd14f9fc703388f09e2b45127d18fb1ed03a..5414be98f424b449d312caa3f5f3ca1aeb35fb21 100644
--- a/Code/Mantid/Framework/Algorithms/test/CropWorkspaceTest.h
+++ b/Code/Mantid/Framework/Algorithms/test/CropWorkspaceTest.h
@@ -130,6 +130,7 @@ public:
     TS_ASSERT_THROWS_NOTHING( algo.setPropertyValue("EndWorkspaceIndex","4") );
     TS_ASSERT(algo.execute());
     TS_ASSERT(algo.isExecuted());
+    if ( !algo.isExecuted() ) return;
 
     // verify the output workspace
     ws = AnalysisDataService::Instance().retrieveWS<EventWorkspace>(eventname);
@@ -158,6 +159,7 @@ public:
 
     TS_ASSERT_THROWS_NOTHING( crop.execute() );
     TS_ASSERT( crop.isExecuted() );
+    if ( !crop.isExecuted() ) return;
 
     MatrixWorkspace_const_sptr output;
     TS_ASSERT_THROWS_NOTHING( output = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(outputWS) );
@@ -189,6 +191,7 @@ public:
     TS_ASSERT_THROWS_NOTHING( crop2.setPropertyValue("OutputWorkspace","unCropped") );
     TS_ASSERT_THROWS_NOTHING( crop2.execute() );
     TS_ASSERT( crop2.isExecuted() );
+    if ( !crop2.isExecuted() ) return;
 
     MatrixWorkspace_const_sptr output;
     TS_ASSERT_THROWS_NOTHING( output = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>("unCropped") );
@@ -229,6 +232,7 @@ public:
     TS_ASSERT_THROWS_NOTHING( crop3.setPropertyValue("OutputWorkspace","pointOut") );
     TS_ASSERT_THROWS_NOTHING( crop3.execute() );
     TS_ASSERT( crop3.isExecuted() );
+    if ( !crop3.isExecuted() ) return;
 
     MatrixWorkspace_const_sptr output;
     TS_ASSERT_THROWS_NOTHING( output = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>("pointOut") );
@@ -273,6 +277,7 @@ public:
     TS_ASSERT_THROWS_NOTHING( crop4.setPropertyValue("XMax","4.1") );
     TS_ASSERT_THROWS_NOTHING( crop4.execute() );
     TS_ASSERT( crop4.isExecuted() );
+    if ( !crop4.isExecuted() ) return;
     
     MatrixWorkspace_const_sptr output;
     TS_ASSERT_THROWS_NOTHING( output = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>("raggedOut") );
@@ -311,6 +316,7 @@ public:
     TS_ASSERT_THROWS_NOTHING( crop4.setPropertyValue("XMax","5.1") );
     TS_ASSERT_THROWS_NOTHING( crop4.execute() );
     TS_ASSERT( crop4.isExecuted() );
+    if ( !crop4.isExecuted() ) return;
 
     MatrixWorkspace_const_sptr output;
     TS_ASSERT_THROWS_NOTHING( output = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>("raggedOut") );
@@ -383,6 +389,7 @@ public:
     alg->setPropertyValue("OutputWorkspace",wsName);
     alg->execute();
     TS_ASSERT(alg->isExecuted());
+    if ( !alg->isExecuted() ) return;
 
     // Check the output
     MatrixWorkspace_sptr outputWS;
diff --git a/Code/Mantid/Framework/Algorithms/test/ExtractSpectraTest.h b/Code/Mantid/Framework/Algorithms/test/ExtractSpectraTest.h
new file mode 100644
index 0000000000000000000000000000000000000000..34aa79fb0b19bc2fcf031e7f430cf995ea79c39d
--- /dev/null
+++ b/Code/Mantid/Framework/Algorithms/test/ExtractSpectraTest.h
@@ -0,0 +1,516 @@
+#ifndef MANTID_ALGORITHMS_EXTRACTSPECTRATEST_H_
+#define MANTID_ALGORITHMS_EXTRACTSPECTRATEST_H_
+
+#include <cxxtest/TestSuite.h>
+
+#include "MantidAlgorithms/ExtractSpectra.h"
+#include "MantidDataObjects/EventWorkspace.h"
+#include "MantidKernel/EmptyValues.h"
+#include "MantidKernel/UnitFactory.h"
+#include "MantidTestHelpers/ComponentCreationHelper.h"
+#include "MantidTestHelpers/WorkspaceCreationHelper.h"
+
+using Mantid::Algorithms::ExtractSpectra;
+using namespace Mantid::API;
+using namespace Mantid::Kernel;
+using namespace Mantid::DataObjects;
+using namespace Mantid;
+
+class ExtractSpectraTest : public CxxTest::TestSuite
+{
+public:
+  // This pair of boilerplate methods prevent the suite being created statically
+  // This means the constructor isn't called when running other tests
+  static ExtractSpectraTest *createSuite() { return new ExtractSpectraTest(); }
+  static void destroySuite( ExtractSpectraTest *suite ) { 
+    AnalysisDataService::Instance().clear();
+    delete suite; 
+  }
+
+  ExtractSpectraTest()
+      : nSpec(5), nBins(6),
+        outWSName("ExtractSpectraTest_OutputWS") {}
+
+  void test_Init()
+  {
+    ExtractSpectra alg;
+    TS_ASSERT_THROWS_NOTHING( alg.initialize() )
+    TS_ASSERT( alg.isInitialized() )
+  }
+
+  void test_defaults()
+  {
+    Parameters params;
+    auto ws = runAlgorithm(params);
+    if (!ws) return;
+    TS_ASSERT_EQUALS(ws->getNumberHistograms(), nSpec);
+    TS_ASSERT_EQUALS(ws->blocksize(), nBins);
+
+    TS_ASSERT_EQUALS(ws->readX(0)[0], 0.0);
+    TS_ASSERT_EQUALS(ws->readX(0)[1], 1.0);
+    TS_ASSERT_EQUALS(ws->readX(0)[2], 2.0);
+    TS_ASSERT_EQUALS(ws->readX(0)[3], 3.0);
+    TS_ASSERT_EQUALS(ws->readX(0)[4], 4.0);
+    TS_ASSERT_EQUALS(ws->readX(0)[5], 5.0);
+    TS_ASSERT_EQUALS(ws->readX(0)[6], 6.0);
+  }
+
+  // ---- test histo ----
+
+  void test_x_range()
+  {
+    Parameters params;
+    params.setXRange();
+
+    auto ws = runAlgorithm(params);
+    if (!ws) return;
+
+    TS_ASSERT_EQUALS(ws->getNumberHistograms(), nSpec);
+    params.testXRange(*ws);
+  }
+
+  void test_index_range()
+  {
+    Parameters params;
+    params.setIndexRange();
+
+    auto ws = runAlgorithm(params);
+    if (!ws) return;
+
+    TS_ASSERT_EQUALS(ws->blocksize(), nBins);
+    params.testIndexRange(*ws);
+  }
+
+  void test_spectrum_list()
+  {
+    Parameters params;
+    params.setSpectrumList();
+
+    auto ws = runAlgorithm(params);
+    if (!ws) return;
+
+    TS_ASSERT_EQUALS(ws->blocksize(), nBins);
+    params.testSpectrumList(*ws);
+  }
+
+  void test_index_and_spectrum_list()
+  {
+    Parameters params;
+    params.setSpectrumList().setIndexRange();
+
+    auto ws = runAlgorithm(params);
+    if (!ws) return;
+
+    TS_ASSERT_EQUALS(ws->blocksize(), nBins);
+    params.testSpectrumList(*ws);
+  }
+
+  void test_x_range_and_spectrum_list()
+  {
+    Parameters params;
+    params.setSpectrumList().setXRange();
+
+    auto ws = runAlgorithm(params);
+    if (!ws) return;
+
+    params.testXRange(*ws);
+    params.testSpectrumList(*ws);
+  }
+
+  void test_invalid_x_range()
+  {
+    Parameters params;
+    params.setInvalidXRange();
+
+    auto ws = runAlgorithm(params, false);
+  }
+
+  void test_invalid_index_range()
+  {
+    {
+      Parameters params;
+      params.setInvalidIndexRange();
+      auto ws = runAlgorithm(params, false);
+    }
+    {
+      Parameters params;
+      params.setInvalidIndexRange1();
+      auto ws = runAlgorithm(params, false);
+    }
+  }
+
+
+  // ---- test event ----
+
+  void test_x_range_event()
+  {
+    Parameters params("event");
+    params.setXRange();
+
+    auto ws = runAlgorithm(params);
+    if (!ws) return;
+
+    TS_ASSERT_EQUALS(ws->getNumberHistograms(), nSpec);
+    params.testXRange(*ws);
+  }
+
+  void test_index_range_event()
+  {
+    Parameters params("event");
+    params.setIndexRange();
+
+    auto ws = runAlgorithm(params);
+    if (!ws) return;
+
+    TS_ASSERT_EQUALS(ws->blocksize(), nBins);
+    params.testIndexRange(*ws);
+  }
+
+  void test_spectrum_list_event()
+  {
+    Parameters params("event");
+    params.setSpectrumList();
+
+    auto ws = runAlgorithm(params);
+    if (!ws) return;
+
+    TS_ASSERT_EQUALS(ws->blocksize(), nBins);
+    params.testSpectrumList(*ws);
+  }
+
+  void test_index_and_spectrum_list_event()
+  {
+    Parameters params("event");
+    params.setSpectrumList().setIndexRange();
+
+    auto ws = runAlgorithm(params);
+    if (!ws) return;
+
+    TS_ASSERT_EQUALS(ws->blocksize(), nBins);
+    params.testSpectrumList(*ws);
+  }
+
+  void test_x_range_and_spectrum_list_event()
+  {
+    Parameters params("event");
+    params.setSpectrumList().setXRange();
+
+    auto ws = runAlgorithm(params);
+    if (!ws) return;
+
+    params.testXRange(*ws);
+    params.testSpectrumList(*ws);
+  }
+
+  void test_invalid_x_range_event()
+  {
+    Parameters params("event");
+    params.setInvalidXRange();
+    auto ws = runAlgorithm(params, true);
+    // this is a bit unexpected but at least no crash
+    TS_ASSERT_EQUALS(ws->getNumberHistograms(), nSpec);
+    TS_ASSERT_EQUALS(ws->blocksize(), 1);
+    TS_ASSERT_EQUALS(ws->readX(0)[0], 2);
+    TS_ASSERT_EQUALS(ws->readX(0)[1], 1);
+  }
+
+  void test_invalid_index_range_event()
+  {
+    {
+      Parameters params("event");
+      params.setInvalidIndexRange();
+      auto ws = runAlgorithm(params, false);
+    }
+    {
+      Parameters params("event");
+      params.setInvalidIndexRange1();
+      auto ws = runAlgorithm(params, false);
+    }
+  }
+  // ---- test histo-ragged ----
+
+  void test_x_range_ragged()
+  {
+    Parameters params("histo-ragged");
+    params.setXRange();
+
+    auto ws = runAlgorithm(params);
+    if (!ws) return;
+
+    TS_ASSERT_EQUALS(ws->getNumberHistograms(), nSpec);
+    params.testXRange(*ws);
+  }
+
+  void test_index_range_ragged()
+  {
+    Parameters params("histo-ragged");
+    params.setIndexRange();
+
+    auto ws = runAlgorithm(params);
+    if (!ws) return;
+
+    TS_ASSERT_EQUALS(ws->blocksize(), nBins);
+    params.testIndexRange(*ws);
+  }
+
+  void test_spectrum_list_ragged()
+  {
+    Parameters params("histo-ragged");
+    params.setSpectrumList();
+
+    auto ws = runAlgorithm(params);
+    if (!ws) return;
+
+    TS_ASSERT_EQUALS(ws->blocksize(), nBins);
+    params.testSpectrumList(*ws);
+  }
+
+  void xtest_invalid_x_range_ragged()
+  {
+    Parameters params("histo-ragged");
+    params.setInvalidXRange();
+
+    auto ws = runAlgorithm(params, false);
+  }
+
+private:
+
+  // -----------------------  helper methods ------------------------
+
+  const size_t nSpec;
+  const size_t nBins;
+  const std::string outWSName;
+
+  MatrixWorkspace_sptr createInputWorkspace(const std::string& workspaceType) const
+  {
+    if (workspaceType == "histo")
+      return createInputWorkspaceHisto();
+    else if (workspaceType == "event")
+      return createInputWorkspaceEvent();
+    else if (workspaceType == "histo-ragged")
+      return createInputWorkspaceHistoRagged();
+    throw std::runtime_error("Undefined workspace type");
+  }
+
+  MatrixWorkspace_sptr createInputWorkspaceHisto() const
+  {
+    // Set up a small workspace for testing
+    MatrixWorkspace_sptr space = WorkspaceFactory::Instance().create("Workspace2D", nSpec, nBins+1, nBins);
+    for (size_t j = 0; j < nSpec; ++j) {
+      for (size_t k = 0; k <= nBins; ++k) {
+        space->dataX(j)[k] = double(k);
+      }
+      space->dataY(j).assign(nBins, double(j));
+      space->dataE(j).assign(nBins, sqrt(double(j)));
+    }
+    return space;
+  }
+
+  MatrixWorkspace_sptr createInputWorkspaceHistoRagged() const
+  {
+    // Set up a small workspace for testing
+    MatrixWorkspace_sptr space = WorkspaceFactory::Instance().create("Workspace2D", nSpec, nBins+1, nBins);
+    for (size_t j = 0; j < nSpec; ++j) {
+      for (size_t k = 0; k <= nBins; ++k) {
+        space->dataX(j)[k] = double(j + k);
+      }
+      space->dataY(j).assign(nBins, double(j+1));
+      space->dataE(j).assign(nBins, sqrt(double(j+1)));
+    }
+    return space;
+  }
+
+  MatrixWorkspace_sptr createInputWorkspaceEvent() const
+  {
+    EventWorkspace_sptr ws = WorkspaceCreationHelper::CreateEventWorkspace(int(nSpec), int(nBins), 50, 0.0, 1., 2);
+    ws->getAxis(0)->unit() = UnitFactory::Instance().create("TOF");
+    ws->setInstrument( ComponentCreationHelper::createTestInstrumentCylindrical(1) );
+    for(size_t i = 0; i < ws->getNumberHistograms(); ++i)
+    {
+      ws->getSpectrum(i)->setDetectorID(detid_t(i + 1));
+    }
+    return ws;
+  }
+
+  struct Parameters
+  {
+    Parameters(const std::string& workspaceType = "histo")
+        : XMin(EMPTY_DBL()), XMax(EMPTY_DBL()), StartWorkspaceIndex(0),
+        EndWorkspaceIndex(EMPTY_INT()), SpectrumList(), wsType(workspaceType)
+    {
+    }
+    double XMin;
+    double XMax;
+    int StartWorkspaceIndex;
+    int EndWorkspaceIndex;
+    std::vector<int> SpectrumList;
+    std::string wsType;
+
+    // ---- x range ----
+    Parameters& setXRange()
+    {
+      XMin = 2.0;
+      XMax = 3.1;
+      return *this;
+    }
+    void testXRange(const MatrixWorkspace& ws) const
+    {
+      if (wsType == "histo-ragged")
+      {
+        TS_ASSERT_EQUALS(ws.blocksize(), 6);
+        TS_ASSERT_EQUALS(ws.readY(0)[0], 0.0);
+        TS_ASSERT_EQUALS(ws.readY(0)[1], 0.0);
+        TS_ASSERT_EQUALS(ws.readY(0)[2], 1.0);
+        TS_ASSERT_EQUALS(ws.readY(0)[3], 0.0);
+        TS_ASSERT_EQUALS(ws.readY(0)[4], 0.0);
+        TS_ASSERT_EQUALS(ws.readY(0)[5], 0.0);
+
+        TS_ASSERT_EQUALS(ws.readY(1)[0], 0.0);
+        TS_ASSERT_EQUALS(ws.readY(1)[1], 2.0);
+        TS_ASSERT_EQUALS(ws.readY(1)[2], 0.0);
+        TS_ASSERT_EQUALS(ws.readY(1)[3], 0.0);
+        TS_ASSERT_EQUALS(ws.readY(1)[4], 0.0);
+        TS_ASSERT_EQUALS(ws.readY(1)[5], 0.0);
+
+        TS_ASSERT_EQUALS(ws.readY(2)[0], 3.0);
+        TS_ASSERT_EQUALS(ws.readY(2)[1], 0.0);
+        TS_ASSERT_EQUALS(ws.readY(2)[2], 0.0);
+        TS_ASSERT_EQUALS(ws.readY(2)[3], 0.0);
+        TS_ASSERT_EQUALS(ws.readY(2)[4], 0.0);
+        TS_ASSERT_EQUALS(ws.readY(2)[5], 0.0);
+
+        TS_ASSERT_EQUALS(ws.readY(3)[0], 0.0);
+        TS_ASSERT_EQUALS(ws.readY(3)[1], 0.0);
+        TS_ASSERT_EQUALS(ws.readY(3)[2], 0.0);
+        TS_ASSERT_EQUALS(ws.readY(3)[3], 0.0);
+        TS_ASSERT_EQUALS(ws.readY(3)[4], 0.0);
+        TS_ASSERT_EQUALS(ws.readY(3)[5], 0.0);
+      }
+      else
+      {
+        TS_ASSERT_EQUALS(ws.blocksize(), 1);
+        TS_ASSERT_EQUALS(ws.readX(0)[0], 2.0);
+      }
+    }
+
+    // ---- index range ----
+    Parameters& setIndexRange()
+    {
+      StartWorkspaceIndex = 1;
+      EndWorkspaceIndex = 3;
+      return *this;
+    }
+    void testIndexRange(const MatrixWorkspace& ws) const
+    {
+      TS_ASSERT_EQUALS(ws.getNumberHistograms(), 3);
+      if (wsType == "histo")
+      {
+        TS_ASSERT_EQUALS(ws.readY(0)[0], 1.0);
+        TS_ASSERT_EQUALS(ws.readY(1)[0], 2.0);
+        TS_ASSERT_EQUALS(ws.readY(2)[0], 3.0);
+      }
+      else if (wsType == "event")
+      {
+        TS_ASSERT_EQUALS(ws.getDetector(0)->getID(), 2);
+        TS_ASSERT_EQUALS(ws.getDetector(1)->getID(), 3);
+        TS_ASSERT_EQUALS(ws.getDetector(2)->getID(), 4);
+      }
+    }
+
+    // ---- spectrum list ----
+    Parameters& setSpectrumList()
+    {
+      SpectrumList.resize(3);
+      SpectrumList[0] = 0;
+      SpectrumList[1] = 2;
+      SpectrumList[2] = 4;
+      return *this;
+    }
+    void testSpectrumList(const MatrixWorkspace& ws) const
+    {
+      TS_ASSERT_EQUALS(ws.getNumberHistograms(), 3);
+      if (wsType == "histo")
+      {
+        TS_ASSERT_EQUALS(ws.readY(0)[0], 0.0);
+        TS_ASSERT_EQUALS(ws.readY(1)[0], 2.0);
+        TS_ASSERT_EQUALS(ws.readY(2)[0], 4.0);
+      }
+      else if (wsType == "event")
+      {
+        TS_ASSERT_EQUALS(ws.getDetector(0)->getID(), 1);
+        TS_ASSERT_EQUALS(ws.getDetector(1)->getID(), 3);
+        TS_ASSERT_EQUALS(ws.getDetector(2)->getID(), 5);
+      }
+   }
+
+    // ---- invalid inputs ----
+    void setInvalidXRange()
+    {
+      XMin = 2.0;
+      XMax = 1.0;
+    }
+    void setInvalidIndexRange()
+    {
+      StartWorkspaceIndex = 3;
+      EndWorkspaceIndex = 1;
+    }
+    void setInvalidIndexRange1()
+    {
+      StartWorkspaceIndex = 1000;
+      EndWorkspaceIndex = 1002;
+    }
+  };
+
+  MatrixWorkspace_sptr runAlgorithm(const Parameters& params, bool expectSuccess = true) const
+  {
+    auto ws = createInputWorkspace(params.wsType);
+    ExtractSpectra alg;
+    TS_ASSERT_THROWS_NOTHING( alg.initialize() )
+    TS_ASSERT( alg.isInitialized() )
+    TS_ASSERT_THROWS_NOTHING( alg.setProperty("InputWorkspace", ws) );
+    TS_ASSERT_THROWS_NOTHING( alg.setPropertyValue("OutputWorkspace", outWSName) );
+
+    if (params.XMin != EMPTY_DBL())
+    {
+      TS_ASSERT_THROWS_NOTHING( alg.setProperty("XMin", params.XMin) );
+    }
+    if (params.XMax != EMPTY_DBL())
+    {
+      TS_ASSERT_THROWS_NOTHING( alg.setProperty("XMax", params.XMax) );
+    }
+    if (params.StartWorkspaceIndex != 0)
+    {
+      TS_ASSERT_THROWS_NOTHING( alg.setProperty("StartWorkspaceIndex", params.StartWorkspaceIndex) );
+    }
+    if (params.EndWorkspaceIndex != EMPTY_INT())
+    {
+      TS_ASSERT_THROWS_NOTHING( alg.setProperty("EndWorkspaceIndex", params.EndWorkspaceIndex) );
+    }
+    if (!params.SpectrumList.empty())
+    {
+      TS_ASSERT_THROWS_NOTHING( alg.setProperty("SpectrumList", params.SpectrumList) );
+    }
+
+    TS_ASSERT_THROWS_NOTHING( alg.execute(); );
+
+    if (expectSuccess)
+    {
+      TS_ASSERT( alg.isExecuted() );
+
+      // Retrieve the workspace from data service. TODO: Change to your desired type
+      MatrixWorkspace_sptr ws;
+      TS_ASSERT_THROWS_NOTHING( ws = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(outWSName) );
+      return ws;
+    }
+    else
+    {
+      TS_ASSERT( !alg.isExecuted() );
+    }
+
+    return MatrixWorkspace_sptr();
+  }
+
+};
+
+
+#endif /* MANTID_ALGORITHMS_EXTRACTSPECTRATEST_H_ */
\ No newline at end of file
diff --git a/Code/Mantid/Framework/Algorithms/test/MultiplyDivideTest.in.h b/Code/Mantid/Framework/Algorithms/test/MultiplyDivideTest.in.h
index 9a52eac541b7ffa70a716bc799e57848b23bd6ed..e19d443cdab649986afe4a5164b63acb36e8263b 100644
--- a/Code/Mantid/Framework/Algorithms/test/MultiplyDivideTest.in.h
+++ b/Code/Mantid/Framework/Algorithms/test/MultiplyDivideTest.in.h
@@ -1,3 +1,4 @@
+// clang-format off
 #ifndef @MULTIPLYDIVIDETEST_CLASS@_H_
 #define @MULTIPLYDIVIDETEST_CLASS@_H_
 
diff --git a/Code/Mantid/Framework/Algorithms/test/PlotAsymmetryByLogValueTest.h b/Code/Mantid/Framework/Algorithms/test/PlotAsymmetryByLogValueTest.h
index 2ec9773aeab6645ddf8094ba8ff58f85ffd7173a..7a5bb3e5ce5e1040e4b9e86f8bdad0fd84c8b17f 100644
--- a/Code/Mantid/Framework/Algorithms/test/PlotAsymmetryByLogValueTest.h
+++ b/Code/Mantid/Framework/Algorithms/test/PlotAsymmetryByLogValueTest.h
@@ -286,12 +286,28 @@ public:
     // rather than asymmetry (Y values)
     const Mantid::MantidVec& X = outWs->readX(0);
 
-    TS_ASSERT_DELTA(X[0], 179.078620, 0.00001);
+    TS_ASSERT_DELTA(X[0], 178.740476, 0.00001);
     TS_ASSERT_DELTA(X[1], 178.849998, 0.00001);
 
     AnalysisDataService::Instance().remove(ws);
   }
 
+  void test_invalidRunNumbers ()
+  {
+    const std::string ws = "Test_LogValueFunction";
+
+    PlotAsymmetryByLogValue alg;
+
+    TS_ASSERT_THROWS_NOTHING(alg.initialize());
+
+    alg.setPropertyValue("FirstRun", lastRun);
+    alg.setPropertyValue("LastRun", firstRun);
+    alg.setPropertyValue("OutputWorkspace", ws);
+
+    TS_ASSERT_THROWS (alg.execute(),std::runtime_error);
+    TS_ASSERT (!alg.isExecuted());
+  }
+
 private:
   std::string firstRun,lastRun;
   
diff --git a/Code/Mantid/Framework/Algorithms/test/PlusMinusTest.in.h b/Code/Mantid/Framework/Algorithms/test/PlusMinusTest.in.h
index 495cbabee1016ad0f4504ad798fa55e74bd5f9aa..be37447afe5a6ae5eb69db1eddbc130dfd836e77 100644
--- a/Code/Mantid/Framework/Algorithms/test/PlusMinusTest.in.h
+++ b/Code/Mantid/Framework/Algorithms/test/PlusMinusTest.in.h
@@ -1,3 +1,4 @@
+// clang-format off
 #ifndef @PLUSMINUSTEST_CLASS@_H_
 #define @PLUSMINUSTEST_CLASS@_H_
 #include <cxxtest/TestSuite.h>
diff --git a/Code/Mantid/Framework/Algorithms/test/RebinByPulseTimesTest.h b/Code/Mantid/Framework/Algorithms/test/RebinByPulseTimesTest.h
index 89e58d300ccd222608b72e8681455d6a802bb12c..6c34992e800c78ed75f3767e131967b5db131f63 100644
--- a/Code/Mantid/Framework/Algorithms/test/RebinByPulseTimesTest.h
+++ b/Code/Mantid/Framework/Algorithms/test/RebinByPulseTimesTest.h
@@ -154,7 +154,9 @@ public:
 //=====================================================================================
 // Performance Tests
 //=====================================================================================
+// clang-format off
 class RebinByPulseTimesTestPerformance : public CxxTest::TestSuite, public RebinByTimeBaseTestPerformance<RebinByPulseTimes>
+// clang-format on
 {
 
 public:
diff --git a/Code/Mantid/Framework/Algorithms/test/RebinByTimeAtSampleTest.h b/Code/Mantid/Framework/Algorithms/test/RebinByTimeAtSampleTest.h
index d008330f91d3b0b6ef15e39d9ca31b3dcd576943..540851a292011245d5c4413a0b8b6071d8fa15fa 100644
--- a/Code/Mantid/Framework/Algorithms/test/RebinByTimeAtSampleTest.h
+++ b/Code/Mantid/Framework/Algorithms/test/RebinByTimeAtSampleTest.h
@@ -268,8 +268,10 @@ public:
 //=====================================================================================
 // Performance Tests
 //=====================================================================================
+// clang-format off
 class RebinByTimeAtSampleTestPerformance: public CxxTest::TestSuite,
     public RebinByTimeBaseTestPerformance<RebinByTimeAtSample>
+// clang-format on
 {
 
 public:
diff --git a/Code/Mantid/Framework/Algorithms/test/RemoveMaskedSpectraTest.h b/Code/Mantid/Framework/Algorithms/test/RemoveMaskedSpectraTest.h
new file mode 100644
index 0000000000000000000000000000000000000000..75ca25c3497b09f6de99198a8a6e121533826b6c
--- /dev/null
+++ b/Code/Mantid/Framework/Algorithms/test/RemoveMaskedSpectraTest.h
@@ -0,0 +1,139 @@
+#ifndef MANTID_ALGORITHMS_REMOVEMASKEDSPECTRATEST_H_
+#define MANTID_ALGORITHMS_REMOVEMASKEDSPECTRATEST_H_
+
+#include <cxxtest/TestSuite.h>
+
+#include "MantidAlgorithms/RemoveMaskedSpectra.h"
+#include "MantidAPI/AlgorithmManager.h"
+#include "MantidTestHelpers/ComponentCreationHelper.h"
+
+using Mantid::Algorithms::RemoveMaskedSpectra;
+using namespace Mantid::API;
+using namespace Mantid;
+
+class RemoveMaskedSpectraTest : public CxxTest::TestSuite {
+public:
+  // This pair of boilerplate methods prevent the suite being created statically
+  // This means the constructor isn't called when running other tests
+  static RemoveMaskedSpectraTest *createSuite() {
+    return new RemoveMaskedSpectraTest();
+  }
+  static void destroySuite(RemoveMaskedSpectraTest *suite) {
+    AnalysisDataService::Instance().clear();
+    delete suite;
+  }
+
+  RemoveMaskedSpectraTest() : nSpec(5), nBins(6) {}
+
+  void test_Init() {
+    RemoveMaskedSpectra alg;
+    TS_ASSERT_THROWS_NOTHING(alg.initialize())
+    TS_ASSERT(alg.isInitialized())
+  }
+
+  void test_workspace2D_mask() {
+    auto inputWS = createInputWorkspace();
+    auto maskedWS = createInputWorkspace();
+    TS_ASSERT_DIFFERS(inputWS, maskedWS);
+    maskWorkspace(maskedWS);
+    auto output = runAlgorithm(inputWS, maskedWS);
+    TS_ASSERT_EQUALS(output->getNumberHistograms(), 2);
+    TS_ASSERT_EQUALS(output->readY(0).front(), 1.0);
+    TS_ASSERT_EQUALS(output->readY(1).front(), 3.0);
+  }
+
+  void test_mask_workspace_mask() {
+    auto inputWS = createInputWorkspace();
+    auto secondWS = createInputWorkspace();
+    maskWorkspace(secondWS);
+
+    auto alg = AlgorithmManager::Instance().create("ExtractMask");
+    alg->initialize();
+    alg->setProperty("InputWorkspace", secondWS);
+    alg->setPropertyValue("OutputWorkspace", "RemoveMaskedSpectraTest_MaskWS");
+    alg->execute();
+    auto maskedWS = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(
+        "RemoveMaskedSpectraTest_MaskWS");
+
+    auto output = runAlgorithm(inputWS, maskedWS);
+    TS_ASSERT_EQUALS(output->getNumberHistograms(), 2);
+    TS_ASSERT_EQUALS(output->readY(0).front(), 1.0);
+    TS_ASSERT_EQUALS(output->readY(1).front(), 3.0);
+  }
+
+  void test_self_mask() {
+    auto inputWS = createInputWorkspace();
+    maskWorkspace(inputWS);
+    auto output = runAlgorithm(inputWS);
+    TS_ASSERT_EQUALS(output->getNumberHistograms(), 2);
+    TS_ASSERT_EQUALS(output->readY(0).front(), 1.0);
+    TS_ASSERT_EQUALS(output->readY(1).front(), 3.0);
+  }
+
+private:
+  // ---- helper methods ----
+
+  const size_t nSpec;
+  const size_t nBins;
+
+  MatrixWorkspace_sptr createInputWorkspace() const {
+    // Set up a small workspace for testing
+    MatrixWorkspace_sptr space = WorkspaceFactory::Instance().create(
+        "Workspace2D", nSpec, nBins + 1, nBins);
+    space->setInstrument(
+        ComponentCreationHelper::createTestInstrumentCylindrical(1));
+    for (size_t j = 0; j < nSpec; ++j) {
+      for (size_t k = 0; k <= nBins; ++k) {
+        space->dataX(j)[k] = double(k);
+      }
+      space->dataY(j).assign(nBins, double(j));
+      space->dataE(j).assign(nBins, sqrt(double(j)));
+      space->getSpectrum(j)->setDetectorID(detid_t(j + 1));
+    }
+    return space;
+  }
+
+  void maskWorkspace(MatrixWorkspace_sptr ws) {
+    std::vector<int> spectra(3);
+    spectra[0] = 1;
+    spectra[1] = 3;
+    spectra[2] = 5;
+    auto alg = AlgorithmManager::Instance().create("MaskDetectors");
+    alg->initialize();
+    alg->setProperty("Workspace", ws);
+    alg->setProperty("SpectraList", spectra);
+    alg->execute();
+  }
+
+  MatrixWorkspace_sptr
+  runAlgorithm(MatrixWorkspace_sptr inputWS,
+               MatrixWorkspace_sptr maskedWS = MatrixWorkspace_sptr()) {
+    // Name of the output workspace.
+    std::string outWSName("RemoveMaskedSpectraTest_OutputWS");
+
+    RemoveMaskedSpectra alg;
+    TS_ASSERT_THROWS_NOTHING(alg.initialize())
+    TS_ASSERT(alg.isInitialized())
+    TS_ASSERT_THROWS_NOTHING(alg.setProperty("InputWorkspace", inputWS));
+    if (maskedWS) {
+      TS_ASSERT_THROWS_NOTHING(alg.setProperty("MaskedWorkspace", maskedWS));
+    }
+    TS_ASSERT_THROWS_NOTHING(
+        alg.setPropertyValue("OutputWorkspace", outWSName));
+    TS_ASSERT_THROWS_NOTHING(alg.execute(););
+    TS_ASSERT(alg.isExecuted());
+    if (!alg.isExecuted())
+      return MatrixWorkspace_sptr();
+
+    // Retrieve the workspace from data service. TODO: Change to your desired
+    // type
+    MatrixWorkspace_sptr ws;
+    TS_ASSERT_THROWS_NOTHING(
+        ws = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(
+            outWSName));
+    TS_ASSERT(ws);
+    return ws;
+  }
+};
+
+#endif /* MANTID_ALGORITHMS_REMOVEMASKEDSPECTRATEST_H_ */
diff --git a/Code/Mantid/Framework/Algorithms/test/SpecularReflectionCalculateThetaTest.h b/Code/Mantid/Framework/Algorithms/test/SpecularReflectionCalculateThetaTest.h
index 3e101cc4ce543c161855b15e4bced074faf20f2f..f00084e9e57958cec6b4bc6c4a3ace8779a90300 100644
--- a/Code/Mantid/Framework/Algorithms/test/SpecularReflectionCalculateThetaTest.h
+++ b/Code/Mantid/Framework/Algorithms/test/SpecularReflectionCalculateThetaTest.h
@@ -11,8 +11,10 @@
 using namespace Mantid::Algorithms;
 using namespace Mantid::API;
 
+// clang-format off
 class SpecularReflectionCalculateThetaTest: public CxxTest::TestSuite,
     public SpecularReflectionAlgorithmTest
+// clang-format on
 {
 
 private:
diff --git a/Code/Mantid/Framework/Algorithms/test/SpecularReflectionPositionCorrectTest.h b/Code/Mantid/Framework/Algorithms/test/SpecularReflectionPositionCorrectTest.h
index 43cd38b3ddd1f0e10696fb7bbb661a9e0ca5a593..f4e0e6f1924359ae2d3379cbc0ac56d23aea86bf 100644
--- a/Code/Mantid/Framework/Algorithms/test/SpecularReflectionPositionCorrectTest.h
+++ b/Code/Mantid/Framework/Algorithms/test/SpecularReflectionPositionCorrectTest.h
@@ -16,8 +16,10 @@ using namespace Mantid::API;
 using namespace Mantid::Kernel;
 using namespace Mantid::Geometry;
 
+// clang-format off
 class SpecularReflectionPositionCorrectTest: public CxxTest::TestSuite,
     public SpecularReflectionAlgorithmTest
+// clang-format on
 {
 
 public:
diff --git a/Code/Mantid/Framework/Crystal/src/AddPeakHKL.cpp b/Code/Mantid/Framework/Crystal/src/AddPeakHKL.cpp
index 2e770043c2b4c4322cbbe4bf855d2b08f1ab60d6..76ef41cf46b36cfe99a7a0054dafccf7cb216fed 100644
--- a/Code/Mantid/Framework/Crystal/src/AddPeakHKL.cpp
+++ b/Code/Mantid/Framework/Crystal/src/AddPeakHKL.cpp
@@ -3,7 +3,6 @@
 #include "MantidAPI/IPeak.h"
 #include "MantidKernel/ArrayProperty.h"
 #include "MantidKernel/ArrayLengthValidator.h"
-#include "MantidKernel/V3D.h"
 
 namespace Mantid
 {
diff --git a/Code/Mantid/Framework/Crystal/src/AnvredCorrection.cpp b/Code/Mantid/Framework/Crystal/src/AnvredCorrection.cpp
index 5506b5b4f902b250625762114e68a2e9fed38e35..4e0457ccf67ef43acfb40a1db686f0a4d4da8fd3 100644
--- a/Code/Mantid/Framework/Crystal/src/AnvredCorrection.cpp
+++ b/Code/Mantid/Framework/Crystal/src/AnvredCorrection.cpp
@@ -8,9 +8,6 @@
 #include "MantidKernel/UnitFactory.h"
 #include "MantidKernel/Fast_Exponential.h"
 #include "MantidKernel/VectorHelper.h"
-#include "MantidKernel/Unit.h"
-#include "MantidKernel/PhysicalConstants.h"
-#include "MantidKernel/V3D.h"
 #include "MantidAPI/MemoryManager.h"
 #include "boost/assign.hpp"
 
diff --git a/Code/Mantid/Framework/Crystal/src/CalculatePeaksHKL.cpp b/Code/Mantid/Framework/Crystal/src/CalculatePeaksHKL.cpp
index 10dc1653c945a9b9165be5748d7aec67bd2cc759..aa6723c5af08996a8d3119595c803493a6afaaae 100644
--- a/Code/Mantid/Framework/Crystal/src/CalculatePeaksHKL.cpp
+++ b/Code/Mantid/Framework/Crystal/src/CalculatePeaksHKL.cpp
@@ -1,9 +1,7 @@
 #include "MantidCrystal/CalculatePeaksHKL.h"
 #include "MantidGeometry/Crystal/IndexingUtils.h"
 #include "MantidDataObjects/PeaksWorkspace.h"
-#include "MantidDataObjects/Peak.h"
 #include "MantidGeometry/Crystal/OrientedLattice.h"
-#include <set>
 
 using namespace Mantid::Kernel;
 using namespace Mantid::Geometry;
diff --git a/Code/Mantid/Framework/Crystal/src/CalculateUMatrix.cpp b/Code/Mantid/Framework/Crystal/src/CalculateUMatrix.cpp
index 2d18782ec82f2dddaa0fd85ffd651d4ee4202ff1..f18dc26bb55bab055af823cf74944293a4c6b9d0 100644
--- a/Code/Mantid/Framework/Crystal/src/CalculateUMatrix.cpp
+++ b/Code/Mantid/Framework/Crystal/src/CalculateUMatrix.cpp
@@ -1,6 +1,5 @@
 #include "MantidCrystal/CalculateUMatrix.h"
 #include "MantidDataObjects/PeaksWorkspace.h"
-#include "MantidDataObjects/Peak.h"
 #include "MantidGeometry/Crystal/OrientedLattice.h"
 #include "MantidKernel/BoundedValidator.h"
 
diff --git a/Code/Mantid/Framework/Crystal/src/CentroidPeaks.cpp b/Code/Mantid/Framework/Crystal/src/CentroidPeaks.cpp
index ceac46accfd594492b182743c79bc087e654589f..270669d1789a5d8552d783867815b64b0c5e4166 100644
--- a/Code/Mantid/Framework/Crystal/src/CentroidPeaks.cpp
+++ b/Code/Mantid/Framework/Crystal/src/CentroidPeaks.cpp
@@ -1,10 +1,8 @@
 #include "MantidDataObjects/PeaksWorkspace.h"
-#include "MantidKernel/System.h"
 #include "MantidCrystal/CentroidPeaks.h"
 #include "MantidGeometry/Instrument/RectangularDetector.h"
 #include "MantidKernel/VectorHelper.h"
 #include "MantidGeometry/Crystal/OrientedLattice.h"
-#include "MantidAPI/MemoryManager.h"
 
 using Mantid::DataObjects::PeaksWorkspace;
 
diff --git a/Code/Mantid/Framework/Crystal/src/Cluster.cpp b/Code/Mantid/Framework/Crystal/src/Cluster.cpp
index e925838a1ecc9a536069fe35d775967e45607f35..9d79b4205466a2029addfff3bdb8138a9d0c7b61 100644
--- a/Code/Mantid/Framework/Crystal/src/Cluster.cpp
+++ b/Code/Mantid/Framework/Crystal/src/Cluster.cpp
@@ -1,7 +1,5 @@
 #include "MantidCrystal/Cluster.h"
-#include "MantidCrystal/DisjointElement.h"
 #include "MantidAPI/IMDHistoWorkspace.h"
-#include <stdexcept>
 
 namespace {
 typedef std::vector<Mantid::Crystal::DisjointElement> VecElements;
diff --git a/Code/Mantid/Framework/Crystal/src/ClusterRegister.cpp b/Code/Mantid/Framework/Crystal/src/ClusterRegister.cpp
index 45f7851083fc461393cebdb887fe507cb5903625..2d61cf6bc07aaf61c70a7665a8644cad51aa6f02 100644
--- a/Code/Mantid/Framework/Crystal/src/ClusterRegister.cpp
+++ b/Code/Mantid/Framework/Crystal/src/ClusterRegister.cpp
@@ -4,9 +4,10 @@
 #include "MantidCrystal/DisjointElement.h"
 #include <boost/make_shared.hpp>
 #include <boost/functional/hash.hpp>
-#include <algorithm>
-#include <set>
 #include <list>
+#include <set>
+#include <stdexcept>
+
 
 namespace {
 template <typename T> std::pair<T, T> ordered_pair(const T &a, const T &b) {
diff --git a/Code/Mantid/Framework/Crystal/src/CombinePeaksWorkspaces.cpp b/Code/Mantid/Framework/Crystal/src/CombinePeaksWorkspaces.cpp
index e4e518348f73a2af6d0618fe8d555587157fbcff..ae225e36b6f2f86af2de6e10b22a4303f0adc7c9 100644
--- a/Code/Mantid/Framework/Crystal/src/CombinePeaksWorkspaces.cpp
+++ b/Code/Mantid/Framework/Crystal/src/CombinePeaksWorkspaces.cpp
@@ -2,7 +2,6 @@
 #include "MantidKernel/BoundedValidator.h"
 #include "MantidKernel/EnabledWhenProperty.h"
 #include "MantidDataObjects/PeaksWorkspace.h"
-#include "MantidDataObjects/Peak.h"
 
 namespace Mantid {
 namespace Crystal {
diff --git a/Code/Mantid/Framework/Crystal/src/CompositeCluster.cpp b/Code/Mantid/Framework/Crystal/src/CompositeCluster.cpp
index 348bbae190349ed35651a05c7fa9188bb5d47545..5b239ec944ec34abc9cd95676726138951818d59 100644
--- a/Code/Mantid/Framework/Crystal/src/CompositeCluster.cpp
+++ b/Code/Mantid/Framework/Crystal/src/CompositeCluster.cpp
@@ -1,6 +1,5 @@
 #include "MantidCrystal/CompositeCluster.h"
 #include <stdexcept>
-#include <algorithm>
 
 namespace {
 /**
diff --git a/Code/Mantid/Framework/Crystal/src/ConnectedComponentLabeling.cpp b/Code/Mantid/Framework/Crystal/src/ConnectedComponentLabeling.cpp
index 4e70dcd623f172279a11e4d0f5c121a3a1feca48..13786689b8b58d1b8ff6ba78ff1355b862e89051 100644
--- a/Code/Mantid/Framework/Crystal/src/ConnectedComponentLabeling.cpp
+++ b/Code/Mantid/Framework/Crystal/src/ConnectedComponentLabeling.cpp
@@ -1,27 +1,12 @@
 #include "MantidCrystal/ConnectedComponentLabeling.h"
 
-#include "MantidKernel/Logger.h"
 #include "MantidKernel/Memory.h"
-#include "MantidKernel/MultiThreaded.h"
-#include "MantidKernel/V3D.h"
 #include "MantidAPI/FrameworkManager.h"
-#include "MantidAPI/IMDHistoWorkspace.h"
 #include "MantidAPI/IMDIterator.h"
-#include "MantidAPI/Progress.h"
 #include "MantidCrystal/BackgroundStrategy.h"
-#include "MantidCrystal/DisjointElement.h"
 #include "MantidCrystal/ICluster.h"
 #include "MantidCrystal/Cluster.h"
 #include "MantidCrystal/ClusterRegister.h"
-#include "MantidCrystal/CompositeCluster.h"
-#include <boost/shared_ptr.hpp>
-#include <boost/tuple/tuple.hpp>
-#include <boost/scoped_ptr.hpp>
-#include <stdexcept>
-#include <set>
-#include <algorithm>
-#include <iterator>
-#include <functional>
 
 using namespace Mantid::API;
 using namespace Mantid::Kernel;
diff --git a/Code/Mantid/Framework/Crystal/src/DisjointElement.cpp b/Code/Mantid/Framework/Crystal/src/DisjointElement.cpp
index 7032757e96b1b8e48db26d5d11d5e6d694d785e7..7fe0614e368fb8064036a113c37639f6b0c3ca82 100644
--- a/Code/Mantid/Framework/Crystal/src/DisjointElement.cpp
+++ b/Code/Mantid/Framework/Crystal/src/DisjointElement.cpp
@@ -1,6 +1,5 @@
 #include "MantidCrystal/DisjointElement.h"
-#include <stdexcept>
-#include <iostream>
+
 namespace Mantid {
 namespace Crystal {
 
diff --git a/Code/Mantid/Framework/Crystal/src/FindClusterFaces.cpp b/Code/Mantid/Framework/Crystal/src/FindClusterFaces.cpp
index 2332de05184709d69f6492a0b20ea0a374c851ab..e1828c1f71b0e593b88eb956a170a189bc238940 100644
--- a/Code/Mantid/Framework/Crystal/src/FindClusterFaces.cpp
+++ b/Code/Mantid/Framework/Crystal/src/FindClusterFaces.cpp
@@ -2,28 +2,17 @@
 
 #include "MantidKernel/BoundedValidator.h"
 #include "MantidKernel/EnabledWhenProperty.h"
-#include "MantidKernel/MultiThreaded.h"
 #include "MantidKernel/Utils.h"
 
 #include "MantidAPI/FrameworkManager.h"
 #include "MantidAPI/IMDIterator.h"
 #include "MantidAPI/IPeaksWorkspace.h"
 #include "MantidAPI/IPeak.h"
-#include "MantidAPI/ITableWorkspace.h"
 #include "MantidAPI/IMDHistoWorkspace.h"
-#include "MantidAPI/Progress.h"
 #include "MantidAPI/TableRow.h"
-#include "MantidAPI/WorkspaceFactory.h"
 
 #include "MantidCrystal/PeakClusterProjection.h"
 
-#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
-#include <boost/make_shared.hpp>
-#include <map>
-#include <deque>
-#include <algorithm>
-
 using namespace Mantid::Kernel;
 using namespace Mantid::API;
 
diff --git a/Code/Mantid/Framework/Crystal/src/FindSXPeaks.cpp b/Code/Mantid/Framework/Crystal/src/FindSXPeaks.cpp
index 41f23f803550a4c0ae91cb829e7009189b998ee7..b1674def6eedfe3fcdc099ede2bc83cdb3b82c0c 100644
--- a/Code/Mantid/Framework/Crystal/src/FindSXPeaks.cpp
+++ b/Code/Mantid/Framework/Crystal/src/FindSXPeaks.cpp
@@ -2,13 +2,9 @@
 // Includes
 //----------------------------------------------------------------------
 #include "MantidCrystal/FindSXPeaks.h"
-#include "MantidAPI/IPeak.h"
-#include "MantidAPI/Progress.h"
 #include "MantidAPI/WorkspaceValidators.h"
-#include "MantidDataObjects/PeaksWorkspace.h"
 #include "MantidKernel/VectorHelper.h"
 #include "MantidKernel/BoundedValidator.h"
-#include "MantidDataObjects/Peak.h"
 
 using namespace Mantid::DataObjects;
 
diff --git a/Code/Mantid/Framework/Crystal/src/FindUBUsingFFT.cpp b/Code/Mantid/Framework/Crystal/src/FindUBUsingFFT.cpp
index 2cc82c47c14adeff5830ef35169b1ab5941654f3..4be3531f733caeba602042b1e0507fbbc6b78456 100644
--- a/Code/Mantid/Framework/Crystal/src/FindUBUsingFFT.cpp
+++ b/Code/Mantid/Framework/Crystal/src/FindUBUsingFFT.cpp
@@ -1,10 +1,8 @@
 #include "MantidCrystal/FindUBUsingFFT.h"
 #include "MantidDataObjects/PeaksWorkspace.h"
-#include "MantidDataObjects/Peak.h"
 #include "MantidGeometry/Crystal/IndexingUtils.h"
 #include "MantidGeometry/Crystal/OrientedLattice.h"
 #include "MantidKernel/BoundedValidator.h"
-#include <cstdio>
 
 namespace Mantid {
 namespace Crystal {
diff --git a/Code/Mantid/Framework/Crystal/src/FindUBUsingIndexedPeaks.cpp b/Code/Mantid/Framework/Crystal/src/FindUBUsingIndexedPeaks.cpp
index 626a84924dd4a05e00fc670d1bd992fd4c4ac0d2..67a0fe6666a3ceea9155e90284e9a8ce88293037 100644
--- a/Code/Mantid/Framework/Crystal/src/FindUBUsingIndexedPeaks.cpp
+++ b/Code/Mantid/Framework/Crystal/src/FindUBUsingIndexedPeaks.cpp
@@ -3,9 +3,7 @@
 #include "MantidDataObjects/PeaksWorkspace.h"
 #include "MantidGeometry/Crystal/IndexingUtils.h"
 #include "MantidGeometry/Crystal/OrientedLattice.h"
-#include "MantidKernel/System.h"
 #include "MantidKernel/BoundedValidator.h"
-#include <cstdio>
 
 namespace Mantid {
 namespace Crystal {
diff --git a/Code/Mantid/Framework/Crystal/src/FindUBUsingLatticeParameters.cpp b/Code/Mantid/Framework/Crystal/src/FindUBUsingLatticeParameters.cpp
index b3adcbbff282b8b4a487d4c718da345a99bbe7e3..d17030d75d7f066510ed06e64d9a1e7e108bab45 100644
--- a/Code/Mantid/Framework/Crystal/src/FindUBUsingLatticeParameters.cpp
+++ b/Code/Mantid/Framework/Crystal/src/FindUBUsingLatticeParameters.cpp
@@ -1,10 +1,8 @@
 #include "MantidCrystal/FindUBUsingLatticeParameters.h"
 #include "MantidDataObjects/PeaksWorkspace.h"
-#include "MantidDataObjects/Peak.h"
 #include "MantidGeometry/Crystal/IndexingUtils.h"
 #include "MantidGeometry/Crystal/OrientedLattice.h"
 #include "MantidKernel/BoundedValidator.h"
-#include <cstdio>
 
 namespace Mantid {
 namespace Crystal {
diff --git a/Code/Mantid/Framework/Crystal/src/FindUBUsingMinMaxD.cpp b/Code/Mantid/Framework/Crystal/src/FindUBUsingMinMaxD.cpp
index 40ea69a2a67e7a0e078a04128415ca97ebf10cb3..9c3fdecb41fd5f3b446930d8f9b7b8a3cc1229c3 100644
--- a/Code/Mantid/Framework/Crystal/src/FindUBUsingMinMaxD.cpp
+++ b/Code/Mantid/Framework/Crystal/src/FindUBUsingMinMaxD.cpp
@@ -1,10 +1,8 @@
 #include "MantidCrystal/FindUBUsingMinMaxD.h"
 #include "MantidKernel/BoundedValidator.h"
 #include "MantidDataObjects/PeaksWorkspace.h"
-#include "MantidDataObjects/Peak.h"
 #include "MantidGeometry/Crystal/IndexingUtils.h"
 #include "MantidGeometry/Crystal/OrientedLattice.h"
-#include <cstdio>
 
 namespace Mantid {
 namespace Crystal {
diff --git a/Code/Mantid/Framework/Crystal/src/GoniometerAnglesFromPhiRotation.cpp b/Code/Mantid/Framework/Crystal/src/GoniometerAnglesFromPhiRotation.cpp
index b63591c70b334149510915eadd303e4f9cd38c5c..8f8e0f8e59466530bf596784d8bf106ebd6d8f74 100644
--- a/Code/Mantid/Framework/Crystal/src/GoniometerAnglesFromPhiRotation.cpp
+++ b/Code/Mantid/Framework/Crystal/src/GoniometerAnglesFromPhiRotation.cpp
@@ -1,23 +1,10 @@
 #include "MantidAPI/Algorithm.h"
 #include "MantidAPI/FrameworkManager.h"
-#include "MantidAPI/IAlgorithm.h"
 #include "MantidAPI/IFunction.h"
-#include "MantidAPI/ITableWorkspace.h"
 #include "MantidCrystal/GoniometerAnglesFromPhiRotation.h"
-#include "MantidCrystal/FindUBUsingFFT.h"
-#include "MantidDataObjects/Peak.h"
-#include "MantidDataObjects/PeaksWorkspace.h"
-#include "MantidDataObjects/TableWorkspace.h"
 #include "MantidDataObjects/Workspace2D.h"
 #include "MantidGeometry/Crystal/IndexingUtils.h"
 #include "MantidGeometry/Crystal/OrientedLattice.h"
-#include "MantidGeometry/Instrument/Goniometer.h"
-#include "MantidKernel/cow_ptr.h"
-#include "MantidKernel/Logger.h"
-#include "MantidKernel/Matrix.h"
-#include "MantidKernel/Property.h"
-#include <cstdio>
-#include <math.h>
 
 using Mantid::Kernel::Direction;
 using Mantid::Kernel::Logger;
diff --git a/Code/Mantid/Framework/Crystal/src/IndexPeaks.cpp b/Code/Mantid/Framework/Crystal/src/IndexPeaks.cpp
index 1a964c9157b19173fbf5b6b958fa6cfa6c3c765b..4a59ecd5a57bd9c7066e2473007f3d94513343a9 100644
--- a/Code/Mantid/Framework/Crystal/src/IndexPeaks.cpp
+++ b/Code/Mantid/Framework/Crystal/src/IndexPeaks.cpp
@@ -1,10 +1,8 @@
 #include "MantidCrystal/IndexPeaks.h"
 #include "MantidDataObjects/PeaksWorkspace.h"
-#include "MantidDataObjects/Peak.h"
 #include "MantidGeometry/Crystal/IndexingUtils.h"
 #include "MantidGeometry/Crystal/OrientedLattice.h"
 #include "MantidKernel/BoundedValidator.h"
-#include <cstdio>
 
 namespace Mantid {
 namespace Crystal {
diff --git a/Code/Mantid/Framework/Crystal/src/IndexSXPeaks.cpp b/Code/Mantid/Framework/Crystal/src/IndexSXPeaks.cpp
index b9851686868cfe5718e7e0357f0acbaa4bc6ebb0..d89eef963dce5e8fcac6fbcb3b6c5f5143f78724 100644
--- a/Code/Mantid/Framework/Crystal/src/IndexSXPeaks.cpp
+++ b/Code/Mantid/Framework/Crystal/src/IndexSXPeaks.cpp
@@ -4,14 +4,10 @@
 #include "MantidCrystal/IndexSXPeaks.h"
 #include "MantidAPI/WorkspaceValidators.h"
 #include "MantidKernel/VectorHelper.h"
-#include "MantidAPI/Progress.h"
 #include "MantidKernel/ArrayProperty.h"
-#include "MantidAPI/Column.h"
 #include "MantidAPI/IPeak.h"
 #include "MantidDataObjects/PeaksWorkspace.h"
 #include "MantidKernel/BoundedValidator.h"
-#include <sstream>
-#include <algorithm>
 
 namespace Mantid {
 namespace Crystal {
diff --git a/Code/Mantid/Framework/Crystal/src/IntegratePeakTimeSlices.cpp b/Code/Mantid/Framework/Crystal/src/IntegratePeakTimeSlices.cpp
index ce49b4c2b675f0de66877cb762f2c170a7944192..dc4a3d02abeb5b0d7981625b20b161ecb498b9a1 100644
--- a/Code/Mantid/Framework/Crystal/src/IntegratePeakTimeSlices.cpp
+++ b/Code/Mantid/Framework/Crystal/src/IntegratePeakTimeSlices.cpp
@@ -8,44 +8,16 @@
  *
  */
 #include "MantidCrystal/IntegratePeakTimeSlices.h"
-#include "MantidDataObjects/Peak.h"
-#include "MantidDataObjects/PeaksWorkspace.h"
-#include "MantidGeometry/Objects/BoundingBox.h"
-#include "MantidGeometry/Instrument/CompAssembly.h"
-#include "MantidGeometry/Instrument/RectangularDetector.h"
-#include "MantidKernel/IPropertyManager.h"
-#include "MantidGeometry/IComponent.h"
-#include "MantidAPI/WorkspaceFactory.h"
 #include "MantidAPI/ConstraintFactory.h"
-#include "MantidAPI/MatrixWorkspace.h"
 #include "MantidAPI/IFunction.h"
 #include "MantidAPI/FunctionDomain1D.h"
-#include "MantidAPI/FunctionValues.h"
 #include "MantidAPI/IFuncMinimizer.h"
 #include "MantidAPI/FuncMinimizerFactory.h"
 #include "MantidAPI/FunctionFactory.h"
-#include "MantidDataObjects/TableWorkspace.h"
 #include "MantidDataObjects/Workspace2D.h"
-#include "MantidAPI/ITableWorkspace.h"
-#include "MantidAPI/SpectraDetectorTypes.h"
-#include "MantidAPI/Progress.h"
-#include "MantidGeometry/IDTypes.h"
-#include "MantidKernel/cow_ptr.h"
-#include "MantidKernel/PropertyManagerOwner.h"
-#include "MantidKernel/Unit.h"
-#include "MantidKernel/V3D.h"
 //#include "MantidGeometry/Surfaces/Surface.h"
-#include <boost/lexical_cast.hpp>
-#include <vector>
-#include "MantidAPI/Algorithm.h"
-#include <algorithm>
-#include <math.h>
-#include <cstdio>
-#include <stdio.h>
-#include <time.h>
 
 //#include <boost/random/poisson_distribution.hpp>
-#include "MantidAPI/ISpectrum.h"
 using namespace Mantid::Kernel;
 using namespace Mantid::API;
 using namespace Mantid::DataObjects;
diff --git a/Code/Mantid/Framework/Crystal/src/IntegratePeaksHybrid.cpp b/Code/Mantid/Framework/Crystal/src/IntegratePeaksHybrid.cpp
index c7d2f6fd8ede9ea1f60c8ae3d529eca139d2900c..c307d108813864005837699cb00b82bf50784d4b 100644
--- a/Code/Mantid/Framework/Crystal/src/IntegratePeaksHybrid.cpp
+++ b/Code/Mantid/Framework/Crystal/src/IntegratePeaksHybrid.cpp
@@ -41,23 +41,16 @@
 #include "MantidCrystal/ICluster.h"
 #include "MantidCrystal/PeakClusterProjection.h"
 
-#include "MantidAPI/IMDHistoWorkspace.h"
 #include "MantidAPI/IMDEventWorkspace.h"
 #include "MantidAPI/IMDIterator.h"
-#include "MantidAPI/WorkspaceProperty.h"
-#include "MantidAPI/WorkspaceGroup.h"
 #include "MantidKernel/CompositeValidator.h"
 #include "MantidKernel/MandatoryValidator.h"
-#include "MantidKernel/MultiThreaded.h"
 #include "MantidKernel/BoundedValidator.h"
 #include "MantidKernel/ListValidator.h"
 #include "MantidDataObjects/PeaksWorkspace.h"
 
-#include <boost/make_shared.hpp>
 #include <boost/format.hpp>
-#include <boost/algorithm/string.hpp>
 #include <boost/math/special_functions/fpclassify.hpp>
-#include <cmath>
 
 using namespace Mantid::API;
 using namespace Mantid::Kernel;
diff --git a/Code/Mantid/Framework/Crystal/src/IntegratePeaksUsingClusters.cpp b/Code/Mantid/Framework/Crystal/src/IntegratePeaksUsingClusters.cpp
index 5b6aeeb76773b008fd7acaa5f907d5de6b150c52..726d1b39e20a1c7eae3c3aea48dba71b75beb05a 100644
--- a/Code/Mantid/Framework/Crystal/src/IntegratePeaksUsingClusters.cpp
+++ b/Code/Mantid/Framework/Crystal/src/IntegratePeaksUsingClusters.cpp
@@ -3,12 +3,8 @@
 #include "MantidCrystal/ConnectedComponentLabeling.h"
 #include "MantidCrystal/HardThresholdBackground.h"
 #include "MantidCrystal/PeakClusterProjection.h"
-#include "MantidAPI/IMDHistoWorkspace.h"
-#include "MantidAPI/WorkspaceProperty.h"
 #include "MantidAPI/IMDIterator.h"
 #include "MantidAPI/AlgorithmManager.h"
-#include "MantidAPI/Progress.h"
-#include "MantidKernel/MultiThreaded.h"
 #include "MantidKernel/CompositeValidator.h"
 #include "MantidKernel/MandatoryValidator.h"
 #include "MantidKernel/BoundedValidator.h"
@@ -16,12 +12,7 @@
 #include "MantidKernel/Utils.h"
 #include "MantidDataObjects/PeaksWorkspace.h"
 
-#include <boost/make_shared.hpp>
 #include <boost/math/special_functions/fpclassify.hpp>
-#include <map>
-#include <algorithm>
-#include <boost/tuple/tuple.hpp>
-#include <cmath>
 
 using namespace Mantid::API;
 using namespace Mantid::Kernel;
diff --git a/Code/Mantid/Framework/Crystal/src/LatticeErrors.cpp b/Code/Mantid/Framework/Crystal/src/LatticeErrors.cpp
index bf9c14a30617748de8c9f894a67ae65cd42bad58..04084ed43096c06ea13f00d150b4464278f8adb3 100644
--- a/Code/Mantid/Framework/Crystal/src/LatticeErrors.cpp
+++ b/Code/Mantid/Framework/Crystal/src/LatticeErrors.cpp
@@ -10,19 +10,7 @@
 #include "MantidAPI/ParamFunction.h"
 #include "MantidCrystal/LatticeErrors.h"
 #include "MantidCrystal/SCDPanelErrors.h"
-#include "MantidDataObjects/Peak.h"
-#include "MantidDataObjects/PeaksWorkspace.h"
-#include "MantidGeometry/IComponent.h"
-#include "MantidGeometry/Instrument/CompAssembly.h"
-#include "MantidGeometry/Instrument/Goniometer.h"
-#include "MantidGeometry/Instrument/ParameterMap.h"
-#include "MantidGeometry/IObjComponent.h"
 #include "MantidCrystal/OptimizeLatticeForCellType.h"
-#include "MantidKernel/Matrix.h"
-#include "MantidKernel/Quat.h"
-#include "MantidKernel/V3D.h"
-#include <cctype>
-#include <string>
 
 using namespace Mantid::DataObjects;
 using namespace Mantid::API;
diff --git a/Code/Mantid/Framework/Crystal/src/LoadHKL.cpp b/Code/Mantid/Framework/Crystal/src/LoadHKL.cpp
index 2f96d9e9d8db51beaa860200e0f8dbd05f8a3ade..0a2cdd3331a2f06b44acfe61f5341eee67f450c7 100644
--- a/Code/Mantid/Framework/Crystal/src/LoadHKL.cpp
+++ b/Code/Mantid/Framework/Crystal/src/LoadHKL.cpp
@@ -2,14 +2,8 @@
 #include "MantidAPI/WorkspaceValidators.h"
 #include "MantidCrystal/LoadHKL.h"
 #include "MantidCrystal/AnvredCorrection.h"
-#include "MantidDataObjects/Peak.h"
-#include "MantidDataObjects/PeaksWorkspace.h"
 #include "MantidGeometry/Instrument/Detector.h"
-#include "MantidKernel/Strings.h"
-#include "MantidKernel/System.h"
 #include "MantidKernel/Utils.h"
-#include "MantidKernel/V3D.h"
-#include <boost/math/special_functions/fpclassify.hpp>
 #include <fstream>
 
 using namespace Mantid::Geometry;
diff --git a/Code/Mantid/Framework/Crystal/src/LoadIsawPeaks.cpp b/Code/Mantid/Framework/Crystal/src/LoadIsawPeaks.cpp
index e7a9803055a549b762cf8bede11ce8dde7a44aee..23b60552a2816170cfc904db9b82faa06f432e35 100644
--- a/Code/Mantid/Framework/Crystal/src/LoadIsawPeaks.cpp
+++ b/Code/Mantid/Framework/Crystal/src/LoadIsawPeaks.cpp
@@ -1,25 +1,9 @@
 #include "MantidAPI/FileProperty.h"
 #include "MantidAPI/RegisterFileLoader.h"
 #include "MantidCrystal/LoadIsawPeaks.h"
-#include "MantidDataObjects/PeaksWorkspace.h"
 #include "MantidGeometry/Crystal/OrientedLattice.h"
-#include "MantidGeometry/IComponent.h"
-#include "MantidGeometry/Instrument/Goniometer.h"
 #include "MantidGeometry/Instrument/RectangularDetector.h"
-#include "MantidKernel/Strings.h"
-#include "MantidKernel/System.h"
 #include "MantidCrystal/SCDCalibratePanels.h"
-#include <algorithm>
-#include <boost/shared_ptr.hpp>
-#include <exception>
-#include <fstream>
-#include <iostream>
-#include <math.h>
-#include <ostream>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string>
-#include "MantidKernel/Unit.h"
 
 using Mantid::Kernel::Strings::readToEndOfLine;
 using Mantid::Kernel::Strings::getWord;
diff --git a/Code/Mantid/Framework/Crystal/src/LoadIsawSpectrum.cpp b/Code/Mantid/Framework/Crystal/src/LoadIsawSpectrum.cpp
index 6cdc650724f6e27ce6883e014a1e11b71fb42c49..1020210a59d8f48c1c261685b9a4e787d7427f38 100644
--- a/Code/Mantid/Framework/Crystal/src/LoadIsawSpectrum.cpp
+++ b/Code/Mantid/Framework/Crystal/src/LoadIsawSpectrum.cpp
@@ -3,14 +3,10 @@
 #include "MantidCrystal/LoadIsawSpectrum.h"
 #include "MantidDataObjects/Workspace2D.h"
 #include "MantidGeometry/Instrument/RectangularDetector.h"
-#include "MantidKernel/Strings.h"
-#include "MantidKernel/System.h"
 #include "MantidKernel/Utils.h"
-#include "MantidKernel/V3D.h"
 #include "MantidKernel/BoundedValidator.h"
 #include "MantidKernel/UnitFactory.h"
 #include "MantidKernel/ListValidator.h"
-#include <boost/math/special_functions/fpclassify.hpp>
 #include <fstream>
 
 using namespace Mantid::Geometry;
diff --git a/Code/Mantid/Framework/Crystal/src/LoadIsawUB.cpp b/Code/Mantid/Framework/Crystal/src/LoadIsawUB.cpp
index c0b591fc4dc55a28f3d6696ba38dafc6941afb1c..baf2b8806a7adbf51dc6a8732ab161cafb78ee4c 100644
--- a/Code/Mantid/Framework/Crystal/src/LoadIsawUB.cpp
+++ b/Code/Mantid/Framework/Crystal/src/LoadIsawUB.cpp
@@ -1,12 +1,7 @@
 #include "MantidAPI/FileProperty.h"
 #include "MantidCrystal/LoadIsawUB.h"
-#include "MantidKernel/Matrix.h"
-#include "MantidKernel/Strings.h"
-#include "MantidKernel/System.h"
 #include <fstream>
-#include <iosfwd>
 #include <MantidGeometry/Crystal/OrientedLattice.h>
-#include <MantidGeometry/Crystal/UnitCell.h>
 #include "MantidAPI/IMDEventWorkspace.h"
 
 using namespace Mantid::Kernel::Strings;
diff --git a/Code/Mantid/Framework/Crystal/src/MaskPeaksWorkspace.cpp b/Code/Mantid/Framework/Crystal/src/MaskPeaksWorkspace.cpp
index 033ef22ea74dc1ff82870ac6b7ad93026dd043c2..3858d0084a2ea4560e6def8436a3905ef3640d02 100644
--- a/Code/Mantid/Framework/Crystal/src/MaskPeaksWorkspace.cpp
+++ b/Code/Mantid/Framework/Crystal/src/MaskPeaksWorkspace.cpp
@@ -9,16 +9,7 @@
 #include "MantidAPI/IPeakFunction.h"
 #include "MantidKernel/VectorHelper.h"
 #include "MantidKernel/ArrayProperty.h"
-#include "MantidKernel/Strings.h"
-#include "MantidDataObjects/TableWorkspace.h"
-#include "MantidAPI/TableRow.h"
-#include "MantidGeometry/Instrument/RectangularDetector.h"
-#include <boost/math/special_functions/fpclassify.hpp>
 #include <fstream>
-#include <ostream>
-#include <iomanip>
-#include <sstream>
-#include <set>
 
 namespace Mantid {
 namespace Crystal {
diff --git a/Code/Mantid/Framework/Crystal/src/NormaliseVanadium.cpp b/Code/Mantid/Framework/Crystal/src/NormaliseVanadium.cpp
index 7e648df811b71352e097f2667b88aaefc40e3d51..dd7b026f1c4a54171729bd101e1a436d104b9caa 100644
--- a/Code/Mantid/Framework/Crystal/src/NormaliseVanadium.cpp
+++ b/Code/Mantid/Framework/Crystal/src/NormaliseVanadium.cpp
@@ -3,14 +3,10 @@
 //----------------------------------------------------------------------
 #include "MantidCrystal/NormaliseVanadium.h"
 #include "MantidAPI/WorkspaceValidators.h"
-#include "MantidGeometry/Objects/ShapeFactory.h"
 #include "MantidKernel/BoundedValidator.h"
 #include "MantidKernel/UnitFactory.h"
 #include "MantidKernel/Fast_Exponential.h"
 #include "MantidKernel/VectorHelper.h"
-#include "MantidKernel/Unit.h"
-#include "MantidKernel/PhysicalConstants.h"
-#include "MantidKernel/V3D.h"
 
 /*  Following A.J.Schultz's anvred, scaling the vanadium spectra:
  */
diff --git a/Code/Mantid/Framework/Crystal/src/OptimizeCrystalPlacement.cpp b/Code/Mantid/Framework/Crystal/src/OptimizeCrystalPlacement.cpp
index 618ff67422028bf613e87eaa475c06635c8c5c4e..6bb40d44dea86c6454eb984c46a8fc1996ce0f85 100644
--- a/Code/Mantid/Framework/Crystal/src/OptimizeCrystalPlacement.cpp
+++ b/Code/Mantid/Framework/Crystal/src/OptimizeCrystalPlacement.cpp
@@ -10,23 +10,10 @@
 #include "MantidCrystal/OptimizeCrystalPlacement.h"
 #include "MantidCrystal/PeakHKLErrors.h"
 #include "MantidCrystal/SCDCalibratePanels.h"
-#include "MantidDataObjects/PeaksWorkspace.h"
 #include "MantidGeometry/Crystal/IndexingUtils.h"
-#include "MantidGeometry/Crystal/OrientedLattice.h"
-#include "MantidGeometry/Instrument.h"
-#include "MantidGeometry/Instrument/ParameterMap.h"
 #include "MantidKernel/ArrayProperty.h"
 #include "MantidKernel/EnabledWhenProperty.h"
-#include "MantidKernel/IPropertySettings.h"
-#include "MantidKernel/Property.h"
-#include "MantidKernel/V3D.h"
-#include <boost/lexical_cast.hpp>
 #include <cstdarg>
-#include <iostream>
-#include <map>
-
-#include <math.h>
-#include <sstream>
 
 using namespace Mantid::API;
 using namespace Mantid::DataObjects;
diff --git a/Code/Mantid/Framework/Crystal/src/OptimizeExtinctionParameters.cpp b/Code/Mantid/Framework/Crystal/src/OptimizeExtinctionParameters.cpp
index d0a2372fa9e0be5b12a9d84928243ab42ae6944d..5cb88b11706a63b570e70bf636db0d70b0f9b9f5 100644
--- a/Code/Mantid/Framework/Crystal/src/OptimizeExtinctionParameters.cpp
+++ b/Code/Mantid/Framework/Crystal/src/OptimizeExtinctionParameters.cpp
@@ -1,7 +1,5 @@
 #include "MantidCrystal/OptimizeExtinctionParameters.h"
-#include "MantidCrystal/GSLFunctions.h"
 #include "MantidDataObjects/PeaksWorkspace.h"
-#include "MantidGeometry/Crystal/PointGroup.h"
 #include "MantidAPI/FileProperty.h"
 #include "MantidAPI/FunctionFactory.h"
 #include "MantidAPI/WorkspaceValidators.h"
@@ -11,11 +9,7 @@
 #include "MantidKernel/VectorHelper.h"
 #include "MantidKernel/ListValidator.h"
 #include "MantidKernel/BoundedValidator.h"
-#include <boost/math/special_functions/fpclassify.hpp>
 #include <fstream>
-#include <iomanip>
-#include <ostream>
-#include <sstream>
 
 using namespace Mantid::Geometry;
 
diff --git a/Code/Mantid/Framework/Crystal/src/OptimizeLatticeForCellType.cpp b/Code/Mantid/Framework/Crystal/src/OptimizeLatticeForCellType.cpp
index c5690373f3cc2149eac21d87022e395bf6f22db8..4d9e7135eee9b261bc79a04facfb8a245260cdae 100644
--- a/Code/Mantid/Framework/Crystal/src/OptimizeLatticeForCellType.cpp
+++ b/Code/Mantid/Framework/Crystal/src/OptimizeLatticeForCellType.cpp
@@ -1,6 +1,5 @@
 #include "MantidCrystal/OptimizeLatticeForCellType.h"
 #include "MantidCrystal/GSLFunctions.h"
-#include "MantidDataObjects/PeaksWorkspace.h"
 #include "MantidAPI/FileProperty.h"
 #include "MantidAPI/FunctionFactory.h"
 #include "MantidAPI/WorkspaceValidators.h"
@@ -12,11 +11,7 @@
 #include "MantidGeometry/Crystal/IndexingUtils.h"
 #include "MantidGeometry/Instrument/RectangularDetector.h"
 #include "MantidGeometry/Crystal/ReducedCell.h"
-#include <boost/math/special_functions/fpclassify.hpp>
 #include <fstream>
-#include <iomanip>
-#include <ostream>
-#include <sstream>
 
 using namespace Mantid::Geometry;
 
diff --git a/Code/Mantid/Framework/Crystal/src/PeakBackground.cpp b/Code/Mantid/Framework/Crystal/src/PeakBackground.cpp
index 725e991100667f8ea808da972c9fc39137e79dbe..4d0e576afb79707792cdbe888db1c50a445e7cd2 100644
--- a/Code/Mantid/Framework/Crystal/src/PeakBackground.cpp
+++ b/Code/Mantid/Framework/Crystal/src/PeakBackground.cpp
@@ -1,7 +1,5 @@
 #include "MantidCrystal/PeakBackground.h"
 #include "MantidAPI/IPeak.h"
-#include <boost/function.hpp>
-#include <boost/bind.hpp>
 
 using namespace Mantid::API;
 using namespace Mantid::Kernel;
diff --git a/Code/Mantid/Framework/Crystal/src/PeakClusterProjection.cpp b/Code/Mantid/Framework/Crystal/src/PeakClusterProjection.cpp
index ddc8c2cc7e55ee318ce8dbe930b9b481ec55c697..4e0d065a58c0a2782a1e8261c852ba22fec43cde 100644
--- a/Code/Mantid/Framework/Crystal/src/PeakClusterProjection.cpp
+++ b/Code/Mantid/Framework/Crystal/src/PeakClusterProjection.cpp
@@ -1,6 +1,5 @@
 #include "MantidCrystal/PeakClusterProjection.h"
 
-#include "MantidKernel/V3D.h"
 #include "MantidAPI/IPeak.h"
 #include "MantidAPI/IMDHistoWorkspace.h"
 #include "MantidAPI/IMDEventWorkspace.h"
@@ -8,8 +7,6 @@
 #include "MantidAPI/PeakTransformQLab.h"
 #include "MantidAPI/PeakTransformQSample.h"
 
-#include <stdexcept>
-
 using namespace Mantid::Kernel;
 using namespace Mantid::API;
 
diff --git a/Code/Mantid/Framework/Crystal/src/PeakHKLErrors.cpp b/Code/Mantid/Framework/Crystal/src/PeakHKLErrors.cpp
index d1bdde4a092eb4d694743f54423a450815ef65fc..1c4cd59e318e88eb6d014636f408f825dc7aad4f 100644
--- a/Code/Mantid/Framework/Crystal/src/PeakHKLErrors.cpp
+++ b/Code/Mantid/Framework/Crystal/src/PeakHKLErrors.cpp
@@ -11,18 +11,6 @@
 #include "MantidAPI/ParamFunction.h"
 #include "MantidCrystal/PeakHKLErrors.h"
 #include "MantidCrystal/SCDPanelErrors.h"
-#include "MantidDataObjects/Peak.h"
-#include "MantidDataObjects/PeaksWorkspace.h"
-#include "MantidGeometry/IComponent.h"
-#include "MantidGeometry/Instrument/CompAssembly.h"
-#include "MantidGeometry/Instrument/Goniometer.h"
-#include "MantidGeometry/Instrument/ParameterMap.h"
-#include "MantidGeometry/IObjComponent.h"
-#include "MantidKernel/Matrix.h"
-#include "MantidKernel/Quat.h"
-#include "MantidKernel/V3D.h"
-#include <cctype>
-#include <string>
 
 using namespace Mantid::DataObjects;
 using namespace Mantid::API;
diff --git a/Code/Mantid/Framework/Crystal/src/PeakIntegration.cpp b/Code/Mantid/Framework/Crystal/src/PeakIntegration.cpp
index 25256cf29ac8028fd02f916a978f2fbd88c73e00..6fcf19ee1ac50bffafe8254dc83570ebc1cfcf2b 100644
--- a/Code/Mantid/Framework/Crystal/src/PeakIntegration.cpp
+++ b/Code/Mantid/Framework/Crystal/src/PeakIntegration.cpp
@@ -1,29 +1,20 @@
 //----------------------------------------------------------------------
 // Includes
 //----------------------------------------------------------------------
-#include "MantidCrystal/PeakIntegration.h"
-#include "MantidDataObjects/PeaksWorkspace.h"
-#include "MantidDataObjects/EventWorkspace.h"
+#include "MantidAPI/MemoryManager.h"
 #include "MantidAPI/WorkspaceValidators.h"
 #include "MantidAPI/FileProperty.h"
 #include "MantidAPI/FunctionFactory.h"
 #include "MantidAPI/IPeakFunction.h"
-#include "MantidKernel/VectorHelper.h"
-#include "MantidKernel/ArrayProperty.h"
-#include <boost/math/special_functions/fpclassify.hpp>
-#include <fstream>
-#include <ostream>
-#include <iomanip>
-#include <sstream>
-#include "MantidGeometry/IComponent.h"
-#include "MantidGeometry/ICompAssembly.h"
+#include "MantidCrystal/PeakIntegration.h"
+#include "MantidDataObjects/EventWorkspace.h"
 #include "MantidGeometry/Instrument/RectangularDetector.h"
 #include "MantidGeometry/Crystal/OrientedLattice.h"
-#include <boost/algorithm/string.hpp>
 #include "MantidKernel/VectorHelper.h"
+#include "MantidKernel/ArrayProperty.h"
 #include "MantidKernel/VisibleWhenProperty.h"
-#include "MantidKernel/EnabledWhenProperty.h"
-#include "MantidAPI/MemoryManager.h"
+#include <boost/math/special_functions/fpclassify.hpp>
+#include <fstream>
 
 namespace Mantid {
 namespace Crystal {
diff --git a/Code/Mantid/Framework/Crystal/src/PeakIntensityVsRadius.cpp b/Code/Mantid/Framework/Crystal/src/PeakIntensityVsRadius.cpp
index e1381d541dabb89a468fb74552c1018693e9adac..4087e8020335d9529b523f922778038f393544e5 100644
--- a/Code/Mantid/Framework/Crystal/src/PeakIntensityVsRadius.cpp
+++ b/Code/Mantid/Framework/Crystal/src/PeakIntensityVsRadius.cpp
@@ -1,5 +1,4 @@
 #include "MantidCrystal/PeakIntensityVsRadius.h"
-#include "MantidKernel/Strings.h"
 #include "MantidDataObjects/PeaksWorkspace.h"
 #include "MantidAPI/IMDEventWorkspace.h"
 #include "MantidAPI/TextAxis.h"
diff --git a/Code/Mantid/Framework/Crystal/src/PeaksInRegion.cpp b/Code/Mantid/Framework/Crystal/src/PeaksInRegion.cpp
index dc590f5b4c62941b8d5fe6b2ced7bd86515ad3dd..24df2eb6c6b9b4d7d757c5b4c59f4c150f3519eb 100644
--- a/Code/Mantid/Framework/Crystal/src/PeaksInRegion.cpp
+++ b/Code/Mantid/Framework/Crystal/src/PeaksInRegion.cpp
@@ -3,7 +3,6 @@
 #include "MantidKernel/MandatoryValidator.h"
 #include "MantidKernel/EnabledWhenProperty.h"
 #include <boost/assign.hpp>
-#include <boost/make_shared.hpp>
 
 using namespace Mantid::Kernel;
 using namespace Mantid::API;
diff --git a/Code/Mantid/Framework/Crystal/src/PeaksIntersection.cpp b/Code/Mantid/Framework/Crystal/src/PeaksIntersection.cpp
index 8b15abbe552488bffde9ca5150723f92e93e1483..3d8be85431b653d5be05b6359a5e2c2262def078 100644
--- a/Code/Mantid/Framework/Crystal/src/PeaksIntersection.cpp
+++ b/Code/Mantid/Framework/Crystal/src/PeaksIntersection.cpp
@@ -1,16 +1,9 @@
 #include "MantidKernel/ListValidator.h"
-#include "MantidKernel/MandatoryValidator.h"
 #include "MantidAPI/IPeaksWorkspace.h"
 #include "MantidAPI/IPeak.h"
 #include "MantidAPI/TableRow.h"
 #include "MantidCrystal/PeaksIntersection.h"
 #include "MantidDataObjects/TableWorkspace.h"
-#include "MantidAPI/Progress.h"
-
-#include <boost/make_shared.hpp>
-#include <boost/function.hpp>
-#include <boost/bind.hpp>
-#include <vector>
 
 using namespace Mantid::API;
 using namespace Mantid::Geometry;
diff --git a/Code/Mantid/Framework/Crystal/src/PeaksOnSurface.cpp b/Code/Mantid/Framework/Crystal/src/PeaksOnSurface.cpp
index 3bd6da8e03fd5d7b4815a3fc17d4a80730719d0c..1eb0e4486dd81471a1c140d2fe3f34b7dfacf8c6 100644
--- a/Code/Mantid/Framework/Crystal/src/PeaksOnSurface.cpp
+++ b/Code/Mantid/Framework/Crystal/src/PeaksOnSurface.cpp
@@ -2,7 +2,6 @@
 #include "MantidKernel/ArrayProperty.h"
 #include "MantidKernel/MandatoryValidator.h"
 #include <boost/assign.hpp>
-#include <boost/make_shared.hpp>
 
 using namespace Mantid::Kernel;
 typedef std::vector<double> VecDouble;
diff --git a/Code/Mantid/Framework/Crystal/src/PredictFractionalPeaks.cpp b/Code/Mantid/Framework/Crystal/src/PredictFractionalPeaks.cpp
index 6bc333631c8417b63d8c7612feee353bba8c346a..77c854a42642429820447da8a405ee35be5eac24 100644
--- a/Code/Mantid/Framework/Crystal/src/PredictFractionalPeaks.cpp
+++ b/Code/Mantid/Framework/Crystal/src/PredictFractionalPeaks.cpp
@@ -6,15 +6,11 @@
 */
 #include "MantidCrystal/PredictFractionalPeaks.h"
 #include "MantidDataObjects/PeaksWorkspace.h"
-#include "MantidGeometry/Instrument.h"
-#include "MantidGeometry/IComponent.h"
 #include "MantidKernel/ArrayProperty.h"
 #include "MantidKernel/ArrayLengthValidator.h"
 #include "MantidKernel/EnabledWhenProperty.h"
 #include "MantidGeometry/Crystal/OrientedLattice.h"
 
-#include <math.h>
-#include "MantidKernel/IPropertySettings.h"
 //#include "MantidKernel/Strings.h"
 namespace Mantid {
 using namespace Mantid::DataObjects;
diff --git a/Code/Mantid/Framework/Crystal/src/PredictPeaks.cpp b/Code/Mantid/Framework/Crystal/src/PredictPeaks.cpp
index 9e74b95668ce6010cb4ed715e4383073bbb4fbc5..155bfe79a7b3d620ac3715b18791b723768fd2b2 100644
--- a/Code/Mantid/Framework/Crystal/src/PredictPeaks.cpp
+++ b/Code/Mantid/Framework/Crystal/src/PredictPeaks.cpp
@@ -1,16 +1,7 @@
 #include "MantidCrystal/PredictPeaks.h"
-#include "MantidDataObjects/Peak.h"
-#include "MantidDataObjects/PeaksWorkspace.h"
-#include "MantidGeometry/Crystal/UnitCell.h"
-#include "MantidKernel/Matrix.h"
 #include "MantidGeometry/Objects/InstrumentRayTracer.h"
-#include "MantidKernel/PropertyWithValue.h"
-#include "MantidKernel/System.h"
-#include <cmath>
-#include <MantidGeometry/Crystal/OrientedLattice.h>
 #include "MantidKernel/ListValidator.h"
 #include "MantidAPI/WorkspaceValidators.h"
-#include "MantidGeometry/Crystal/ReflectionCondition.h"
 #include "MantidKernel/EnabledWhenProperty.h"
 #include "MantidAPI/IMDEventWorkspace.h"
 
diff --git a/Code/Mantid/Framework/Crystal/src/SCDCalibratePanels.cpp b/Code/Mantid/Framework/Crystal/src/SCDCalibratePanels.cpp
index 106ed965dab2d10f23f8e4be54ceb8bc845d3837..f332fd11dd62fe438868b3270f4d4c6c4c88ff82 100644
--- a/Code/Mantid/Framework/Crystal/src/SCDCalibratePanels.cpp
+++ b/Code/Mantid/Framework/Crystal/src/SCDCalibratePanels.cpp
@@ -1,34 +1,14 @@
 #include "MantidCrystal/SCDCalibratePanels.h"
-#include "MantidAPI/Algorithm.h"
 #include "MantidAPI/ConstraintFactory.h"
-#include "MantidDataObjects/PeaksWorkspace.h"
-#include "MantidDataObjects/Workspace2D.h"
-#include "MantidGeometry/Instrument.h"
-#include "MantidGeometry/IComponent.h"
-#include "MantidGeometry/Instrument/RectangularDetector.h"
-#include "MantidAPI/MatrixWorkspace.h"
 #include "MantidKernel/BoundedValidator.h"
 #include "MantidKernel/EnabledWhenProperty.h"
-#include "MantidGeometry/Instrument/ParameterMap.h"
-#include "MantidKernel/V3D.h"
-#include "MantidKernel/Quat.h"
 #include "MantidAPI/FileProperty.h"
 #include "MantidKernel/ListValidator.h"
 
-#include "MantidAPI/Workspace.h"
 #include "MantidAPI/IFunction.h"
 #include "MantidAPI/FunctionFactory.h"
 #include "MantidAPI/IFunction1D.h"
-#include "MantidAPI/ITableWorkspace.h"
-#include <boost/algorithm/string/trim.hpp>
-#include <iostream>
 #include <fstream>
-#include <math.h>
-#include <boost/algorithm/string.hpp>
-#include <boost/lexical_cast.hpp>
-#include "MantidKernel/Property.h"
-#include "MantidAPI/IFunction.h"
-#include "MantidGeometry/Instrument/RectangularDetector.h"
 #include "MantidGeometry/Crystal/IndexingUtils.h"
 #include "MantidGeometry/Crystal/OrientedLattice.h"
 
diff --git a/Code/Mantid/Framework/Crystal/src/SCDPanelErrors.cpp b/Code/Mantid/Framework/Crystal/src/SCDPanelErrors.cpp
index 717bc8895c0986bb66a976c55ef6d5a8a16d35b3..45341497a72224b56a4320adca399d958072eb64 100644
--- a/Code/Mantid/Framework/Crystal/src/SCDPanelErrors.cpp
+++ b/Code/Mantid/Framework/Crystal/src/SCDPanelErrors.cpp
@@ -1,15 +1,8 @@
 #include "MantidCrystal/SCDPanelErrors.h"
 #include "MantidCrystal/SCDCalibratePanels.h"
-#include "MantidAPI/WorkspaceFactory.h"
 #include "MantidAPI/FunctionFactory.h"
-#include "MantidGeometry/Instrument/RectangularDetector.h"
 #include "MantidGeometry/Crystal/OrientedLattice.h"
 #include "MantidGeometry/Crystal/IndexingUtils.h"
-#include "MantidGeometry/Instrument/Parameter.h"
-#include "MantidDataObjects/PeaksWorkspace.h"
-#include <boost/lexical_cast.hpp>
-#include <stdio.h>
-#include <math.h>
 
 using namespace Mantid::API;
 using namespace Mantid::DataObjects;
diff --git a/Code/Mantid/Framework/Crystal/src/SaveHKL.cpp b/Code/Mantid/Framework/Crystal/src/SaveHKL.cpp
index 88ddcfbbd808fd37b57aa352e3b12ca28023b704..4b8052438da93280f7ac950c923e8a0a2ecaf385 100644
--- a/Code/Mantid/Framework/Crystal/src/SaveHKL.cpp
+++ b/Code/Mantid/Framework/Crystal/src/SaveHKL.cpp
@@ -1,21 +1,16 @@
 #include "MantidAPI/FileProperty.h"
 #include "MantidAPI/WorkspaceValidators.h"
 #include "MantidCrystal/SaveHKL.h"
-#include "MantidDataObjects/Peak.h"
-#include "MantidDataObjects/PeaksWorkspace.h"
 #include "MantidGeometry/Instrument/RectangularDetector.h"
-#include "MantidKernel/Strings.h"
-#include "MantidKernel/System.h"
 #include "MantidKernel/Utils.h"
-#include "MantidKernel/V3D.h"
 #include "MantidKernel/BoundedValidator.h"
 #include "MantidKernel/UnitFactory.h"
 #include "MantidKernel/ListValidator.h"
 #include "MantidCrystal/AnvredCorrection.h"
-#include <boost/math/special_functions/fpclassify.hpp>
 #include <fstream>
 #include "Poco/File.h"
 #include "boost/assign.hpp"
+#include <boost/math/special_functions/fpclassify.hpp>
 
 using namespace Mantid::Geometry;
 using namespace Mantid::DataObjects;
@@ -101,6 +96,7 @@ void SaveHKL::init() {
                   "The minimum Intensity");
   declareProperty(new WorkspaceProperty<PeaksWorkspace>("OutputWorkspace", "SaveHKLOutput",
                                                         Direction::Output), "Output PeaksWorkspace");
+  declareProperty("HKLDecimalPlaces", EMPTY_INT(), "Number of decimal places for fractional HKL.  Default is integer HKL.");
 }
 
 //----------------------------------------------------------------------------------------------
@@ -122,6 +118,7 @@ void SaveHKL::exec() {
   double minIsigI = getProperty("MinIsigI");
   double minIntensity = getProperty("MinIntensity");
   int widthBorder = getProperty("WidthBorder");
+  int decimalHKL = getProperty("HKLDecimalPlaces");
 
   // Sequence and run number
   int seqNum = 1;
@@ -288,7 +285,8 @@ void SaveHKL::exec() {
     std::string bankName = p.getBankName();
     int nCols, nRows;
     sizeBanks(bankName, nCols, nRows);
-    if (widthBorder != EMPTY_INT() &&
+    // peaks with detectorID=-1 are from LoadHKL
+    if (widthBorder != EMPTY_INT() && p.getDetectorID() != -1 &&
         (p.getCol() < widthBorder || p.getRow() < widthBorder ||
          p.getCol() > (nCols - widthBorder) ||
          p.getRow() > (nRows - widthBorder))){
@@ -326,8 +324,14 @@ void SaveHKL::exec() {
       banned.push_back(wi);
       continue;
     }
-    out << std::setw(4) << Utils::round(-p.getH()) << std::setw(4)
-        << Utils::round(-p.getK()) << std::setw(4) << Utils::round(-p.getL());
+    if (decimalHKL == EMPTY_INT() )
+      out << std::setw(4) << Utils::round(-p.getH())
+            << std::setw(4) << Utils::round(-p.getK())
+            << std::setw(4) << Utils::round(-p.getL());
+    else
+      out << std::setw(5+decimalHKL) << std::fixed << std::setprecision(decimalHKL) << -p.getH()
+            << std::setw(5+decimalHKL) << std::fixed << std::setprecision(decimalHKL) << -p.getK()
+            << std::setw(5+decimalHKL) << std::fixed << std::setprecision(decimalHKL) << -p.getL();
     double correc = scaleFactor;
     double relSigSpect = 0.0;
     if (bank != bankold)
@@ -429,7 +433,15 @@ void SaveHKL::exec() {
 
     out << std::endl;
   }
-  out << "   0   0   0    0.00    0.00   0  0.0000 0.0000      0      0 0.0000 "
+  if (decimalHKL == EMPTY_INT() )
+    out << std::setw(4) << 0
+          << std::setw(4) << 0
+          << std::setw(4) << 0;
+  else
+    out << std::setw(5+decimalHKL) << std::fixed << std::setprecision(decimalHKL) << 0.0
+          << std::setw(5+decimalHKL) << std::fixed << std::setprecision(decimalHKL) << 0.0
+          << std::setw(5+decimalHKL) << std::fixed << std::setprecision(decimalHKL) << 0.0;
+  out << "    0.00    0.00   0  0.0000 0.0000      0      0 0.0000 "
          "  0";
   out << std::endl;
 
diff --git a/Code/Mantid/Framework/Crystal/src/SaveIsawPeaks.cpp b/Code/Mantid/Framework/Crystal/src/SaveIsawPeaks.cpp
index d0705a96ade79a979a7885db857a7f1bc8c00df6..44e3e5a7d5d1f9cef5824e9bb96f1f7c20513f6e 100644
--- a/Code/Mantid/Framework/Crystal/src/SaveIsawPeaks.cpp
+++ b/Code/Mantid/Framework/Crystal/src/SaveIsawPeaks.cpp
@@ -4,10 +4,7 @@
 #include "MantidDataObjects/Peak.h"
 #include "MantidDataObjects/PeaksWorkspace.h"
 #include "MantidGeometry/Instrument/RectangularDetector.h"
-#include "MantidKernel/Strings.h"
-#include "MantidKernel/System.h"
 #include "MantidKernel/Utils.h"
-#include "MantidKernel/V3D.h"
 #include "MantidDataObjects/Workspace2D.h"
 #include <fstream>
 #include <Poco/File.h>
diff --git a/Code/Mantid/Framework/Crystal/src/SaveIsawUB.cpp b/Code/Mantid/Framework/Crystal/src/SaveIsawUB.cpp
index a2ba70830a4f219bd0efdcee5c0e0ef3b2b69c27..a703b70cd8610e1df765c94b173756a728e9a16a 100644
--- a/Code/Mantid/Framework/Crystal/src/SaveIsawUB.cpp
+++ b/Code/Mantid/Framework/Crystal/src/SaveIsawUB.cpp
@@ -1,14 +1,6 @@
 #include "MantidAPI/FileProperty.h"
 #include "MantidCrystal/SaveIsawUB.h"
-#include "MantidKernel/Matrix.h"
-#include "MantidKernel/System.h"
-#include <iostream>
 #include <fstream>
-#include <iomanip>
-#include <stdio.h>
-#include <exception>
-#include <MantidGeometry/Crystal/OrientedLattice.h>
-#include <MantidGeometry/Crystal/UnitCell.h>
 #include "MantidAPI/IMDEventWorkspace.h"
 
 using Mantid::Kernel::DblMatrix;
diff --git a/Code/Mantid/Framework/Crystal/src/SaveLauenorm.cpp b/Code/Mantid/Framework/Crystal/src/SaveLauenorm.cpp
index 8a87ea3a724ad2c276fe690fc5db513c3a338430..927a86d07c8a9797dfd8a0df0164c71fc6268431 100644
--- a/Code/Mantid/Framework/Crystal/src/SaveLauenorm.cpp
+++ b/Code/Mantid/Framework/Crystal/src/SaveLauenorm.cpp
@@ -1,22 +1,17 @@
 #include "MantidAPI/FileProperty.h"
 #include "MantidAPI/WorkspaceValidators.h"
 #include "MantidCrystal/SaveLauenorm.h"
-#include "MantidDataObjects/Peak.h"
-#include "MantidDataObjects/PeaksWorkspace.h"
 #include "MantidGeometry/Instrument/RectangularDetector.h"
-#include "MantidKernel/Strings.h"
-#include "MantidKernel/System.h"
 #include "MantidKernel/Utils.h"
-#include "MantidKernel/V3D.h"
 #include "MantidKernel/BoundedValidator.h"
 #include "MantidKernel/UnitFactory.h"
 #include "MantidKernel/ListValidator.h"
 #include "MantidCrystal/AnvredCorrection.h"
-#include <boost/math/special_functions/fpclassify.hpp>
 #include <fstream>
 #include <Poco/File.h>
 #include <Poco/Path.h>
 #include "boost/assign.hpp"
+#include <boost/math/special_functions/fpclassify.hpp>
 
 using namespace Mantid::Geometry;
 using namespace Mantid::DataObjects;
diff --git a/Code/Mantid/Framework/Crystal/src/SavePeaksFile.cpp b/Code/Mantid/Framework/Crystal/src/SavePeaksFile.cpp
index 026882f20f5702959778eb272ca6e2ebedaf97e4..539fad3fdb3703cca9693740bb47ef95e86758e0 100644
--- a/Code/Mantid/Framework/Crystal/src/SavePeaksFile.cpp
+++ b/Code/Mantid/Framework/Crystal/src/SavePeaksFile.cpp
@@ -1,5 +1,4 @@
 #include "MantidCrystal/SavePeaksFile.h"
-#include "MantidKernel/System.h"
 #include "MantidAPI/FileProperty.h"
 #include "MantidDataObjects/PeaksWorkspace.h"
 
diff --git a/Code/Mantid/Framework/Crystal/src/SelectCellOfType.cpp b/Code/Mantid/Framework/Crystal/src/SelectCellOfType.cpp
index e99771781bf9cd4d103f826aa18d85b110d09029..5e9367c6c38a39899823f01ebf3bff522d80784a 100644
--- a/Code/Mantid/Framework/Crystal/src/SelectCellOfType.cpp
+++ b/Code/Mantid/Framework/Crystal/src/SelectCellOfType.cpp
@@ -1,15 +1,9 @@
 #include "MantidCrystal/SelectCellOfType.h"
-#include "MantidCrystal/IndexPeaks.h"
 #include "MantidDataObjects/PeaksWorkspace.h"
-#include "MantidDataObjects/Peak.h"
 #include "MantidGeometry/Crystal/IndexingUtils.h"
 #include "MantidGeometry/Crystal/ScalarUtils.h"
-#include "MantidGeometry/Crystal/ReducedCell.h"
-#include "MantidGeometry/Crystal/ConventionalCell.h"
 #include "MantidGeometry/Crystal/OrientedLattice.h"
 #include "MantidKernel/ListValidator.h"
-#include <boost/lexical_cast.hpp>
-#include <cstdio>
 #include "MantidCrystal/SelectCellWithForm.h"
 
 namespace Mantid {
diff --git a/Code/Mantid/Framework/Crystal/src/SelectCellWithForm.cpp b/Code/Mantid/Framework/Crystal/src/SelectCellWithForm.cpp
index 8333b2660de5b45e9884b86f3ff2913bc1005791..e8c7d98ba3742bb88d6650d5184f45d569a618cd 100644
--- a/Code/Mantid/Framework/Crystal/src/SelectCellWithForm.cpp
+++ b/Code/Mantid/Framework/Crystal/src/SelectCellWithForm.cpp
@@ -1,15 +1,8 @@
 #include "MantidCrystal/SelectCellWithForm.h"
-#include "MantidCrystal/IndexPeaks.h"
-#include "MantidDataObjects/PeaksWorkspace.h"
-#include "MantidDataObjects/Peak.h"
 #include "MantidGeometry/Crystal/IndexingUtils.h"
 #include "MantidGeometry/Crystal/ScalarUtils.h"
-#include "MantidGeometry/Crystal/ReducedCell.h"
-#include "MantidGeometry/Crystal/ConventionalCell.h"
 #include "MantidGeometry/Crystal/OrientedLattice.h"
 #include "MantidKernel/BoundedValidator.h"
-#include <boost/lexical_cast.hpp>
-#include <cstdio>
 
 namespace Mantid {
 namespace Crystal {
diff --git a/Code/Mantid/Framework/Crystal/src/SetGoniometer.cpp b/Code/Mantid/Framework/Crystal/src/SetGoniometer.cpp
index 507b9a96ca7cb31bb16967fbf621f471dc95329b..d6a15000cd9e0578390372892086072f822fd616 100644
--- a/Code/Mantid/Framework/Crystal/src/SetGoniometer.cpp
+++ b/Code/Mantid/Framework/Crystal/src/SetGoniometer.cpp
@@ -1,10 +1,4 @@
 #include "MantidCrystal/SetGoniometer.h"
-#include "MantidKernel/System.h"
-#include <boost/algorithm/string/split.hpp>
-#include "MantidKernel/Strings.h"
-#include "MantidGeometry/Instrument/Goniometer.h"
-#include <boost/algorithm/string/detail/classification.hpp>
-#include "MantidKernel/V3D.h"
 #include "MantidKernel/ListValidator.h"
 #include "MantidKernel/TimeSeriesProperty.h"
 
diff --git a/Code/Mantid/Framework/Crystal/src/SetSpecialCoordinates.cpp b/Code/Mantid/Framework/Crystal/src/SetSpecialCoordinates.cpp
index 61ecc88afb96ba393511d9b0d1dc4b58c8643696..3f2509ef47e1c486d4bd0153ae6fc317684b60b3 100644
--- a/Code/Mantid/Framework/Crystal/src/SetSpecialCoordinates.cpp
+++ b/Code/Mantid/Framework/Crystal/src/SetSpecialCoordinates.cpp
@@ -1,11 +1,9 @@
 #include "MantidCrystal/SetSpecialCoordinates.h"
 #include "MantidAPI/WorkspaceValidators.h"
-#include "MantidAPI/IMDWorkspace.h"
 #include "MantidAPI/IPeaksWorkspace.h"
 #include "MantidAPI/IMDEventWorkspace.h"
 #include "MantidAPI/IMDHistoWorkspace.h"
 #include "MantidKernel/ListValidator.h"
-#include <boost/make_shared.hpp>
 
 using namespace Mantid::Kernel;
 using namespace Mantid::API;
diff --git a/Code/Mantid/Framework/Crystal/src/SetUB.cpp b/Code/Mantid/Framework/Crystal/src/SetUB.cpp
index be04d87473a82fec332dcde4eebed26655818e7d..9b2b96f4a34e19e0576c156adce36c63d3a2e357 100644
--- a/Code/Mantid/Framework/Crystal/src/SetUB.cpp
+++ b/Code/Mantid/Framework/Crystal/src/SetUB.cpp
@@ -1,5 +1,4 @@
 #include "MantidCrystal/SetUB.h"
-#include "MantidKernel/System.h"
 #include "MantidKernel/ArrayProperty.h"
 #include "MantidKernel/ArrayLengthValidator.h"
 #include "MantidKernel/BoundedValidator.h"
diff --git a/Code/Mantid/Framework/Crystal/src/ShowPeakHKLOffsets.cpp b/Code/Mantid/Framework/Crystal/src/ShowPeakHKLOffsets.cpp
index 226c757a7a236dca64e797a147790c9da70bf57a..fd6a223048642ece5f97ac9a4689547bb0df5747 100644
--- a/Code/Mantid/Framework/Crystal/src/ShowPeakHKLOffsets.cpp
+++ b/Code/Mantid/Framework/Crystal/src/ShowPeakHKLOffsets.cpp
@@ -1,15 +1,7 @@
 #include "MantidDataObjects/PeaksWorkspace.h"
 #include "MantidAPI/WorkspaceProperty.h"
-#include "MantidKernel/Property.h"
-#include "MantidDataObjects/TableWorkspace.h"
 #include "MantidCrystal/ShowPeakHKLOffsets.h"
-#include "MantidKernel/Matrix.h"
-#include "MantidDataObjects/Peak.h"
-#include "MantidKernel/V3D.h"
-#include "MantidAPI/Sample.h"
 #include "MantidGeometry/Crystal/OrientedLattice.h"
-#include "../../API/inc/MantidAPI/WorkspaceFactory.h"
-#include "../../API/inc/MantidAPI/ITableWorkspace.h"
 
 using Mantid::DataObjects::PeaksWorkspace;
 using Mantid::API::WorkspaceProperty;
@@ -40,7 +32,7 @@ void ShowPeakHKLOffsets::init() {
                                                         Direction::Input),
                   "Workspace of Peaks with UB loaded");
 
-  declareProperty(new WorkspaceProperty<TableWorkspace>("HKLIntegerOffsets",
+  declareProperty(new WorkspaceProperty<ITableWorkspace>("HKLIntegerOffsets",
                                                         "HKLIntegerOffsets",
                                                         Direction::Output),
                   "Workspace with the Results");
diff --git a/Code/Mantid/Framework/Crystal/src/ShowPossibleCells.cpp b/Code/Mantid/Framework/Crystal/src/ShowPossibleCells.cpp
index 69dcd153c5add7a2a5b3db6fc0d7e92ac3be3eb5..b26b880f1dfd1c6c45034a275f755cc2d72f3d24 100644
--- a/Code/Mantid/Framework/Crystal/src/ShowPossibleCells.cpp
+++ b/Code/Mantid/Framework/Crystal/src/ShowPossibleCells.cpp
@@ -1,12 +1,9 @@
 #include "MantidCrystal/ShowPossibleCells.h"
 #include "MantidDataObjects/PeaksWorkspace.h"
-#include "MantidDataObjects/Peak.h"
 #include "MantidGeometry/Crystal/IndexingUtils.h"
 #include "MantidGeometry/Crystal/ScalarUtils.h"
-#include "MantidGeometry/Crystal/ConventionalCell.h"
 #include "MantidGeometry/Crystal/OrientedLattice.h"
 #include "MantidKernel/BoundedValidator.h"
-#include <cstdio>
 
 namespace Mantid {
 namespace Crystal {
diff --git a/Code/Mantid/Framework/Crystal/src/SortHKL.cpp b/Code/Mantid/Framework/Crystal/src/SortHKL.cpp
index b489fdd72b5e7e33e0b2e33fec9a0c45c701af12..5e9adc68e696948a1cdeef3ec3ac314c89140f76 100644
--- a/Code/Mantid/Framework/Crystal/src/SortHKL.cpp
+++ b/Code/Mantid/Framework/Crystal/src/SortHKL.cpp
@@ -5,16 +5,8 @@
 #include "MantidDataObjects/PeaksWorkspace.h"
 #include "MantidGeometry/Instrument/RectangularDetector.h"
 #include "MantidGeometry/Crystal/PointGroupFactory.h"
-#include "MantidKernel/Strings.h"
-#include "MantidKernel/System.h"
 #include "MantidKernel/Utils.h"
-#include "MantidKernel/V3D.h"
-#include "MantidKernel/Statistics.h"
 #include "MantidKernel/ListValidator.h"
-#include "MantidDataObjects/TableWorkspace.h"
-#include "MantidAPI/TableRow.h"
-#include "MantidAPI/AnalysisDataService.h"
-#include <boost/math/special_functions/fpclassify.hpp>
 #include <fstream>
 
 using namespace Mantid::Geometry;
diff --git a/Code/Mantid/Framework/Crystal/src/SortPeaksWorkspace.cpp b/Code/Mantid/Framework/Crystal/src/SortPeaksWorkspace.cpp
index 2045ca8d73f848bc1658162d4650c8b51cba1a4e..68c05197b157e77ca20151367c0e03aaf259fa32 100644
--- a/Code/Mantid/Framework/Crystal/src/SortPeaksWorkspace.cpp
+++ b/Code/Mantid/Framework/Crystal/src/SortPeaksWorkspace.cpp
@@ -1,9 +1,5 @@
 #include "MantidCrystal/SortPeaksWorkspace.h"
-#include "MantidKernel/PropertyWithValue.h"
 #include "MantidKernel/MandatoryValidator.h"
-#include "MantidAPI/WorkspaceProperty.h"
-#include "MantidAPI/IPeaksWorkspace.h"
-#include <boost/make_shared.hpp>
 
 using namespace Mantid::Kernel;
 using namespace Mantid::API;
diff --git a/Code/Mantid/Framework/Crystal/src/StatisticsOfPeaksWorkspace.cpp b/Code/Mantid/Framework/Crystal/src/StatisticsOfPeaksWorkspace.cpp
index 477332812842294fea330880e4de6b940eb8937e..84451bb8e53fe7054a53822ef6b4c36111287535 100644
--- a/Code/Mantid/Framework/Crystal/src/StatisticsOfPeaksWorkspace.cpp
+++ b/Code/Mantid/Framework/Crystal/src/StatisticsOfPeaksWorkspace.cpp
@@ -1,20 +1,12 @@
 #include "MantidAPI/FileProperty.h"
 #include "MantidAPI/WorkspaceValidators.h"
 #include "MantidCrystal/StatisticsOfPeaksWorkspace.h"
-#include "MantidDataObjects/Peak.h"
-#include "MantidDataObjects/PeaksWorkspace.h"
-#include "MantidKernel/Strings.h"
-#include "MantidKernel/System.h"
 #include "MantidKernel/Utils.h"
-#include "MantidKernel/V3D.h"
 #include "MantidKernel/BoundedValidator.h"
 #include "MantidKernel/UnitFactory.h"
 #include "MantidKernel/ListValidator.h"
 
-#include <boost/math/special_functions/fpclassify.hpp>
 #include <fstream>
-#include <Poco/File.h>
-#include <Poco/Path.h>
 #include "boost/assign.hpp"
 
 using namespace Mantid::Geometry;
diff --git a/Code/Mantid/Framework/Crystal/src/TOFExtinction.cpp b/Code/Mantid/Framework/Crystal/src/TOFExtinction.cpp
index 175e30fdfebd3868d68623139f29c1ad2c1fa0ee..ca85e2173084a8ddd4966ad21966d8b33702258a 100644
--- a/Code/Mantid/Framework/Crystal/src/TOFExtinction.cpp
+++ b/Code/Mantid/Framework/Crystal/src/TOFExtinction.cpp
@@ -4,17 +4,10 @@
 #include "MantidDataObjects/Peak.h"
 #include "MantidDataObjects/PeaksWorkspace.h"
 #include "MantidGeometry/Instrument/RectangularDetector.h"
-#include "MantidKernel/Strings.h"
-#include "MantidKernel/System.h"
 #include "MantidKernel/Utils.h"
-#include "MantidKernel/V3D.h"
-#include "MantidKernel/Statistics.h"
 #include "MantidKernel/ListValidator.h"
-#include <boost/math/special_functions/fpclassify.hpp>
-#include "MantidDataObjects/TableWorkspace.h"
-#include "MantidAPI/TableRow.h"
-#include <boost/math/special_functions/fpclassify.hpp>
 #include <fstream>
+#include <boost/math/special_functions/fpclassify.hpp>
 
 using namespace Mantid::Geometry;
 using namespace Mantid::DataObjects;
diff --git a/Code/Mantid/Framework/Crystal/src/TransformHKL.cpp b/Code/Mantid/Framework/Crystal/src/TransformHKL.cpp
index 5af49dd1bdea8407bdb6806fa5283d8b1185c962..9e5179c5c0b4e94a41c5b3cd002d1d40bf6d5fb5 100644
--- a/Code/Mantid/Framework/Crystal/src/TransformHKL.cpp
+++ b/Code/Mantid/Framework/Crystal/src/TransformHKL.cpp
@@ -1,14 +1,10 @@
 #include "MantidCrystal/TransformHKL.h"
-#include "MantidKernel/System.h"
 #include "MantidDataObjects/PeaksWorkspace.h"
-#include "MantidDataObjects/Peak.h"
 #include "MantidGeometry/Crystal/IndexingUtils.h"
 #include "MantidGeometry/Crystal/OrientedLattice.h"
 #include "MantidKernel/BoundedValidator.h"
 #include "MantidKernel/ArrayProperty.h"
 #include "MantidKernel/ArrayLengthValidator.h"
-#include "MantidKernel/Matrix.h"
-#include <cstdio>
 #include "MantidCrystal/SelectCellWithForm.h"
 
 namespace Mantid {
diff --git a/Code/Mantid/Framework/Crystal/test/CalculateUMatrixTest.h b/Code/Mantid/Framework/Crystal/test/CalculateUMatrixTest.h
index 60ca8c8eaffaeec215e7e4507e4b6bfe7f9054df..740f4961200659309f7c961098438cdef2a1db66 100644
--- a/Code/Mantid/Framework/Crystal/test/CalculateUMatrixTest.h
+++ b/Code/Mantid/Framework/Crystal/test/CalculateUMatrixTest.h
@@ -199,7 +199,7 @@ private:
           phi.at(i)=ph(Hpeaks[i],Kpeaks[i],Lpeaks[i]);
       }
 
-      Mantid::Geometry::Instrument_sptr inst = ComponentCreationHelper::createCylInstrumentWithDetInGivenPosisions(L2,theta, phi);
+      auto inst = ComponentCreationHelper::createCylInstrumentWithDetInGivenPositions(L2,theta, phi);
       inst->setName("SillyInstrument");
       auto pw = PeaksWorkspace_sptr(new PeaksWorkspace);
       pw->setInstrument(inst);
diff --git a/Code/Mantid/Framework/Crystal/test/IntegratePeaksUsingClustersTest.h b/Code/Mantid/Framework/Crystal/test/IntegratePeaksUsingClustersTest.h
index 929a51b287ffc16237aeebdb2754557a4ef6e9af..fc15f46a0469704fb6ddef75c5e248e96f2befc1 100644
--- a/Code/Mantid/Framework/Crystal/test/IntegratePeaksUsingClustersTest.h
+++ b/Code/Mantid/Framework/Crystal/test/IntegratePeaksUsingClustersTest.h
@@ -256,7 +256,9 @@ public:
 //=====================================================================================
 // Performance Tests
 //=====================================================================================
+// clang-format off
 class IntegratePeaksUsingClustersTestPerformance : public CxxTest::TestSuite, public ClusterIntegrationBaseTest
+// clang-format on
 {
 
 private:
diff --git a/Code/Mantid/Framework/Crystal/test/ShowPeakHKLOffsetsTest.h b/Code/Mantid/Framework/Crystal/test/ShowPeakHKLOffsetsTest.h
index 53f4b5e5b98507bd9338b725874ac0aafaf29d0d..1097302cb13038e77048bc328325900cad28cc7a 100644
--- a/Code/Mantid/Framework/Crystal/test/ShowPeakHKLOffsetsTest.h
+++ b/Code/Mantid/Framework/Crystal/test/ShowPeakHKLOffsetsTest.h
@@ -8,10 +8,10 @@
 #ifndef SHOWPEAKHKLOFFSETSTEST_H_
 #define SHOWPEAKHKLOFFSETSTEST_H_
 #include <cxxtest/TestSuite.h>
+#include "MantidAPI/ITableWorkspace.h"
 #include "MantidCrystal/LoadIsawPeaks.h"
 #include "MantidCrystal/LoadIsawUB.h"
 #include "MantidCrystal/ShowPeakHKLOffsets.h"
-#include "../../DataObjects/inc/MantidDataObjects/TableWorkspace.h"
 
 using Mantid::Crystal::LoadIsawPeaks;
 using Mantid::Crystal::LoadIsawUB;
@@ -48,7 +48,7 @@ class ShowPeakHKLOffsetsTest: public CxxTest::TestSuite
      TS_ASSERT(show.execute())
      TS_ASSERT(show.isExecuted())
      show.setProperty("HKLIntegerOffsets","offsets");
-     boost::shared_ptr<TableWorkspace> Offsets= show.getProperty("HKLIntegerOffsets");
+     boost::shared_ptr<Mantid::API::ITableWorkspace> Offsets= show.getProperty("HKLIntegerOffsets"); 
 
 
      TS_ASSERT_DELTA( Offsets->Double(3,1), 0.0186555,.1)
diff --git a/Code/Mantid/Framework/CurveFitting/CMakeLists.txt b/Code/Mantid/Framework/CurveFitting/CMakeLists.txt
index 987301cf78bcd134fa4d89bb421996bfaa8c2a63..c60bcf76181e2c4767500287ab874c7fbb1388c7 100644
--- a/Code/Mantid/Framework/CurveFitting/CMakeLists.txt
+++ b/Code/Mantid/Framework/CurveFitting/CMakeLists.txt
@@ -24,6 +24,7 @@ set ( SRC_FILES
 	src/CostFuncFitting.cpp
 	src/CostFuncLeastSquares.cpp
 	src/CostFuncRwp.cpp
+	src/CostFuncUnweightedLeastSquares.cpp
 	src/CubicSpline.cpp
 	src/DampingMinimizer.cpp
 	src/DeltaFunction.cpp
@@ -53,6 +54,8 @@ set ( SRC_FILES
 	src/GaussianComptonProfile.cpp
 	src/GramCharlierComptonProfile.cpp
 	src/IkedaCarpenterPV.cpp
+	src/LatticeDomainCreator.cpp
+	src/LatticeFunction.cpp
 	src/LeBailFit.cpp
 	src/LeBailFunction.cpp
 	src/LevenbergMarquardtMDMinimizer.cpp
@@ -135,6 +138,7 @@ set ( INC_FILES
 	inc/MantidCurveFitting/CostFuncFitting.h
 	inc/MantidCurveFitting/CostFuncLeastSquares.h
 	inc/MantidCurveFitting/CostFuncRwp.h
+	inc/MantidCurveFitting/CostFuncUnweightedLeastSquares.h
 	inc/MantidCurveFitting/CubicSpline.h
 	inc/MantidCurveFitting/DampingMinimizer.h
 	inc/MantidCurveFitting/DeltaFunction.h
@@ -144,7 +148,7 @@ set ( INC_FILES
 	inc/MantidCurveFitting/DllConfig.h
 	inc/MantidCurveFitting/DynamicKuboToyabe.h
 	inc/MantidCurveFitting/EndErfc.h
-    inc/MantidCurveFitting/EstimatePeakErrors.h
+	inc/MantidCurveFitting/EstimatePeakErrors.h
 	inc/MantidCurveFitting/ExpDecay.h
 	inc/MantidCurveFitting/ExpDecayMuon.h
 	inc/MantidCurveFitting/ExpDecayOsc.h
@@ -168,6 +172,8 @@ set ( INC_FILES
 	inc/MantidCurveFitting/GramCharlierComptonProfile.h
 	inc/MantidCurveFitting/IkedaCarpenterPV.h
 	inc/MantidCurveFitting/Jacobian.h
+	inc/MantidCurveFitting/LatticeDomainCreator.h
+	inc/MantidCurveFitting/LatticeFunction.h
 	inc/MantidCurveFitting/LeBailFit.h
 	inc/MantidCurveFitting/LeBailFunction.h
 	inc/MantidCurveFitting/LevenbergMarquardtMDMinimizer.h
@@ -244,6 +250,7 @@ set ( TEST_FILES
 	ConvertToYSpaceTest.h
 	ConvolutionTest.h
 	ConvolveWorkspacesTest.h
+	CostFuncUnweightedLeastSquaresTest.h
 	CubicSplineTest.h
 	DampingMinimizerTest.h
 	DeltaFunctionTest.h
@@ -251,7 +258,7 @@ set ( TEST_FILES
 	DiffSphereTest.h
 	DynamicKuboToyabeTest.h
 	EndErfcTest.h
-    EstimatePeakErrorsTest.h
+	EstimatePeakErrorsTest.h
 	ExpDecayMuonTest.h
 	ExpDecayOscTest.h
 	ExpDecayTest.h
@@ -274,6 +281,8 @@ set ( TEST_FILES
 	IPeakFunctionCentreParameterNameTest.h
 	IPeakFunctionIntensityTest.h
 	IkedaCarpenterPVTest.h
+	LatticeDomainCreatorTest.h
+	LatticeFunctionTest.h
 	LeBailFitTest.h
 	LeBailFunctionTest.h
 	LeastSquaresTest.h
diff --git a/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/CostFuncUnweightedLeastSquares.h b/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/CostFuncUnweightedLeastSquares.h
new file mode 100644
index 0000000000000000000000000000000000000000..17fc016bb426d6e2c37c534c89f796124d3bb7a5
--- /dev/null
+++ b/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/CostFuncUnweightedLeastSquares.h
@@ -0,0 +1,59 @@
+#ifndef MANTID_CURVEFITTING_COSTFUNCUNWEIGHTEDLEASTSQUARES_H_
+#define MANTID_CURVEFITTING_COSTFUNCUNWEIGHTEDLEASTSQUARES_H_
+
+#include "MantidKernel/System.h"
+#include "MantidCurveFitting/CostFuncLeastSquares.h"
+
+namespace Mantid {
+namespace CurveFitting {
+
+/** @class CostFuncUnweightedLeastSquares
+ *
+  In contrast to CostFuncLeastSquares, this variant of the cost function
+  assumes that there are no weights attached to the values, so all observations
+  will have unit weights.
+
+  The covariance matrix is multiplied with the variance of the residuals.
+
+    @author Michael Wedel, Paul Scherrer Institut - SINQ
+    @date 03/03/2015
+
+  Copyright © 2015 PSI-NXMM
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid 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 General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport CostFuncUnweightedLeastSquares : public CostFuncLeastSquares {
+public:
+  CostFuncUnweightedLeastSquares();
+  virtual ~CostFuncUnweightedLeastSquares() {}
+
+  std::string name() const { return "Unweighted least squares"; }
+  std::string shortName() const { return "Chi-sq-unw."; }
+
+protected:
+  void calActiveCovarianceMatrix(GSLMatrix &covar, double epsrel);
+  std::vector<double> getFitWeights(API::FunctionValues_sptr values) const;
+
+  double getResidualVariance() const;
+};
+
+} // namespace CurveFitting
+} // namespace Mantid
+
+#endif /* MANTID_CURVEFITTING_COSTFUNCUNWEIGHTEDLEASTSQUARES_H_ */
diff --git a/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/DynamicKuboToyabe.h b/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/DynamicKuboToyabe.h
index 34f8cb9fbfbb28848d52bd561a3dbdfc8ba6d775..4900feaac73b4c29040c41706a7e7c867b4fad5a 100644
--- a/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/DynamicKuboToyabe.h
+++ b/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/DynamicKuboToyabe.h
@@ -44,6 +44,9 @@ namespace Mantid
     {
     public:
 
+      /// Constructor
+      DynamicKuboToyabe();
+
       /// Destructor
       virtual ~DynamicKuboToyabe() {}
 
@@ -51,6 +54,21 @@ namespace Mantid
       std::string name()const{return "DynamicKuboToyabe";}
       virtual const std::string category() const { return "Muon";}
 
+      /// Returns the number of attributes associated with the function
+      size_t nAttributes() const { return 1; }
+
+      /// Returns a list of attribute names
+      std::vector<std::string> getAttributeNames() const;
+
+      /// Return a value of attribute attName
+      Attribute getAttribute(const std::string &attName) const;
+
+      /// Set a value to attribute attName
+      void setAttribute(const std::string &attName, const Attribute &);
+
+      /// Check if attribute attName exists
+      bool hasAttribute(const std::string &attName) const;
+
     protected:
       virtual void function1D(double* out, const double* xValues, const size_t nData)const;
       virtual void functionDeriv1D(API::Jacobian* out, const double* xValues, const size_t nData);
@@ -58,6 +76,14 @@ namespace Mantid
       virtual void init();
       virtual void setActiveParameter(size_t i, double value);
 
+    private:
+
+      // Evaluate DKT function for a given t, G, F, v and eps
+      double getDKT (double t, double G, double F, double v, double eps) const;
+
+      /// Bin width
+      double m_eps;
+      double m_minEps, m_maxEps;
     };
 
   } // namespace CurveFitting
diff --git a/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/LatticeDomainCreator.h b/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/LatticeDomainCreator.h
new file mode 100644
index 0000000000000000000000000000000000000000..290a8347fd0e6cd13fc79731ed575fc140879a71
--- /dev/null
+++ b/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/LatticeDomainCreator.h
@@ -0,0 +1,81 @@
+#ifndef MANTID_CURVEFITTING_LATTICEDOMAINCREATOR_H_
+#define MANTID_CURVEFITTING_LATTICEDOMAINCREATOR_H_
+
+#include "MantidKernel/System.h"
+#include "MantidAPI/IDomainCreator.h"
+#include "MantidAPI/Workspace.h"
+#include "MantidAPI/IPeaksWorkspace.h"
+
+namespace Mantid {
+namespace CurveFitting {
+
+/** LatticeDomainCreator
+
+  Domain creator for LatticeDomain, which processes IPeaksWorkspace or
+  an ITableWorkspace with certain columns (HKL, d).
+
+    @author Michael Wedel, Paul Scherrer Institut - SINQ
+    @date 15/04/2015
+
+  Copyright © 2015 PSI-NXMM
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid 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 General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport LatticeDomainCreator : public API::IDomainCreator {
+public:
+  LatticeDomainCreator(Kernel::IPropertyManager *manager,
+                       const std::string &workspacePropertyName,
+                       DomainType domainType = Simple);
+
+  virtual ~LatticeDomainCreator() {}
+
+  virtual void createDomain(boost::shared_ptr<API::FunctionDomain> &domain,
+                            boost::shared_ptr<API::FunctionValues> &values,
+                            size_t i0);
+
+  virtual API::Workspace_sptr createOutputWorkspace(
+          const std::string &baseName,
+          API::IFunction_sptr function,
+          boost::shared_ptr<API::FunctionDomain> domain,
+          boost::shared_ptr<API::FunctionValues> values,
+          const std::string &outputWorkspacePropertyName);
+
+  virtual size_t getDomainSize() const;
+
+protected:
+  void setWorkspaceFromPropertyManager();
+  void
+  createDomainFromPeaksWorkspace(const API::IPeaksWorkspace_sptr &workspace,
+                                 boost::shared_ptr<API::FunctionDomain> &domain,
+                                 boost::shared_ptr<API::FunctionValues> &values,
+                                 size_t i0);
+
+  void createDomainFromPeakTable(const API::ITableWorkspace_sptr &workspace,
+                                 boost::shared_ptr<API::FunctionDomain> &domain,
+                                 boost::shared_ptr<API::FunctionValues> &values,
+                                 size_t i0);
+
+  std::string m_workspacePropertyName;
+  API::Workspace_sptr m_workspace;
+};
+
+} // namespace CurveFitting
+} // namespace Mantid
+
+#endif /* MANTID_CURVEFITTING_LATTICEDOMAINCREATOR_H_ */
diff --git a/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/LatticeFunction.h b/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/LatticeFunction.h
new file mode 100644
index 0000000000000000000000000000000000000000..dda2fcf1d8358f0e60023c855a4eb5080a758447
--- /dev/null
+++ b/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/LatticeFunction.h
@@ -0,0 +1,72 @@
+#ifndef MANTID_CURVEFITTING_LATTICEFUNCTION_H_
+#define MANTID_CURVEFITTING_LATTICEFUNCTION_H_
+
+#include "MantidKernel/System.h"
+#include "MantidAPI/ILatticeFunction.h"
+
+#include "MantidCurveFitting/PawleyFunction.h"
+
+namespace Mantid {
+namespace CurveFitting {
+
+/** LatticeFunction
+
+  LatticeFunction implements API::ILatticeFunction. Internally it uses
+  a PawleyParameterFunction to expose appropriate lattice parameters for each
+  crystal system.
+
+  For each HKL in the supplied LatticeDomain, the function method calculates
+  the d-value using the UnitCell that is generated from the function parameters.
+
+    @author Michael Wedel, Paul Scherrer Institut - SINQ
+    @date 15/04/2015
+
+  Copyright © 2015 PSI-NXMM
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid 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 General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport LatticeFunction : public API::ILatticeFunction {
+public:
+  LatticeFunction();
+  virtual ~LatticeFunction() {}
+
+  std::string name() const { return "LatticeFunction"; }
+
+  void functionLattice(const API::LatticeDomain &latticeDomain,
+                       API::FunctionValues &values) const;
+
+  void setCrystalSystem(const std::string &crystalSystem);
+  void setUnitCell(const std::string &unitCellString);
+  void setUnitCell(const Geometry::UnitCell &unitCell);
+  Geometry::UnitCell getUnitCell() const;
+
+protected:
+  void init();
+  void beforeDecoratedFunctionSet(const API::IFunction_sptr &fn);
+
+private:
+  PawleyParameterFunction_sptr m_cellParameters;
+};
+
+typedef boost::shared_ptr<LatticeFunction> LatticeFunction_sptr;
+
+} // namespace CurveFitting
+} // namespace Mantid
+
+#endif /* MANTID_CURVEFITTING_LATTICEFUNCTION_H_ */
diff --git a/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/PawleyFit.h b/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/PawleyFit.h
index 4c00d9b1c35c99de7bb46b96796ea4400fc13f58..455df893d86d5afafc4a473e538a13125d3b0cff 100644
--- a/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/PawleyFit.h
+++ b/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/PawleyFit.h
@@ -9,7 +9,27 @@
 namespace Mantid {
 namespace CurveFitting {
 
-/** PawleyFit
+/** @class V3DFromHKLColumnExtractor
+
+  Small helper class to extract HKLs as V3D from table columns. The table
+  column can either store V3D directly, or a string with various separators:
+    , ; [ ] (space)
+
+*/
+struct DLLExport V3DFromHKLColumnExtractor {
+  Kernel::V3D operator()(const API::Column_const_sptr &hklColumn,
+                         size_t i) const;
+
+protected:
+  Kernel::V3D getHKLFromV3DColumn(const API::Column_const_sptr &hklColumn,
+                                  size_t i) const;
+  Kernel::V3D getHKLFromStringColumn(const API::Column_const_sptr &hklColumn,
+                                     size_t i) const;
+
+  Kernel::V3D getHKLFromString(const std::string &hklString) const;
+};
+
+/** @class PawleyFit
 
   This algorithm uses the Pawley-method to refine lattice parameters using a
   powder diffractogram and a list of unique Miller indices. From the initial
@@ -59,10 +79,6 @@ protected:
                          const Kernel::Unit_sptr &unit, double startX,
                          double endX) const;
 
-  Kernel::V3D getHKLFromColumn(size_t i,
-                               const API::Column_const_sptr &hklColumn) const;
-  Kernel::V3D getHkl(const std::string &hklString) const;
-
   API::ITableWorkspace_sptr
   getLatticeFromFunction(const PawleyFunction_sptr &pawleyFn) const;
   API::ITableWorkspace_sptr
diff --git a/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/PawleyFunction.h b/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/PawleyFunction.h
index a015b74a52fc59377592ae5cae5a15b5f3edd5c9..bd042c8a4cbd02c7da0ce01cc5eeb58b22022ecc 100644
--- a/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/PawleyFunction.h
+++ b/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/PawleyFunction.h
@@ -62,6 +62,10 @@ protected:
 
   void createCrystalSystemParameters(
       Geometry::PointGroup::CrystalSystem crystalSystem);
+
+  void addLengthConstraint(const std::string &parameterName);
+  void addAngleConstraint(const std::string &parameterName);
+
   void setCenterParameterNameFromFunction(
       const API::IPeakFunction_sptr &profileFunction);
 
diff --git a/Code/Mantid/Framework/CurveFitting/src/CostFuncUnweightedLeastSquares.cpp b/Code/Mantid/Framework/CurveFitting/src/CostFuncUnweightedLeastSquares.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..bf6bd0770dca89b13150ce6021ffd74d1af7923c
--- /dev/null
+++ b/Code/Mantid/Framework/CurveFitting/src/CostFuncUnweightedLeastSquares.cpp
@@ -0,0 +1,85 @@
+#include "MantidCurveFitting/CostFuncUnweightedLeastSquares.h"
+
+#include "MantidKernel/Logger.h"
+#include <iomanip>
+#include <cmath>
+
+namespace Mantid {
+namespace CurveFitting {
+
+namespace {
+/// static logger
+Kernel::Logger g_log("CostFuncUnweightedLeastSquares");
+}
+
+DECLARE_COSTFUNCTION(CostFuncUnweightedLeastSquares, Unweighted least squares)
+
+CostFuncUnweightedLeastSquares::CostFuncUnweightedLeastSquares()
+    : CostFuncLeastSquares() {}
+
+void CostFuncUnweightedLeastSquares::calActiveCovarianceMatrix(GSLMatrix &covar,
+                                                               double epsrel) {
+  CostFuncLeastSquares::calActiveCovarianceMatrix(covar, epsrel);
+
+  double variance = getResidualVariance();
+  covar *= variance;
+
+  if (g_log.is(Kernel::Logger::Priority::PRIO_INFORMATION)) {
+    g_log.information() << "== Final covariance matrix (H^-1) ==" << std::endl;
+
+    std::ios::fmtflags prevState = g_log.information().flags();
+    g_log.information() << std::left << std::fixed;
+
+    for (size_t i = 0; i < covar.size1(); ++i) {
+      for (size_t j = 0; j < covar.size2(); ++j) {
+        g_log.information() << std::setw(10);
+        g_log.information() << covar.get(i, j) << "  ";
+      }
+      g_log.information() << std::endl;
+    }
+    g_log.information().flags(prevState);
+  }
+}
+
+/// Return unit weights for all data points.
+std::vector<double> CostFuncUnweightedLeastSquares::getFitWeights(
+    API::FunctionValues_sptr values) const {
+  return std::vector<double>(values->size(), 1.0);
+}
+
+/// Calculates the residual variance from the internally stored FunctionValues.
+double CostFuncUnweightedLeastSquares::getResidualVariance() const {
+  if (!m_values || m_values->size() == 0) {
+    return 0;
+  }
+
+  double sum = 0.0;
+  for (size_t i = 0; i < m_values->size(); ++i) {
+    double difference = m_values->getCalculated(i) - m_values->getFitData(i);
+    sum += difference * difference;
+  }
+
+  double degreesOfFreedom = static_cast<double>(m_values->size() - nParams());
+  double residualVariance = sum / degreesOfFreedom;
+
+  if (g_log.is(Kernel::Logger::Priority::PRIO_INFORMATION)) {
+    g_log.information() << "== Statistics of residuals ==" << std::endl;
+    std::ios::fmtflags prevState = g_log.information().flags();
+    g_log.information() << std::left << std::fixed << std::setw(10);
+    g_log.information() << "Residual sum of squares: " << sum << std::endl;
+    g_log.information() << "Residual variance: " << residualVariance
+                        << std::endl;
+    g_log.information() << "Residual standard deviation: "
+                        << sqrt(residualVariance) << std::endl;
+    g_log.information() << "Degrees of freedom: "
+                        << static_cast<size_t>(degreesOfFreedom) << std::endl;
+    g_log.information() << "Number of observations: " << m_values->size()
+                        << std::endl;
+    g_log.information().flags(prevState);
+  }
+
+  return residualVariance;
+}
+
+} // namespace CurveFitting
+} // namespace Mantid
diff --git a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp
index 7fa8c64fa07016e933dcf6a7a3bb330bdfae7e7a..0197335b1bcbf86ceae075e38d040e5f0fae4299 100644
--- a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp
+++ b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp
@@ -175,18 +175,18 @@ double HKT (const double x, const double G, const double F) {
 }
 
 // Dynamic Kubo-Toyabe
-double getDKT (double t, double G, double F, double v){
+double DynamicKuboToyabe::getDKT (double t, double G, double F, double v, double eps) const {
 
-  const int tsmax = 656; // Length of the time axis, 32 us of valid data
-  const double eps = 0.05; // Bin width for calculations
+  const int tsmax = static_cast<int>(std::ceil(32.768/eps));
 
-  static double oldG=-1., oldV=-1., oldF=-1.;
-  static std::vector<double> gStat(tsmax), gDyn(tsmax);
+  static double oldG=-1., oldV=-1., oldF=-1., oldEps=-1.;
 
+  const int maxTsmax = static_cast<int>(std::ceil(32.768/m_minEps));
+  static std::vector<double> gStat(maxTsmax), gDyn(maxTsmax);
 
-  if ( (G != oldG) || (v != oldV) || (F != oldF) ){
+  if ( (G != oldG) || (v != oldV) || (F != oldF) || (eps != oldEps)){
 
-    // If G or v or F have changed with respect to the 
+    // If G or v or F or eps have changed with respect to the
     // previous call, we need to re-do the computations
 
 
@@ -213,6 +213,8 @@ double getDKT (double t, double G, double F, double v){
 
     // Store new v value
     oldV =v;
+    // Store new eps value
+    oldEps =eps;
 
     double hop = v*eps;
 
@@ -266,7 +268,7 @@ void DynamicKuboToyabe::function1D(double* out, const double* xValues, const siz
   else {
 
     for (size_t i = 0; i<nData; i++){
-      out[i] = A*getDKT(xValues[i],G,F,v);
+      out[i] = A*getDKT(xValues[i],G,F,v,m_eps);
     }
   }
 
@@ -274,22 +276,107 @@ void DynamicKuboToyabe::function1D(double* out, const double* xValues, const siz
 }
 
 
+//----------------------------------------------------------------------------------------------
+/** Constructor
+ */
+DynamicKuboToyabe::DynamicKuboToyabe() : m_eps(0.05), m_minEps(0.001), m_maxEps(0.1) {}
 
+//----------------------------------------------------------------------------------------------
+/** Function to calculate derivative numerically
+ */
 void DynamicKuboToyabe::functionDeriv(const API::FunctionDomain& domain, API::Jacobian& jacobian)
 {
   calNumericalDeriv(domain, jacobian);
 }
 
+//----------------------------------------------------------------------------------------------
+/** Function to calculate derivative analytically
+ */
 void DynamicKuboToyabe::functionDeriv1D(API::Jacobian* , const double* , const size_t )
 {
-  throw Mantid::Kernel::Exception::NotImplementedError("functionDerivLocal is not implemented for DynamicKuboToyabe.");
+  throw Mantid::Kernel::Exception::NotImplementedError("functionDeriv1D is not implemented for DynamicKuboToyabe.");
 }
 
+//----------------------------------------------------------------------------------------------
+/** Set new value of the i-th parameter
+ * @param i :: parameter index
+ * @param value :: new value
+ */
 void DynamicKuboToyabe::setActiveParameter(size_t i, double value) {
 
   setParameter( i, fabs(value), false);
 
 }
 
+//----------------------------------------------------------------------------------------------
+/** Get Attribute names
+ * @return A list of attribute names
+ */
+std::vector<std::string> DynamicKuboToyabe::getAttributeNames() const {
+  std::vector<std::string> res;
+  res.push_back("BinWidth");
+  return res;
+}
+
+//----------------------------------------------------------------------------------------------
+/** Get Attribute
+ * @param attName :: Attribute name. If it is not "eps" an exception is thrown.
+ * @return a value of attribute attName
+ */
+API::IFunction::Attribute DynamicKuboToyabe::getAttribute(const std::string &attName) const {
+
+  if (attName == "BinWidth") {
+    return Attribute(m_eps);
+  }
+  throw std::invalid_argument("DynamicKuboToyabe: Unknown attribute " + attName);
+}
+
+//----------------------------------------------------------------------------------------------
+/** Set Attribute
+ * @param attName :: The attribute name. If it is not "eps" exception is thrown.
+ * @param att :: A double attribute containing a new positive value.
+ */
+void DynamicKuboToyabe::setAttribute(const std::string &attName,
+                              const API::IFunction::Attribute &att) {
+  if (attName == "BinWidth") {
+
+    double newVal = att.asDouble();
+
+    if (newVal < 0) {
+      clearAllParameters();
+      throw std::invalid_argument("DKT: Attribute BinWidth cannot be negative.");
+
+    } else if (newVal < m_minEps) {
+      clearAllParameters();
+      std::stringstream ss;
+      ss << "DKT: Attribute BinWidth too small (BinWidth < " << std::setprecision(3) << m_minEps << ")";
+      throw std::invalid_argument(ss.str());
+
+    } else if (newVal > m_maxEps) {
+      clearAllParameters();
+      std::stringstream ss;
+      ss << "DKT: Attribute BinWidth too large (BinWidth > " << std::setprecision(3) << m_maxEps << ")";
+      throw std::invalid_argument(ss.str());
+    }
+
+    if ( !nParams() ) {
+      init();
+    }
+    m_eps = newVal;
+
+  } else {
+    throw std::invalid_argument("DynamicKuboToyabe: Unknown attribute " + attName);
+  }
+}
+
+//----------------------------------------------------------------------------------------------
+/** Check if attribute attName exists
+ * @param attName :: The attribute name.
+ */
+bool DynamicKuboToyabe::hasAttribute(const std::string &attName) const {
+  return attName == "BinWidth";
+}
+
+
 } // namespace CurveFitting
 } // namespace Mantid
diff --git a/Code/Mantid/Framework/CurveFitting/src/FABADAMinimizer.cpp b/Code/Mantid/Framework/CurveFitting/src/FABADAMinimizer.cpp
index 4fb27b06173e78b5e22ab8ee59ff7e9996818884..a823c4d21f8c31e38ebbce9cedfe268ebaed7518 100644
--- a/Code/Mantid/Framework/CurveFitting/src/FABADAMinimizer.cpp
+++ b/Code/Mantid/Framework/CurveFitting/src/FABADAMinimizer.cpp
@@ -64,19 +64,19 @@ FABADAMinimizer::FABADAMinimizer() {
   declareProperty(
       new API::WorkspaceProperty<>("PDF", "PDF", Kernel::Direction::Output),
       "The name to give the output workspace");
-  declareProperty(new API::WorkspaceProperty<>("Chains", "Chain",
+  declareProperty(new API::WorkspaceProperty<>("Chains", "",
                                                Kernel::Direction::Output),
                   "The name to give the output workspace");
   declareProperty(new API::WorkspaceProperty<>(
-                      "ConvergedChain", "ConvergedChain",
+                      "ConvergedChain", "",
                       Kernel::Direction::Output, API::PropertyMode::Optional),
                   "The name to give the output workspace");
   declareProperty(
       new API::WorkspaceProperty<API::ITableWorkspace>(
-          "CostFunctionTable", "CostFunction", Kernel::Direction::Output),
+          "CostFunctionTable", "", Kernel::Direction::Output),
       "The name to give the output workspace");
   declareProperty(new API::WorkspaceProperty<API::ITableWorkspace>(
-                      "Parameters", "Parameters", Kernel::Direction::Output),
+                      "Parameters", "", Kernel::Direction::Output),
                   "The name to give the output workspace");
 }
 
@@ -320,7 +320,7 @@ bool FABADAMinimizer::iterate(size_t) {
   } // for i
 
   // Update the counter, after finishing the iteration for each parameter
-  m_counter += 1; 
+  m_counter += 1;
 
   // Check if Chi square has converged for all the parameters.
   if (m_counter > lowerIterationLimit && !m_converged) {
diff --git a/Code/Mantid/Framework/CurveFitting/src/FRConjugateGradientMinimizer.cpp b/Code/Mantid/Framework/CurveFitting/src/FRConjugateGradientMinimizer.cpp
index 0c0b233fea713f00cbf840c06ad9154e26719efa..a06a974c52ff6db48b0532bf76cab1c32bb2fd2e 100644
--- a/Code/Mantid/Framework/CurveFitting/src/FRConjugateGradientMinimizer.cpp
+++ b/Code/Mantid/Framework/CurveFitting/src/FRConjugateGradientMinimizer.cpp
@@ -15,10 +15,11 @@ namespace {
 Kernel::Logger g_log("FRConjugateGradientMinimizer");
 }
 
+// clang-format off
 ///@cond nodoc
-DECLARE_FUNCMINIMIZER(FRConjugateGradientMinimizer,
-                      Conjugate gradient(Fletcher - Reeves imp.))
+DECLARE_FUNCMINIMIZER(FRConjugateGradientMinimizer,Conjugate gradient (Fletcher-Reeves imp.))
 ///@endcond
+// clang-format on
 
 /// Return a concrete type to initialize m_gslSolver
 /// gsl_multimin_fdfminimizer_vector_bfgs2
diff --git a/Code/Mantid/Framework/CurveFitting/src/Fit.cpp b/Code/Mantid/Framework/CurveFitting/src/Fit.cpp
index 691c124409b3ae99a5e9cba7499b0da0d525bcd7..0ec88050d9ac3cd29d04d9fdd211aa94e46dcf44 100644
--- a/Code/Mantid/Framework/CurveFitting/src/Fit.cpp
+++ b/Code/Mantid/Framework/CurveFitting/src/Fit.cpp
@@ -8,6 +8,7 @@
 #include "MantidCurveFitting/MultiDomainCreator.h"
 #include "MantidCurveFitting/Convolution.h"
 #include "MantidCurveFitting/SeqDomainSpectrumCreator.h"
+#include "MantidCurveFitting/LatticeDomainCreator.h"
 
 #include "MantidAPI/FuncMinimizerFactory.h"
 #include "MantidAPI/IFuncMinimizer.h"
@@ -22,6 +23,7 @@
 #include "MantidAPI/IFunctionMW.h"
 #include "MantidAPI/IFunctionMD.h"
 #include "MantidAPI/IFunction1DSpectrum.h"
+#include "MantidAPI/ILatticeFunction.h"
 #include "MantidAPI/MultiDomainFunction.h"
 #include "MantidAPI/ITableWorkspace.h"
 
@@ -156,23 +158,29 @@ void Fit::addWorkspace(const std::string &workspacePropertyName,
   IDomainCreator *creator = NULL;
   setDomainType();
 
-  if (boost::dynamic_pointer_cast<const API::MatrixWorkspace>(ws) &&
-      !boost::dynamic_pointer_cast<API::IFunctionMD>(fun)) {
-    /* IFunction1DSpectrum needs a different domain creator. If a function
-     * implements that type, we need to react appropriately at this point.
-     * Otherwise, the default creator FitMW is used.
-     */
-    if (boost::dynamic_pointer_cast<API::IFunction1DSpectrum>(fun)) {
-      creator = new SeqDomainSpectrumCreator(this, workspacePropertyName);
-    } else {
-      creator = new FitMW(this, workspacePropertyName, m_domainType);
-    }
+  // ILatticeFunction requires API::LatticeDomain.
+  if (boost::dynamic_pointer_cast<API::ILatticeFunction>(fun)) {
+    creator = new LatticeDomainCreator(this, workspacePropertyName);
   } else {
-    try {
-      creator = API::DomainCreatorFactory::Instance().createDomainCreator(
-          "FitMD", this, workspacePropertyName, m_domainType);
-    } catch (Kernel::Exception::NotFoundError &) {
-      throw std::invalid_argument("Unsupported workspace type" + ws->id());
+    if (boost::dynamic_pointer_cast<const API::MatrixWorkspace>(ws) &&
+        !boost::dynamic_pointer_cast<API::IFunctionMD>(fun)) {
+      /* IFunction1DSpectrum needs a different domain creator. If a function
+       * implements that type, we need to react appropriately at this point.
+       * Otherwise, the default creator FitMW is used.
+       */
+      if (boost::dynamic_pointer_cast<API::IFunction1DSpectrum>(fun)) {
+        creator = new SeqDomainSpectrumCreator(this, workspacePropertyName);
+      } else {
+        creator = new FitMW(this, workspacePropertyName, m_domainType);
+      }
+    } else {
+      try {
+        creator = API::DomainCreatorFactory::Instance().createDomainCreator(
+            "FitMD", this, workspacePropertyName, m_domainType);
+      }
+      catch (Kernel::Exception::NotFoundError &) {
+        throw std::invalid_argument("Unsupported workspace type" + ws->id());
+      }
     }
   }
 
@@ -227,25 +235,35 @@ void Fit::addWorkspaces() {
       const std::string workspacePropertyName = (**prop).name();
       API::Workspace_const_sptr ws = getProperty(workspacePropertyName);
       IDomainCreator *creator = NULL;
-      if (boost::dynamic_pointer_cast<const API::MatrixWorkspace>(ws) &&
-          !boost::dynamic_pointer_cast<API::IFunctionMD>(m_function)) {
-        /* IFunction1DSpectrum needs a different domain creator. If a function
-         * implements that type, we need to react appropriately at this point.
-         * Otherwise, the default creator FitMW is used.
-         */
-        if (boost::dynamic_pointer_cast<API::IFunction1DSpectrum>(m_function)) {
-          creator = new SeqDomainSpectrumCreator(this, workspacePropertyName);
-        } else {
-          creator = new FitMW(this, workspacePropertyName, m_domainType);
-        }
-      } else { // don't know what to do with this workspace
-        try {
-          creator = API::DomainCreatorFactory::Instance().createDomainCreator(
-              "FitMD", this, workspacePropertyName, m_domainType);
-        } catch (Kernel::Exception::NotFoundError &) {
-          throw std::invalid_argument("Unsupported workspace type" + ws->id());
+
+      // ILatticeFunction requires API::LatticeDomain.
+      if (boost::dynamic_pointer_cast<API::ILatticeFunction>(m_function)) {
+        creator = new LatticeDomainCreator(this, workspacePropertyName);
+      } else {
+        if (boost::dynamic_pointer_cast<const API::MatrixWorkspace>(ws) &&
+            !boost::dynamic_pointer_cast<API::IFunctionMD>(m_function)) {
+          /* IFunction1DSpectrum needs a different domain creator. If a function
+           * implements that type, we need to react appropriately at this point.
+           * Otherwise, the default creator FitMW is used.
+           */
+          if (boost::dynamic_pointer_cast<API::IFunction1DSpectrum>(
+                  m_function)) {
+            creator = new SeqDomainSpectrumCreator(this, workspacePropertyName);
+          } else {
+            creator = new FitMW(this, workspacePropertyName, m_domainType);
+          }
+        } else { // don't know what to do with this workspace
+          try {
+            creator = API::DomainCreatorFactory::Instance().createDomainCreator(
+                "FitMD", this, workspacePropertyName, m_domainType);
+          }
+          catch (Kernel::Exception::NotFoundError &) {
+            throw std::invalid_argument("Unsupported workspace type" +
+                                        ws->id());
+          }
         }
       }
+
       const size_t n = std::string("InputWorkspace").size();
       const std::string suffix = (workspacePropertyName.size() > n)
                                      ? workspacePropertyName.substr(n)
@@ -294,7 +312,7 @@ void Fit::init() {
                          "the fitting function.");
   declareProperty("Constraints", "", Kernel::Direction::Input);
   getPointerToProperty("Constraints")->setDocumentation("List of constraints");
-  auto mustBePositive = boost::shared_ptr<Kernel::BoundedValidator<int>>(
+  auto mustBePositive = boost::shared_ptr<Kernel::BoundedValidator<int> >(
       new Kernel::BoundedValidator<int>());
   mustBePositive->setLower(0);
   declareProperty(
diff --git a/Code/Mantid/Framework/CurveFitting/src/LatticeDomainCreator.cpp b/Code/Mantid/Framework/CurveFitting/src/LatticeDomainCreator.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..e8a6895f00b48773059704c6253d8e8bb899ef49
--- /dev/null
+++ b/Code/Mantid/Framework/CurveFitting/src/LatticeDomainCreator.cpp
@@ -0,0 +1,286 @@
+#include "MantidCurveFitting/LatticeDomainCreator.h"
+
+#include "MantidAPI/ILatticeFunction.h"
+#include "MantidAPI/IPeak.h"
+#include "MantidAPI/LatticeDomain.h"
+#include "MantidAPI/TableRow.h"
+#include "MantidAPI/WorkspaceFactory.h"
+
+#include "MantidDataObjects/Peak.h"
+#include "MantidCurveFitting/PawleyFit.h"
+
+namespace Mantid {
+namespace CurveFitting {
+
+using namespace API;
+using namespace Kernel;
+using namespace DataObjects;
+
+/// Constructor
+LatticeDomainCreator::LatticeDomainCreator(
+    Kernel::IPropertyManager *manager, const std::string &workspacePropertyName,
+    API::IDomainCreator::DomainType domainType)
+    : IDomainCreator(manager,
+                     std::vector<std::string>(1, workspacePropertyName),
+                     domainType),
+      m_workspace() {
+  m_workspacePropertyName = m_workspacePropertyNames.front();
+}
+
+/**
+ * Creates a LatticeDomain from the assigned Workspace
+ *
+ * This function uses the internally stored workspace which can either be an
+ * IPeaksWorkspace or a TableWorkspace with HKL and d-values to create a
+ * LatticeDomain. It also assigns fit data to the supplied value object. If
+ * null-pointers are passed, new objects are allocated.
+ *
+ * Reflections where HKL is (000) are ignored, so the final domain size may
+ * be smaller than the number of rows in the input workspace.
+ *
+ * @param domain :: Pointer to outgoing FunctionDomain instance.
+ * @param values :: Pointer to outgoing FunctionValues object.
+ * @param i0 :: Size offset for values object if it already contains data.
+ */
+void LatticeDomainCreator::createDomain(
+    boost::shared_ptr<API::FunctionDomain> &domain,
+    boost::shared_ptr<API::FunctionValues> &values, size_t i0) {
+  setWorkspaceFromPropertyManager();
+
+  API::IPeaksWorkspace_sptr peaksWorkspace =
+      boost::dynamic_pointer_cast<IPeaksWorkspace>(m_workspace);
+  if (peaksWorkspace) {
+    createDomainFromPeaksWorkspace(peaksWorkspace, domain, values, i0);
+  } else {
+    API::ITableWorkspace_sptr tableWorkspace =
+        boost::dynamic_pointer_cast<ITableWorkspace>(m_workspace);
+    if (tableWorkspace) {
+      createDomainFromPeakTable(tableWorkspace, domain, values, i0);
+    }
+  }
+}
+
+/**
+ * Creates an output workspace from calculated and observed values
+ *
+ * This method creates a table workspace for an ILatticeFunction, containing
+ * observed and calculated d-values for each HKL, as well as the difference
+ * between those two values.
+ *
+ * @param baseName :: Basename for output workspace.
+ * @param function :: An ILatticeFunction
+ * @param domain :: Pointer to LatticeDomain instance.
+ * @param values :: Pointer to FunctionValues instance.
+ * @param outputWorkspacePropertyName :: Name of output workspace property.
+ * @return TableWorkspace with calculated and observed d-values.
+ */
+Workspace_sptr LatticeDomainCreator::createOutputWorkspace(
+    const std::string &baseName, IFunction_sptr function,
+    boost::shared_ptr<FunctionDomain> domain,
+    boost::shared_ptr<FunctionValues> values,
+    const std::string &outputWorkspacePropertyName) {
+
+  boost::shared_ptr<LatticeDomain> latticeDomain =
+      boost::dynamic_pointer_cast<LatticeDomain>(domain);
+  if (!latticeDomain) {
+    throw std::invalid_argument("LatticeDomain is required.");
+  }
+
+  ILatticeFunction_sptr latticeFunction =
+      boost::dynamic_pointer_cast<ILatticeFunction>(function);
+  if (!latticeFunction) {
+    throw std::invalid_argument(
+        "LatticeDomainCreator can only process ILatticeFunction.");
+  }
+
+  // Calculate function values again.
+  latticeFunction->functionLattice(*latticeDomain, *values);
+
+  ITableWorkspace_sptr tableWorkspace =
+      WorkspaceFactory::Instance().createTable();
+
+  if (tableWorkspace) {
+    tableWorkspace->addColumn("V3D", "HKL");
+    tableWorkspace->addColumn("double", "d(obs)");
+    tableWorkspace->addColumn("double", "d(calc)");
+    tableWorkspace->addColumn("double", "d(obs) - d(calc)");
+
+    for (size_t i = 0; i < values->size(); ++i) {
+      double dObs = values->getFitData(i);
+      double dCalc = values->getCalculated(i);
+
+      TableRow newRow = tableWorkspace->appendRow();
+      newRow << (*latticeDomain)[i] << dObs << dCalc << dObs - dCalc;
+    }
+  }
+
+  if (m_manager && !outputWorkspacePropertyName.empty()) {
+    declareProperty(
+        new WorkspaceProperty<ITableWorkspace>(outputWorkspacePropertyName, "",
+                                               Kernel::Direction::Output),
+        "Result workspace");
+
+    m_manager->setPropertyValue(outputWorkspacePropertyName,
+                                baseName + "Workspace");
+    m_manager->setProperty(outputWorkspacePropertyName, tableWorkspace);
+  }
+
+  return tableWorkspace;
+}
+
+size_t LatticeDomainCreator::getDomainSize() const {
+  API::IPeaksWorkspace_sptr peaksWorkspace =
+      boost::dynamic_pointer_cast<IPeaksWorkspace>(m_workspace);
+  if (peaksWorkspace) {
+    return peaksWorkspace->getNumberPeaks();
+  }
+
+  API::ITableWorkspace_sptr tableWorkspace =
+      boost::dynamic_pointer_cast<ITableWorkspace>(m_workspace);
+  if (tableWorkspace) {
+    return tableWorkspace->rowCount();
+  }
+
+  return 0;
+}
+
+/// Get the workspace with peak data from the property manager.
+void LatticeDomainCreator::setWorkspaceFromPropertyManager() {
+  if (!m_manager) {
+    throw std::invalid_argument(
+        "PropertyManager not set in LatticeDomainCreator.");
+  }
+
+  try {
+    m_workspace = m_manager->getProperty(m_workspacePropertyName);
+  }
+  catch (Kernel::Exception::NotFoundError) {
+    throw std::invalid_argument(
+        "Could not extract workspace from PropertyManager.");
+  }
+}
+
+/// Creates a LatticeDomain from an IPeaksWorkspace, using HKL and d-values.
+void LatticeDomainCreator::createDomainFromPeaksWorkspace(
+    const API::IPeaksWorkspace_sptr &workspace,
+    boost::shared_ptr<API::FunctionDomain> &domain,
+    boost::shared_ptr<API::FunctionValues> &values, size_t i0) {
+  if (!workspace) {
+    throw std::invalid_argument(
+        "This function only works on an IPeaksWorkspace-object.");
+  }
+
+  size_t peakCount = workspace->getNumberPeaks();
+
+  if (peakCount < 1) {
+    throw std::range_error("Cannot create a domain for 0 peaks.");
+  }
+
+  std::vector<V3D> hkls;
+  hkls.reserve(peakCount);
+
+  std::vector<double> dSpacings;
+  dSpacings.reserve(peakCount);
+
+  for (size_t i = 0; i < peakCount; ++i) {
+    IPeak *currentPeak = workspace->getPeakPtr(static_cast<int>(i));
+    V3D hkl = currentPeak->getHKL();
+
+    if (hkl != V3D(0, 0, 0)) {
+      hkls.push_back(hkl);
+      dSpacings.push_back(currentPeak->getDSpacing());
+    }
+  }
+
+  LatticeDomain *latticeDomain = new LatticeDomain(hkls);
+  domain.reset(latticeDomain);
+
+  if (!values) {
+    FunctionValues *functionValues = new FunctionValues(*domain);
+    values.reset(functionValues);
+  } else {
+    values->expand(i0 + latticeDomain->size());
+  }
+
+  values->setFitData(dSpacings);
+
+  // Set unit weights.
+  values->setFitWeights(1.0);
+}
+
+/**
+ * Creates a domain from an ITableWorkspace
+ *
+ * This method creates a LatticeDomain from a table workspace that contains two
+ * columns, HKL and d. HKL can either be a V3D-column or a string column,
+ * containing three integers separated by space, comma, semi-colon and
+ * optionally surrounded by []. The d-column can be double or a string that can
+ * be parsed as a double number.
+ *
+ * @param workspace :: ITableWorkspace with format specified above.
+ * @param domain :: Pointer to outgoing FunctionDomain instance.
+ * @param values :: Pointer to outgoing FunctionValues object.
+ * @param i0 :: Size offset for values object if it already contains data.
+ */
+void LatticeDomainCreator::createDomainFromPeakTable(
+    const ITableWorkspace_sptr &workspace,
+    boost::shared_ptr<FunctionDomain> &domain,
+    boost::shared_ptr<FunctionValues> &values, size_t i0) {
+
+  size_t peakCount = workspace->rowCount();
+
+  if (peakCount < 1) {
+    throw std::range_error("Cannot create a domain for 0 peaks.");
+  }
+
+  try {
+    Column_const_sptr hklColumn = workspace->getColumn("HKL");
+    Column_const_sptr dColumn = workspace->getColumn("d");
+
+    std::vector<V3D> hkls;
+    hkls.reserve(peakCount);
+
+    std::vector<double> dSpacings;
+    dSpacings.reserve(peakCount);
+
+    V3DFromHKLColumnExtractor extractor;
+
+    for (size_t i = 0; i < peakCount; ++i) {
+      try {
+        V3D hkl = extractor(hklColumn, i);
+
+        if (hkl != V3D(0, 0, 0)) {
+          hkls.push_back(hkl);
+
+          double d = (*dColumn)[i];
+          dSpacings.push_back(d);
+        }
+      }
+      catch (std::bad_alloc) {
+        // do nothing.
+      }
+    }
+
+    LatticeDomain *latticeDomain = new LatticeDomain(hkls);
+    domain.reset(latticeDomain);
+
+    if (!values) {
+      FunctionValues *functionValues = new FunctionValues(*domain);
+      values.reset(functionValues);
+    } else {
+      values->expand(i0 + latticeDomain->size());
+    }
+
+    values->setFitData(dSpacings);
+
+    values->setFitWeights(1.0);
+  }
+  catch (std::runtime_error) {
+    // Column does not exist
+    throw std::runtime_error("Can not process table, the following columns are "
+                             "required: HKL, d.");
+  }
+}
+
+} // namespace CurveFitting
+} // namespace Mantid
diff --git a/Code/Mantid/Framework/CurveFitting/src/LatticeFunction.cpp b/Code/Mantid/Framework/CurveFitting/src/LatticeFunction.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..895327b1d97f18dcb4252531b56b780828c0a84b
--- /dev/null
+++ b/Code/Mantid/Framework/CurveFitting/src/LatticeFunction.cpp
@@ -0,0 +1,77 @@
+#include "MantidCurveFitting/LatticeFunction.h"
+#include "MantidAPI/FunctionFactory.h"
+#include "MantidGeometry/Crystal/UnitCell.h"
+
+namespace Mantid {
+namespace CurveFitting {
+
+using namespace API;
+using namespace Geometry;
+
+DECLARE_FUNCTION(LatticeFunction)
+
+LatticeFunction::LatticeFunction() : ILatticeFunction(), m_cellParameters() {}
+
+/// Calculates d-values using the internally stored cell parameters
+void LatticeFunction::functionLattice(const LatticeDomain &latticeDomain,
+                                      FunctionValues &values) const {
+  throwIfNoFunctionSet();
+
+  UnitCell cell = m_cellParameters->getUnitCellFromParameters();
+  double zeroShift = m_cellParameters->getParameter("ZeroShift");
+
+  for (size_t i = 0; i < values.size(); ++i) {
+    values.setCalculated(i, cell.d(latticeDomain[i]) + zeroShift);
+  }
+}
+
+/// Assigns the crystal system to the internally stored function. Number of
+/// parameters may change after this function call.
+void LatticeFunction::setCrystalSystem(const std::string &crystalSystem) {
+  throwIfNoFunctionSet();
+
+  m_cellParameters->setAttributeValue("CrystalSystem", crystalSystem);
+}
+
+/// Sets the unit cell parameters from a string that can be parsed by
+/// Geometry::strToUnitCell.
+void LatticeFunction::setUnitCell(const std::string &unitCellString) {
+  throwIfNoFunctionSet();
+
+  m_cellParameters->setParametersFromUnitCell(strToUnitCell(unitCellString));
+}
+
+/// Sets the unit cell parameters from a UnitCell object.
+void LatticeFunction::setUnitCell(const UnitCell &unitCell) {
+  throwIfNoFunctionSet();
+
+  m_cellParameters->setParametersFromUnitCell(unitCell);
+}
+
+/// Returns a UnitCell object constructed from the function parameters.
+UnitCell LatticeFunction::getUnitCell() const {
+  throwIfNoFunctionSet();
+
+  return m_cellParameters->getUnitCellFromParameters();
+}
+
+/// Sets the decorated function to expose parameters
+void LatticeFunction::init() {
+  setDecoratedFunction("PawleyParameterFunction");
+}
+
+/// Checks that the decorated function is a PawleyParameterFunction.
+void LatticeFunction::beforeDecoratedFunctionSet(const IFunction_sptr &fn) {
+  PawleyParameterFunction_sptr paramFn =
+      boost::dynamic_pointer_cast<PawleyParameterFunction>(fn);
+
+  if (!paramFn) {
+    throw std::invalid_argument(
+        "LatticeFunction can only decorate a PawleyParameterFunction.");
+  }
+
+  m_cellParameters = paramFn;
+}
+
+} // namespace CurveFitting
+} // namespace Mantid
diff --git a/Code/Mantid/Framework/CurveFitting/src/LevenbergMarquardtMDMinimizer.cpp b/Code/Mantid/Framework/CurveFitting/src/LevenbergMarquardtMDMinimizer.cpp
index eadea53be79470fd29907f68bf54423c72643f22..7f21410a9b6d7491b8b250cdaed575984a0b6572 100644
--- a/Code/Mantid/Framework/CurveFitting/src/LevenbergMarquardtMDMinimizer.cpp
+++ b/Code/Mantid/Framework/CurveFitting/src/LevenbergMarquardtMDMinimizer.cpp
@@ -22,7 +22,9 @@ namespace {
 Kernel::Logger g_log("LevenbergMarquardMD");
 }
 
+// clang-format off
 DECLARE_FUNCMINIMIZER(LevenbergMarquardtMDMinimizer, Levenberg-MarquardtMD)
+// clang-format on
 
 /// Constructor
 LevenbergMarquardtMDMinimizer::LevenbergMarquardtMDMinimizer()
diff --git a/Code/Mantid/Framework/CurveFitting/src/LevenbergMarquardtMinimizer.cpp b/Code/Mantid/Framework/CurveFitting/src/LevenbergMarquardtMinimizer.cpp
index 567cf15c960a65016c20084f3b8e9f4333911b93..8b363b58a6c7740985fe11188f2a62064afe2007 100644
--- a/Code/Mantid/Framework/CurveFitting/src/LevenbergMarquardtMinimizer.cpp
+++ b/Code/Mantid/Framework/CurveFitting/src/LevenbergMarquardtMinimizer.cpp
@@ -22,7 +22,9 @@ namespace {
 Kernel::Logger g_log("LevenbergMarquardtMinimizer");
 }
 
+// clang-format off
 DECLARE_FUNCMINIMIZER(LevenbergMarquardtMinimizer, Levenberg-Marquardt)
+// clang-format on
 
 LevenbergMarquardtMinimizer::LevenbergMarquardtMinimizer()
     : m_data(NULL), gslContainer(), m_gslSolver(NULL), m_function(),
diff --git a/Code/Mantid/Framework/CurveFitting/src/PRConjugateGradientMinimizer.cpp b/Code/Mantid/Framework/CurveFitting/src/PRConjugateGradientMinimizer.cpp
index 513fb3f36c10126cb69193e01b7f090a92f408f3..ae9d3adaa6fb0e7841e23f563c88b6027a88685a 100644
--- a/Code/Mantid/Framework/CurveFitting/src/PRConjugateGradientMinimizer.cpp
+++ b/Code/Mantid/Framework/CurveFitting/src/PRConjugateGradientMinimizer.cpp
@@ -10,10 +10,12 @@
 
 namespace Mantid {
 namespace CurveFitting {
+
+// clang-format off
 ///@cond nodoc
-DECLARE_FUNCMINIMIZER(PRConjugateGradientMinimizer,
-                      Conjugate gradient(Polak - Ribiere imp.))
+DECLARE_FUNCMINIMIZER(PRConjugateGradientMinimizer,Conjugate gradient (Polak-Ribiere imp.))
 ///@endcond
+// clang-format on
 
 /// Return a concrete type to initialize m_gslSolver
 /// gsl_multimin_fdfminimizer_vector_bfgs2
diff --git a/Code/Mantid/Framework/CurveFitting/src/PawleyFit.cpp b/Code/Mantid/Framework/CurveFitting/src/PawleyFit.cpp
index 11a110f20013093857770a0b029f87931656e4a0..e3291e7fb7182c029c049022884139f11368690d 100644
--- a/Code/Mantid/Framework/CurveFitting/src/PawleyFit.cpp
+++ b/Code/Mantid/Framework/CurveFitting/src/PawleyFit.cpp
@@ -72,6 +72,8 @@ void PawleyFit::addHKLsToFunction(PawleyFunction_sptr &pawleyFn,
   pawleyFn->clearPeaks();
 
   try {
+    V3DFromHKLColumnExtractor extractor;
+
     Column_const_sptr hklColumn = tableWs->getColumn("HKL");
     Column_const_sptr dColumn = tableWs->getColumn("d");
     Column_const_sptr intensityColumn = tableWs->getColumn("Intensity");
@@ -79,7 +81,7 @@ void PawleyFit::addHKLsToFunction(PawleyFunction_sptr &pawleyFn,
 
     for (size_t i = 0; i < tableWs->rowCount(); ++i) {
       try {
-        V3D hkl = getHKLFromColumn(i, hklColumn);
+        V3D hkl = extractor(hklColumn, i);
 
         double d = (*dColumn)[i];
         double center = getTransformedCenter(d, unit);
@@ -102,36 +104,6 @@ void PawleyFit::addHKLsToFunction(PawleyFunction_sptr &pawleyFn,
   }
 }
 
-/// Tries to extract Miller indices as V3D from column.
-V3D PawleyFit::getHKLFromColumn(size_t i,
-                                const Column_const_sptr &hklColumn) const {
-  if (hklColumn->type() == "V3D") {
-    return hklColumn->cell<V3D>(i);
-  }
-
-  return getHkl(hklColumn->cell<std::string>(i));
-}
-
-/// Try to extract a V3D from the given string with different separators.
-V3D PawleyFit::getHkl(const std::string &hklString) const {
-  auto delimiters = boost::is_any_of(" ,[];");
-
-  std::string workingCopy = boost::trim_copy_if(hklString, delimiters);
-  std::vector<std::string> indicesStr;
-  boost::split(indicesStr, workingCopy, delimiters);
-
-  if (indicesStr.size() != 3) {
-    throw std::invalid_argument("Input string cannot be parsed as HKL.");
-  }
-
-  V3D hkl;
-  hkl.setX(boost::lexical_cast<double>(indicesStr[0]));
-  hkl.setY(boost::lexical_cast<double>(indicesStr[1]));
-  hkl.setZ(boost::lexical_cast<double>(indicesStr[2]));
-
-  return hkl;
-}
-
 /// Creates a table containing the cell parameters stored in the supplied
 /// function.
 ITableWorkspace_sptr
@@ -401,5 +373,49 @@ void PawleyFit::exec() {
   setProperty("ReducedChiSquare", chiSquare);
 }
 
+/// Tries to extract Miller indices as V3D from column.
+V3D V3DFromHKLColumnExtractor::operator()(const Column_const_sptr &hklColumn,
+                                          size_t i) const {
+  if (hklColumn->type() == "V3D") {
+    return getHKLFromV3DColumn(hklColumn, i);
+  }
+
+  return getHKLFromStringColumn(hklColumn, i);
+}
+
+/// Returns the i-th cell of a V3D column.
+V3D V3DFromHKLColumnExtractor::getHKLFromV3DColumn(
+    const Column_const_sptr &hklColumn, size_t i) const {
+  return hklColumn->cell<V3D>(i);
+}
+
+/// Pass the cell value as string to getHKLFromString.
+V3D V3DFromHKLColumnExtractor::getHKLFromStringColumn(
+    const Column_const_sptr &hklColumn, size_t i) const {
+
+  return getHKLFromString(hklColumn->cell<std::string>(i));
+}
+
+/// Try to extract a V3D from the given string with different separators.
+V3D V3DFromHKLColumnExtractor::getHKLFromString(const std::string &hklString)
+    const {
+  auto delimiters = boost::is_any_of(" ,[];");
+
+  std::string workingCopy = boost::trim_copy_if(hklString, delimiters);
+  std::vector<std::string> indicesStr;
+  boost::split(indicesStr, workingCopy, delimiters);
+
+  if (indicesStr.size() != 3) {
+    throw std::invalid_argument("Input string cannot be parsed as HKL.");
+  }
+
+  V3D hkl;
+  hkl.setX(boost::lexical_cast<double>(indicesStr[0]));
+  hkl.setY(boost::lexical_cast<double>(indicesStr[1]));
+  hkl.setZ(boost::lexical_cast<double>(indicesStr[2]));
+
+  return hkl;
+}
+
 } // namespace CurveFitting
 } // namespace Mantid
diff --git a/Code/Mantid/Framework/CurveFitting/src/PawleyFunction.cpp b/Code/Mantid/Framework/CurveFitting/src/PawleyFunction.cpp
index 781e67b9c6325c37a1f27bebd12a40e468edcca5..a64b5232ad4b094559e44e61250aae16b94f3568 100644
--- a/Code/Mantid/Framework/CurveFitting/src/PawleyFunction.cpp
+++ b/Code/Mantid/Framework/CurveFitting/src/PawleyFunction.cpp
@@ -1,6 +1,9 @@
 #include "MantidCurveFitting/PawleyFunction.h"
 
 #include "MantidAPI/FunctionFactory.h"
+
+#include "MantidCurveFitting/BoundaryConstraint.h"
+
 #include "MantidKernel/UnitConversion.h"
 #include "MantidKernel/UnitFactory.h"
 
@@ -173,32 +176,14 @@ void PawleyParameterFunction::setProfileFunction(
  * This method takes the name of a crystal system (case insensitive) and stores
  * it. Furthermore it creates the necessary parameters, which means that after
  * calling this function, PawleyParameterFunction potentially exposes a
- * different number of parameters.
+ * different number of parameters. The parameters are constrained to physically
+ * meaningful values (angles between 0 and 180 degrees, cell edges above 0).
  *
  * @param crystalSystem :: Crystal system, case insensitive.
  */
 void
 PawleyParameterFunction::setCrystalSystem(const std::string &crystalSystem) {
-  std::string crystalSystemLC = boost::algorithm::to_lower_copy(crystalSystem);
-
-  if (crystalSystemLC == "cubic") {
-    m_crystalSystem = PointGroup::Cubic;
-  } else if (crystalSystemLC == "tetragonal") {
-    m_crystalSystem = PointGroup::Tetragonal;
-  } else if (crystalSystemLC == "hexagonal") {
-    m_crystalSystem = PointGroup::Hexagonal;
-  } else if (crystalSystemLC == "trigonal") {
-    m_crystalSystem = PointGroup::Trigonal;
-  } else if (crystalSystemLC == "orthorhombic") {
-    m_crystalSystem = PointGroup::Orthorhombic;
-  } else if (crystalSystemLC == "monoclinic") {
-    m_crystalSystem = PointGroup::Monoclinic;
-  } else if (crystalSystemLC == "triclinic") {
-    m_crystalSystem = PointGroup::Triclinic;
-  } else {
-    throw std::invalid_argument("Not a valid crystal system: '" +
-                                crystalSystem + "'.");
-  }
+  m_crystalSystem = Geometry::getCrystalSystemFromString(crystalSystem);
 
   createCrystalSystemParameters(m_crystalSystem);
 }
@@ -212,30 +197,43 @@ void PawleyParameterFunction::createCrystalSystemParameters(
   switch (crystalSystem) {
   case PointGroup::Cubic:
     declareParameter("a", 1.0);
+    addLengthConstraint("a");
     break;
 
   case PointGroup::Hexagonal:
   case PointGroup::Tetragonal:
     declareParameter("a", 1.0);
     declareParameter("c", 1.0);
+    addLengthConstraint("a");
+    addLengthConstraint("c");
     break;
 
   case PointGroup::Orthorhombic:
     declareParameter("a", 1.0);
     declareParameter("b", 1.0);
     declareParameter("c", 1.0);
+    addLengthConstraint("a");
+    addLengthConstraint("b");
+    addLengthConstraint("c");
     break;
 
   case PointGroup::Monoclinic:
     declareParameter("a", 1.0);
     declareParameter("b", 1.0);
     declareParameter("c", 1.0);
+    addLengthConstraint("a");
+    addLengthConstraint("b");
+    addLengthConstraint("c");
+
     declareParameter("Beta", 90.0);
+    addAngleConstraint("Beta");
     break;
 
   case PointGroup::Trigonal:
     declareParameter("a", 1.0);
     declareParameter("Alpha", 90.0);
+    addLengthConstraint("a");
+    addAngleConstraint("Alpha");
     break;
 
   default:
@@ -243,16 +241,40 @@ void PawleyParameterFunction::createCrystalSystemParameters(
     declareParameter("a", 1.0);
     declareParameter("b", 1.0);
     declareParameter("c", 1.0);
+    addLengthConstraint("a");
+    addLengthConstraint("b");
+    addLengthConstraint("c");
 
     declareParameter("Alpha", 90.0);
     declareParameter("Beta", 90.0);
     declareParameter("Gamma", 90.0);
+    addAngleConstraint("Alpha");
+    addAngleConstraint("Beta");
+    addAngleConstraint("Gamma");
     break;
   }
 
   declareParameter("ZeroShift", 0.0);
 }
 
+/// Adds a default constraint so that cell edge lengths can not be less than 0.
+void
+PawleyParameterFunction::addLengthConstraint(const std::string &parameterName) {
+  BoundaryConstraint *cellEdgeConstraint =
+      new BoundaryConstraint(this, parameterName, 0.0, true);
+  cellEdgeConstraint->setPenaltyFactor(1e12);
+  addConstraint(cellEdgeConstraint);
+}
+
+/// Adds a default constraint so cell angles are in the range 0 to 180.
+void
+PawleyParameterFunction::addAngleConstraint(const std::string &parameterName) {
+  BoundaryConstraint *cellAngleConstraint =
+      new BoundaryConstraint(this, parameterName, 0.0, 180.0, true);
+  cellAngleConstraint->setPenaltyFactor(1e12);
+  addConstraint(cellAngleConstraint);
+}
+
 /// Tries to extract and store the center parameter name from the function.
 void PawleyParameterFunction::setCenterParameterNameFromFunction(
     const IPeakFunction_sptr &profileFunction) {
diff --git a/Code/Mantid/Framework/CurveFitting/test/CostFuncUnweightedLeastSquaresTest.h b/Code/Mantid/Framework/CurveFitting/test/CostFuncUnweightedLeastSquaresTest.h
new file mode 100644
index 0000000000000000000000000000000000000000..aaff2f3e849b65ef7c289b95cb94cd6d0c185777
--- /dev/null
+++ b/Code/Mantid/Framework/CurveFitting/test/CostFuncUnweightedLeastSquaresTest.h
@@ -0,0 +1,84 @@
+#ifndef MANTID_CURVEFITTING_COSTFUNCUNWEIGHTEDLEASTSQUARESTEST_H_
+#define MANTID_CURVEFITTING_COSTFUNCUNWEIGHTEDLEASTSQUARESTEST_H_
+
+#include <cxxtest/TestSuite.h>
+#include "MantidAPI/FunctionDomain1D.h"
+#include "MantidAPI/FunctionFactory.h"
+
+#include "MantidCurveFitting/CostFuncUnweightedLeastSquares.h"
+
+#include <boost/make_shared.hpp>
+
+using Mantid::CurveFitting::CostFuncUnweightedLeastSquares;
+using namespace Mantid::API;
+
+class CostFuncUnweightedLeastSquaresTest : public CxxTest::TestSuite {
+public:
+  // This pair of boilerplate methods prevent the suite being created statically
+  // This means the constructor isn't called when running other tests
+  static CostFuncUnweightedLeastSquaresTest *createSuite() {
+    return new CostFuncUnweightedLeastSquaresTest();
+  }
+  static void destroySuite(CostFuncUnweightedLeastSquaresTest *suite) {
+    delete suite;
+  }
+
+  void testGetFitWeights() {
+    /* The test makes sure that the returned weights are always 1.0 */
+    FunctionDomain1DVector d1d(std::vector<double>(20, 1.0));
+    FunctionValues_sptr values = boost::make_shared<FunctionValues>(d1d);
+
+    for (size_t i = 0; i < values->size(); ++i) {
+      values->setFitWeight(i, static_cast<double>(i));
+    }
+
+    TestableCostFuncUnweightedLeastSquares uwls;
+
+    std::vector<double> weights = uwls.getFitWeights(values);
+
+    TS_ASSERT_EQUALS(weights.size(), values->size());
+    for (size_t i = 0; i < weights.size(); ++i) {
+      TS_ASSERT_EQUALS(weights[i], 1.0);
+    }
+  }
+
+  void testGetResidualVariance() {
+    /* Make sure that the calculated residuals variance is correct. The
+     * test uses dummy values for which the sum of residuals is known.
+     */
+    FunctionDomain1DVector d1d(std::vector<double>(10, 1.0));
+    FunctionValues_sptr values = boost::make_shared<FunctionValues>(d1d);
+
+    // Data generated with numpy.random.normal(loc=2.0, scale=0.25, size=10)
+    double obsValues[10] = { 1.9651563160778176, 1.9618188576389295,
+                             1.9565961107376706, 2.0049055113975252,
+                             2.0747505383068865, 2.0666404554638578,
+                             1.7854026688169637, 2.266075963037971,
+                             1.8656602424955859, 1.8132221813342393 };
+
+    for (size_t i = 0; i < 10; ++i) {
+      values->setCalculated(2.0);
+      values->setFitData(i, obsValues[i]);
+    }
+
+    // Function has 1 parameter, so degrees of freedom = 9
+    IFunction_sptr fn =
+        FunctionFactory::Instance().createFunction("FlatBackground");
+    FunctionDomain_sptr domain =
+        boost::make_shared<FunctionDomain1DVector>(d1d);
+
+    TestableCostFuncUnweightedLeastSquares uwls;
+    uwls.setFittingFunction(fn, domain, values);
+
+    double variance = uwls.getResidualVariance();
+    TS_ASSERT_DELTA(variance, 0.0204877770575, 1e-13);
+  }
+
+private:
+  class TestableCostFuncUnweightedLeastSquares
+      : public CostFuncUnweightedLeastSquares {
+    friend class CostFuncUnweightedLeastSquaresTest;
+  };
+};
+
+#endif /* MANTID_CURVEFITTING_COSTFUNCUNWEIGHTEDLEASTSQUARESTEST_H_ */
diff --git a/Code/Mantid/Framework/CurveFitting/test/FABADAMinimizerTest.h b/Code/Mantid/Framework/CurveFitting/test/FABADAMinimizerTest.h
index 54ce15e4a07bfeecd967620864af4b4f26a2c64b..54821e1c286781c09a340faea26bca50ab6cbf73 100644
--- a/Code/Mantid/Framework/CurveFitting/test/FABADAMinimizerTest.h
+++ b/Code/Mantid/Framework/CurveFitting/test/FABADAMinimizerTest.h
@@ -44,7 +44,9 @@ public:
     fit.setProperty("CreateOutput", true);
     fit.setProperty("MaxIterations", 100000);
     fit.setProperty("Minimizer", "FABADA,ChainLength=5000,StepsBetweenValues="
-                                 "10,ConvergenceCriteria = 0.1");
+                                 "10,ConvergenceCriteria=0.1,CostFunctionTable="
+                                 "CostFunction,Chains=Chain,ConvergedChain"
+                                 "=ConvergedChain,Parameters=Parameters");
 
     TS_ASSERT_THROWS_NOTHING(fit.execute());
 
@@ -104,9 +106,9 @@ public:
     TS_ASSERT_EQUALS(Xconv.size(), 500);
     TS_ASSERT_EQUALS(Xconv[437], 437);
 
-    TS_ASSERT(AnalysisDataService::Instance().doesExist("chain"));
+    TS_ASSERT(AnalysisDataService::Instance().doesExist("Chain"));
     MatrixWorkspace_sptr wsChain = boost::dynamic_pointer_cast<MatrixWorkspace>(
-        API::AnalysisDataService::Instance().retrieve("chain"));
+        API::AnalysisDataService::Instance().retrieve("Chain"));
     TS_ASSERT(wsChain);
     TS_ASSERT_EQUALS(wsChain->getNumberHistograms(), n + 1);
 
diff --git a/Code/Mantid/Framework/CurveFitting/test/LatticeDomainCreatorTest.h b/Code/Mantid/Framework/CurveFitting/test/LatticeDomainCreatorTest.h
new file mode 100644
index 0000000000000000000000000000000000000000..f2b11bcb8881f0949ef3fa668212619d9e1a5da2
--- /dev/null
+++ b/Code/Mantid/Framework/CurveFitting/test/LatticeDomainCreatorTest.h
@@ -0,0 +1,233 @@
+#ifndef MANTID_CURVEFITTING_LATTICEDOMAINCREATORTEST_H_
+#define MANTID_CURVEFITTING_LATTICEDOMAINCREATORTEST_H_
+
+#include <cxxtest/TestSuite.h>
+
+#include "MantidAPI/FunctionFactory.h"
+#include "MantidAPI/LatticeDomain.h"
+#include "MantidCurveFitting/LatticeDomainCreator.h"
+#include "MantidCurveFitting/LatticeFunction.h"
+#include "MantidDataObjects/PeaksWorkspace.h"
+#include "MantidTestHelpers/WorkspaceCreationHelper.h"
+
+using Mantid::CurveFitting::LatticeDomainCreator;
+using Mantid::CurveFitting::LatticeFunction;
+using Mantid::Kernel::V3D;
+
+using namespace Mantid::API;
+using namespace Mantid::DataObjects;
+
+class LatticeDomainCreatorTest : public CxxTest::TestSuite {
+public:
+  // This pair of boilerplate methods prevent the suite being created statically
+  // This means the constructor isn't called when running other tests
+  static LatticeDomainCreatorTest *createSuite() {
+    return new LatticeDomainCreatorTest();
+  }
+  static void destroySuite(LatticeDomainCreatorTest *suite) { delete suite; }
+
+  void testGetDomainSizeIPeaksWorkspace() {
+    Workspace_sptr peaksWs = boost::dynamic_pointer_cast<Workspace>(
+        WorkspaceCreationHelper::createPeaksWorkspace(5));
+
+    TestableLatticeDomainCreator dc;
+    TS_ASSERT_THROWS_NOTHING(dc.setWorkspace(peaksWs));
+
+    TS_ASSERT_EQUALS(dc.getDomainSize(), 5);
+  }
+
+  void testGetDomainSizeTableWorkspace() {
+    ITableWorkspace_sptr table = getValidTableWs();
+
+    TestableLatticeDomainCreator dc;
+    TS_ASSERT_THROWS_NOTHING(dc.setWorkspace(table));
+
+    TS_ASSERT_EQUALS(dc.getDomainSize(), 3);
+  }
+
+  void testCreateDomainTableWs() {
+    ITableWorkspace_sptr table = getValidTableWs();
+
+    TestableLatticeDomainCreator dc;
+
+    FunctionDomain_sptr domain;
+    FunctionValues_sptr values;
+
+    TS_ASSERT_THROWS_NOTHING(
+        dc.createDomainFromPeakTable(table, domain, values, 0));
+
+    TS_ASSERT_EQUALS(domain->size(), 3);
+    TS_ASSERT_EQUALS(values->size(), 3);
+
+    boost::shared_ptr<LatticeDomain> latticeDomain =
+        boost::dynamic_pointer_cast<LatticeDomain>(domain);
+
+    TS_ASSERT(latticeDomain);
+
+    TS_ASSERT_EQUALS((*latticeDomain)[0], V3D(1, 1, 1));
+    TS_ASSERT_EQUALS((*latticeDomain)[1], V3D(2, 2, 0));
+    TS_ASSERT_EQUALS((*latticeDomain)[2], V3D(3, 1, 1));
+
+    TS_ASSERT_EQUALS(values->getFitData(0), 3.135702);
+    TS_ASSERT_EQUALS(values->getFitData(1), 1.920217);
+    TS_ASSERT_EQUALS(values->getFitData(2), 1.637567);
+
+    TS_ASSERT_EQUALS(values->getFitWeight(0), 1.0);
+    TS_ASSERT_EQUALS(values->getFitWeight(1), 1.0);
+    TS_ASSERT_EQUALS(values->getFitWeight(2), 1.0);
+  }
+
+  void testCreateDomainHKL000() {
+      ITableWorkspace_sptr table = getValidTableWs();
+      TableRow newRow = table->appendRow();
+      newRow << V3D(0, 0, 0) << 0.0;
+
+      TestableLatticeDomainCreator dc;
+
+      FunctionDomain_sptr domain;
+      FunctionValues_sptr values;
+
+      TS_ASSERT_THROWS_NOTHING(
+          dc.createDomainFromPeakTable(table, domain, values, 0));
+
+      // Domain size should still be 3, because 0, 0, 0 can not be used
+      TS_ASSERT_EQUALS(domain->size(), 3);
+      TS_ASSERT_EQUALS(values->size(), 3);
+  }
+
+  void testCreateDomainTableWsInvalid() {
+    ITableWorkspace_sptr invalid = getInvalidTableWs();
+    ITableWorkspace_sptr empty = getEmptyTableWs();
+
+    TestableLatticeDomainCreator dc;
+
+    FunctionDomain_sptr domain;
+    FunctionValues_sptr values;
+
+    TS_ASSERT_THROWS(dc.createDomainFromPeakTable(invalid, domain, values, 0),
+                     std::runtime_error);
+
+    TS_ASSERT_THROWS(dc.createDomainFromPeakTable(empty, domain, values, 0),
+                     std::range_error);
+  }
+
+  void testCreateDomainPeaksWorkspace() {
+    IPeaksWorkspace_sptr peaksWs = boost::dynamic_pointer_cast<IPeaksWorkspace>(
+        WorkspaceCreationHelper::createPeaksWorkspace(2));
+    peaksWs->getPeak(0).setHKL(V3D(1, 1, 1));
+    peaksWs->getPeak(1).setHKL(V3D(2, 2, 0));
+
+    TestableLatticeDomainCreator dc;
+
+    FunctionDomain_sptr domain;
+    FunctionValues_sptr values;
+
+    TS_ASSERT_THROWS_NOTHING(
+        dc.createDomainFromPeaksWorkspace(peaksWs, domain, values, 0));
+
+    TS_ASSERT_EQUALS(domain->size(), 2);
+    TS_ASSERT_EQUALS(values->size(), 2);
+
+    boost::shared_ptr<LatticeDomain> latticeDomain =
+        boost::dynamic_pointer_cast<LatticeDomain>(domain);
+
+    TS_ASSERT(latticeDomain);
+
+    TS_ASSERT_EQUALS((*latticeDomain)[0], V3D(1, 1, 1));
+    TS_ASSERT_EQUALS((*latticeDomain)[1], V3D(2, 2, 0));
+
+    TS_ASSERT_EQUALS(values->getFitData(0), peaksWs->getPeak(0).getDSpacing());
+    TS_ASSERT_EQUALS(values->getFitData(1), peaksWs->getPeak(1).getDSpacing());
+
+    TS_ASSERT_EQUALS(values->getFitWeight(0), 1.0);
+    TS_ASSERT_EQUALS(values->getFitWeight(1), 1.0);
+  }
+
+  void testCreateOutputWorkspace() {
+    ITableWorkspace_sptr table = getValidTableWs();
+
+    // Function that does nothing.
+    IFunction_sptr fn = boost::make_shared<EmptyLatticeFunction>();
+    FunctionDomain_sptr domain;
+    FunctionValues_sptr values;
+
+    // Make domain and values
+    TestableLatticeDomainCreator dc;
+    dc.createDomainFromPeakTable(table, domain, values, 0);
+
+    values->setCalculated(0, 3.125702);
+    values->setCalculated(1, 1.930217);
+    values->setCalculated(2, 1.627567);
+
+    Workspace_sptr outputWs;
+    TS_ASSERT_THROWS_NOTHING(
+        outputWs = dc.createOutputWorkspace("base", fn, domain, values, "pp"));
+
+    ITableWorkspace_sptr tableWs =
+        boost::dynamic_pointer_cast<ITableWorkspace>(outputWs);
+    TS_ASSERT(tableWs);
+
+    TS_ASSERT_EQUALS(tableWs->rowCount(), 3);
+    TS_ASSERT_DELTA(tableWs->cell<double>(0, 3), 0.01, 1e-6);
+    TS_ASSERT_DELTA(tableWs->cell<double>(1, 3), -0.01, 1e-6);
+    TS_ASSERT_DELTA(tableWs->cell<double>(2, 3), 0.01, 1e-6);
+  }
+
+private:
+  ITableWorkspace_sptr getValidTableWs() {
+    ITableWorkspace_sptr table = WorkspaceFactory::Instance().createTable();
+    table->addColumn("V3D", "HKL");
+    table->addColumn("double", "d");
+
+    TableRow newRow = table->appendRow();
+    newRow << V3D(1, 1, 1) << 3.135702;
+    newRow = table->appendRow();
+    newRow << V3D(2, 2, 0) << 1.920217;
+    newRow = table->appendRow();
+    newRow << V3D(3, 1, 1) << 1.637567;
+
+    return table;
+  }
+
+  ITableWorkspace_sptr getEmptyTableWs() {
+    ITableWorkspace_sptr table = WorkspaceFactory::Instance().createTable();
+    table->addColumn("V3D", "HKL");
+    table->addColumn("double", "d");
+
+    return table;
+  }
+
+  ITableWorkspace_sptr getInvalidTableWs() {
+    ITableWorkspace_sptr table = WorkspaceFactory::Instance().createTable();
+    table->addColumn("V3D", "HKL");
+
+    TableRow newRow = table->appendRow();
+    newRow << V3D(1, 1, 1);
+    newRow = table->appendRow();
+    newRow << V3D(2, 2, 0);
+    newRow = table->appendRow();
+    newRow << V3D(3, 1, 1);
+
+    return table;
+  }
+
+  class TestableLatticeDomainCreator : public LatticeDomainCreator {
+    friend class LatticeDomainCreatorTest;
+
+  public:
+    TestableLatticeDomainCreator() : LatticeDomainCreator(NULL, "") {}
+
+    void setWorkspace(const Workspace_sptr &ws) { m_workspace = ws; }
+  };
+
+  class EmptyLatticeFunction : public LatticeFunction {
+  public:
+    void functionLattice(const LatticeDomain &latticeDomain,
+                         FunctionValues &values) const {
+      UNUSED_ARG(latticeDomain);
+      UNUSED_ARG(values);
+    }
+  };
+};
+
+#endif /* MANTID_CURVEFITTING_LATTICEDOMAINCREATORTEST_H_ */
diff --git a/Code/Mantid/Framework/CurveFitting/test/LatticeFunctionTest.h b/Code/Mantid/Framework/CurveFitting/test/LatticeFunctionTest.h
new file mode 100644
index 0000000000000000000000000000000000000000..3bf49ea7a72c9467f5ddd5eabadbf2e5a8370851
--- /dev/null
+++ b/Code/Mantid/Framework/CurveFitting/test/LatticeFunctionTest.h
@@ -0,0 +1,156 @@
+#ifndef MANTID_CURVEFITTING_LATTICEFUNCTIONTEST_H_
+#define MANTID_CURVEFITTING_LATTICEFUNCTIONTEST_H_
+
+#include <cxxtest/TestSuite.h>
+
+#include "MantidCurveFitting/LatticeFunction.h"
+#include "MantidAPI/AlgorithmManager.h"
+#include "MantidAPI/FunctionFactory.h"
+#include "MantidAPI/LatticeDomain.h"
+#include "MantidAPI/TableRow.h"
+#include "MantidGeometry/Crystal/UnitCell.h"
+
+using Mantid::CurveFitting::LatticeFunction;
+using Mantid::Kernel::V3D;
+using Mantid::Geometry::UnitCell;
+using Mantid::Geometry::unitCellToStr;
+
+using namespace Mantid::API;
+
+class LatticeFunctionTest : public CxxTest::TestSuite {
+public:
+  // This pair of boilerplate methods prevent the suite being created statically
+  // This means the constructor isn't called when running other tests
+  static LatticeFunctionTest *createSuite() {
+    return new LatticeFunctionTest();
+  }
+  static void destroySuite(LatticeFunctionTest *suite) { delete suite; }
+
+  void testSetCrystalSystem() {
+    LatticeFunction fn;
+    fn.initialize();
+
+    TS_ASSERT_THROWS_NOTHING(fn.setCrystalSystem("Cubic"));
+    TS_ASSERT_THROWS_NOTHING(fn.setCrystalSystem("Tetragonal"));
+    TS_ASSERT_THROWS_NOTHING(fn.setCrystalSystem("triclinic"));
+
+    TS_ASSERT_THROWS(fn.setCrystalSystem("DoesNotExist"),
+                     std::invalid_argument);
+
+    fn.setCrystalSystem("Cubic");
+    // a and ZeroShift
+    TS_ASSERT_EQUALS(fn.nParams(), 2);
+
+    fn.setCrystalSystem("Hexagonal");
+    // a, c and ZeroShift
+    TS_ASSERT_EQUALS(fn.nParams(), 3);
+
+    /* The basic functionality is covered by the tests for
+     * PawleyParameterFunction.
+     */
+  }
+
+  void testSetUnitCellString() {
+    LatticeFunction fn;
+    fn.initialize();
+
+    TS_ASSERT_THROWS_NOTHING(fn.setUnitCell("1.0 2.0 3.0 90 100 110"));
+    TS_ASSERT_EQUALS(fn.getParameter("a"), 1.0);
+    TS_ASSERT_EQUALS(fn.getParameter("b"), 2.0);
+    TS_ASSERT_EQUALS(fn.getParameter("c"), 3.0);
+    TS_ASSERT_EQUALS(fn.getParameter("Alpha"), 90.0);
+    TS_ASSERT_EQUALS(fn.getParameter("Beta"), 100.0);
+    TS_ASSERT_EQUALS(fn.getParameter("Gamma"), 110.0);
+
+    TS_ASSERT_THROWS_NOTHING(fn.setUnitCell("1.0 2.0 3.0"));
+    TS_ASSERT_EQUALS(fn.getParameter("a"), 1.0);
+    TS_ASSERT_EQUALS(fn.getParameter("b"), 2.0);
+    TS_ASSERT_EQUALS(fn.getParameter("c"), 3.0);
+    TS_ASSERT_EQUALS(fn.getParameter("Alpha"), 90.0);
+    TS_ASSERT_EQUALS(fn.getParameter("Beta"), 90.0);
+    TS_ASSERT_EQUALS(fn.getParameter("Gamma"), 90.0);
+  }
+
+  void testSetUnitCellUnitCell() {
+    LatticeFunction fn;
+    fn.initialize();
+
+    TS_ASSERT_THROWS_NOTHING(fn.setUnitCell(UnitCell(1, 2, 3, 90, 100, 110)));
+    TS_ASSERT_EQUALS(fn.getParameter("a"), 1.0);
+    TS_ASSERT_EQUALS(fn.getParameter("b"), 2.0);
+    TS_ASSERT_EQUALS(fn.getParameter("c"), 3.0);
+    TS_ASSERT_EQUALS(fn.getParameter("Alpha"), 90.0);
+    TS_ASSERT_EQUALS(fn.getParameter("Beta"), 100.0);
+    TS_ASSERT_EQUALS(fn.getParameter("Gamma"), 110.0);
+  }
+
+  void testGetUnitCell() {
+    LatticeFunction fn;
+    fn.initialize();
+
+    UnitCell cell(1, 2, 3, 90, 100, 110);
+    TS_ASSERT_THROWS_NOTHING(fn.setUnitCell(cell));
+
+    TS_ASSERT_EQUALS(unitCellToStr(fn.getUnitCell()), unitCellToStr(cell));
+  }
+
+  void testFunctionValues() {
+    LatticeFunction fn;
+    fn.initialize();
+
+    // Al2O3, from PoldiCreatePeaksFromCell system test.
+    fn.setCrystalSystem("Hexagonal");
+    fn.setParameter("a", 4.7605);
+    fn.setParameter("c", 12.9956);
+
+    std::vector<V3D> hkls;
+    hkls.push_back(V3D(1, 0, -2));
+    hkls.push_back(V3D(1, 0, 4));
+    hkls.push_back(V3D(0, 0, 6));
+    hkls.push_back(V3D(5, -2, -5));
+
+    LatticeDomain domain(hkls);
+    FunctionValues values(domain);
+
+    // Calculate d-values
+    TS_ASSERT_THROWS_NOTHING(fn.function(domain, values));
+
+    // Check values.
+    TS_ASSERT_DELTA(values[0], 3.481144, 1e-6);
+    TS_ASSERT_DELTA(values[1], 2.551773, 1e-6);
+    TS_ASSERT_DELTA(values[2], 2.165933, 1e-6);
+    TS_ASSERT_DELTA(values[3], 0.88880, 1e-5);
+  }
+
+  void testFitExampleTable() {
+    // Fit Silicon lattice with three peaks.
+    ITableWorkspace_sptr table = WorkspaceFactory::Instance().createTable();
+    table->addColumn("V3D", "HKL");
+    table->addColumn("double", "d");
+
+    TableRow newRow = table->appendRow();
+    newRow << V3D(1, 1, 1) << 3.135702;
+    newRow = table->appendRow();
+    newRow << V3D(2, 2, 0) << 1.920217;
+    newRow = table->appendRow();
+    newRow << V3D(3, 1, 1) << 1.637567;
+
+    IFunction_sptr fn =
+        FunctionFactory::Instance().createFunction("LatticeFunction");
+    fn->setAttributeValue("CrystalSystem", "Cubic");
+    fn->addTies("ZeroShift=0.0");
+    fn->setParameter("a", 5);
+
+    IAlgorithm_sptr fit = AlgorithmManager::Instance().create("Fit");
+    fit->setProperty("Function", fn);
+    fit->setProperty("InputWorkspace", table);
+    fit->setProperty("CostFunction", "Unweighted least squares");
+    fit->setProperty("CreateOutput", true);
+    fit->execute();
+
+    TS_ASSERT_DELTA(fn->getParameter("a"), 5.4311946, 1e-6);
+    TS_ASSERT_LESS_THAN(fn->getError(0), 1e-6);
+  }
+};
+
+#endif /* MANTID_CURVEFITTING_LATTICEFUNCTIONTEST_H_ */
diff --git a/Code/Mantid/Framework/CurveFitting/test/PawleyFitTest.h b/Code/Mantid/Framework/CurveFitting/test/PawleyFitTest.h
index 30b0ca92e8d438ed7550f85384bfff6bb6d7469c..3c99605f3d889689ca20cd3a8f375a4c09f0a93f 100644
--- a/Code/Mantid/Framework/CurveFitting/test/PawleyFitTest.h
+++ b/Code/Mantid/Framework/CurveFitting/test/PawleyFitTest.h
@@ -12,6 +12,7 @@
 #include "MantidTestHelpers/WorkspaceCreationHelper.h"
 
 using Mantid::CurveFitting::PawleyFit;
+using Mantid::CurveFitting::V3DFromHKLColumnExtractor;
 using namespace Mantid::API;
 using namespace Mantid::Kernel;
 
@@ -23,17 +24,17 @@ public:
   static void destroySuite(PawleyFitTest *suite) { delete suite; }
 
   void testGetHKL() {
-    TestablePawleyFit pfit;
+    TestableV3DFromHKLColumnExtractor extractor;
 
     V3D referenceHKL(1, 2, 3);
 
-    TS_ASSERT_EQUALS(pfit.getHkl("1 2 3"), referenceHKL);
-    TS_ASSERT_EQUALS(pfit.getHkl(" 1 2 3 "), referenceHKL);
-    TS_ASSERT_EQUALS(pfit.getHkl("1 2 3"), referenceHKL);
-    TS_ASSERT_EQUALS(pfit.getHkl("1,2,3"), referenceHKL);
-    TS_ASSERT_EQUALS(pfit.getHkl("1;2;3"), referenceHKL);
-    TS_ASSERT_EQUALS(pfit.getHkl("[1,2,3]"), referenceHKL);
-    TS_ASSERT_EQUALS(pfit.getHkl("[1;2 3]"), referenceHKL);
+    TS_ASSERT_EQUALS(extractor.getHKLFromString("1 2 3"), referenceHKL);
+    TS_ASSERT_EQUALS(extractor.getHKLFromString(" 1 2 3 "), referenceHKL);
+    TS_ASSERT_EQUALS(extractor.getHKLFromString("1 2 3"), referenceHKL);
+    TS_ASSERT_EQUALS(extractor.getHKLFromString("1,2,3"), referenceHKL);
+    TS_ASSERT_EQUALS(extractor.getHKLFromString("1;2;3"), referenceHKL);
+    TS_ASSERT_EQUALS(extractor.getHKLFromString("[1,2,3]"), referenceHKL);
+    TS_ASSERT_EQUALS(extractor.getHKLFromString("[1;2 3]"), referenceHKL);
   }
 
   void testFitHexagonalCellQ() {
@@ -152,6 +153,10 @@ private:
     ~TestablePawleyFit() {}
   };
 
+  class TestableV3DFromHKLColumnExtractor : public V3DFromHKLColumnExtractor {
+    friend class PawleyFitTest;
+  };
+
   ITableWorkspace_sptr getHCPTable() {
     ITableWorkspace_sptr tableWs = WorkspaceFactory::Instance().createTable();
     tableWs->addColumn("V3D", "HKL");
diff --git a/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/ISISRunLogs.h b/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/ISISRunLogs.h
index a939a0aa63dc00541a5fa73cae18ce5c690e6a93..090d13a28dc1fde612e2a1da631848c6f48bafe8 100644
--- a/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/ISISRunLogs.h
+++ b/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/ISISRunLogs.h
@@ -52,6 +52,8 @@ public:
   void addStatusLog(API::Run &exptRun);
   /// Adds period related logs
   void addPeriodLogs(const int period, API::Run &exptRun);
+  /// Add 'period i' log.
+  void addPeriodLog(const int i, API::Run &exptRun);
 
 private:
   DISABLE_DEFAULT_CONSTRUCT(ISISRunLogs)
diff --git a/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/LoadFITS.h b/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/LoadFITS.h
index 474446b003ca01542ab1f1f8a38aba38bf33f20e..84a8058c8806c0e965a5580e1d73e120cbd24161 100644
--- a/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/LoadFITS.h
+++ b/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/LoadFITS.h
@@ -4,23 +4,22 @@
 //---------------------------------------------------
 // Includes
 //---------------------------------------------------
-#include "MantidAPI/IFileLoader.h"
-#include "MantidDataObjects/Workspace2D.h"
 #include <map>
 #include <sstream>
 #include <string>
 #include <vector>
 
-using namespace std;
+#include "MantidAPI/IFileLoader.h"
+#include "MantidDataObjects/Workspace2D.h"
 
 struct FITSInfo {
-  vector<string> headerItems;
-  std::map<string, string> headerKeys;
+  std::vector<std::string> headerItems;
+  std::map<std::string, std::string> headerKeys;
   int bitsPerPixel;
   int numberOfAxis;
   int offset;
   int headerSizeMultiplier;
-  vector<size_t> axisPixelLengths;
+  std::vector<size_t> axisPixelLengths;
   double tof;
   double timeBin;
   double scale;
@@ -81,7 +80,9 @@ public:
   virtual int version() const { return 1; }
 
   /// Algorithm's category for identification overriding a virtual method
-  virtual const std::string category() const { return "DataHandling"; }
+  virtual const std::string category() const {
+    return "DataHandling;DataHandling\\Tomography";
+  }
 
   /// Returns a confidence value that this algorithm can load a file
   virtual int confidence(Kernel::FileDescriptor &descriptor) const;
@@ -97,7 +98,8 @@ private:
   void exec();
 
   /// Loads files into workspace(s)
-  void doLoadFiles(const std::vector<std::string> &paths);
+  void doLoadFiles(const std::vector<std::string> &paths,
+                   const std::string &outWSName, bool loadAsRectImg = false);
 
   /// Loads the FITS header(s) into a struct
   void doLoadHeaders(const std::vector<std::string> &paths,
@@ -111,17 +113,28 @@ private:
   makeWorkspace(const FITSInfo &fileInfo, size_t &newFileNumber,
                 std::vector<char> &buffer, API::MantidImage &imageY,
                 API::MantidImage &imageE,
-                const DataObjects::Workspace2D_sptr parent);
+                const DataObjects::Workspace2D_sptr parent,
+                bool loadAsRectImg = false);
 
   // Reads the data from a single FITS file into a workspace
-  void readDataToWorkspace2D(DataObjects::Workspace2D_sptr ws,
-                             const FITSInfo &fileInfo, API::MantidImage &imageY,
-                             API::MantidImage &imageE,
-                             std::vector<char> &buffer);
+  void readDataToImgs(const FITSInfo &fileInfo, API::MantidImage &imageY,
+                      API::MantidImage &imageE, std::vector<char> &buffer);
 
   /// Once loaded, check against standard and limitations of this algorithm
   void headerSanityCheck(const FITSInfo &hdr, const FITSInfo &hdrFirst);
 
+  /// filter noise pixel by pixel
+  void doFilterNoise(double thresh, API::MantidImage &imageY,
+                     API::MantidImage &imageE);
+
+  /// rebin the matrix/image
+  void doRebin(size_t rebin, API::MantidImage &imageY,
+               API::MantidImage &imageE, API::MantidImage &rebinnedY,
+               API::MantidImage &rebinnedE);
+
+  /// identifies fits coming from 'other' cameras by specific headers
+  bool isInstrOtherThanIMAT(FITSInfo &hdr);
+
   void setupDefaultKeywordNames();
 
   /// Returns the trailing number from a string minus leading 0's (so 25 from
@@ -144,31 +157,35 @@ private:
   std::vector<std::string> m_headerAxisNameKeys;
   std::string m_mapFile;
 
-  static const std::string m_defaultImgType;
+  static const std::string g_defaultImgType;
 
   // names of extension headers
   std::string m_sampleRotation;
   std::string m_imageType;
 
   std::string m_baseName;
-  size_t m_spectraCount;
+  size_t m_pixelCount;
+  // rebin block size (m_rebin x m_rebin) cells
+  int m_rebin;
+  // noise threshold level
+  double m_noiseThresh;
   API::Progress *m_progress;
 
   // Number of digits for the fixed width appendix number added to
   // workspace names, i.e. 3=> workspace_001; 5 => workspace_00001
-  static const size_t DIGIT_SIZE_APPEND = 5;
+  static const size_t g_DIGIT_SIZE_APPEND = 5;
   /// size of a FITS header block (room for 36 entries, of 80
   /// characters each), in bytes. A FITS header always comes in
   /// multiples of this block.
-  static const int BASE_HEADER_SIZE = 2880;
+  static const int g_BASE_HEADER_SIZE = 2880;
 
   // names for several options that can be given in a "FITS" header
   // setup file
-  static const std::string m_BIT_DEPTH_NAME;
-  static const std::string m_AXIS_NAMES_NAME;
-  static const std::string m_ROTATION_NAME;
-  static const std::string m_IMAGE_KEY_NAME;
-  static const std::string m_HEADER_MAP_NAME;
+  static const std::string g_BIT_DEPTH_NAME;
+  static const std::string g_AXIS_NAMES_NAME;
+  static const std::string g_ROTATION_NAME;
+  static const std::string g_IMAGE_KEY_NAME;
+  static const std::string g_HEADER_MAP_NAME;
 };
 
 } // namespace DataHandling
diff --git a/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/LoadISISNexus2.h b/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/LoadISISNexus2.h
index d36c8c4739622875c8e999bdaec1fe98471089bc..23b71e349baa562e045e1da78241fefde1189544 100644
--- a/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/LoadISISNexus2.h
+++ b/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/LoadISISNexus2.h
@@ -233,7 +233,9 @@ private:
   static double dblSqrt(double in);
 
   // C++ interface to the NXS file
+  // clang-format off
   boost::scoped_ptr< ::NeXus::File> m_cppFile;
+  // clang-format on
 
   bool findSpectraDetRangeInFile(
       NeXus::NXEntry &entry, boost::shared_array<int> &spectrum_index,
diff --git a/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/LoadMuonNexus1.h b/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/LoadMuonNexus1.h
index d12b524dcaa8714baeddd935d61e0435da62c249..7baed71cc58d3020820f5e547f72b395fa10a4ed 100644
--- a/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/LoadMuonNexus1.h
+++ b/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/LoadMuonNexus1.h
@@ -106,6 +106,7 @@ private:
   void runLoadMappingTable(DataObjects::Workspace2D_sptr);
   void runLoadLog(DataObjects::Workspace2D_sptr);
   void loadRunDetails(DataObjects::Workspace2D_sptr localWorkspace);
+  void addPeriodLog(DataObjects::Workspace2D_sptr localWorkspace, int64_t period);
 
   /// Loads dead time table for the detector
   void loadDeadTimes(Mantid::NeXus::NXRoot &root);
diff --git a/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/LoadNexusMonitors.h b/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/LoadNexusMonitors.h
index 61fc044f5bb3b2131e8d5255cf199f16631a91f0..4d2fb2d8cee94871611ad9febb313c67bee14009 100644
--- a/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/LoadNexusMonitors.h
+++ b/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/LoadNexusMonitors.h
@@ -80,6 +80,9 @@ private:
   /// is it possible to open the file?
   bool canOpenAsNeXus(const std::string &fname);
 
+  /// split multi period histogram workspace into a workspace group
+  void splitMutiPeriodHistrogramData(const size_t numPeriods);
+
   /// The name and path of the input file
   std::string filename;
   /// The workspace being filled out
diff --git a/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/SaveNXSPE.h b/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/SaveNXSPE.h
index aeb0d48031b2ce93f4dcc307016f6fad0d01531d..1df805df1501cfcc3c9b8cd8e87c898720115f40 100644
--- a/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/SaveNXSPE.h
+++ b/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/SaveNXSPE.h
@@ -5,13 +5,6 @@
 // Includes
 //---------------------------------------------------
 #include "MantidAPI/Algorithm.h"
-#include "MantidNexus/NexusClasses.h"
-#include "MantidAPI/MatrixWorkspace.h"
-#include "MantidAPI/Sample.h"
-#include "MantidDataObjects/Workspace2D.h"
-#include "MantidDataObjects/EventWorkspace.h"
-#include <nexus/NeXusFile.hpp>
-#include <nexus/NeXusException.hpp>
 
 namespace Mantid {
 namespace DataHandling {
@@ -19,14 +12,6 @@ namespace DataHandling {
 /**
  * Saves a workspace into a NeXus/HDF5 NXSPE file.
  *
- * Required properties:
- * <ul>
- * <li> InputWorkspace - The workspace to save. </li>
- * <li> Filename - The filename for output </li>
- * </ul>
- *
- * @author Stuart Campbell, NScD, Oak Ridge National Laboratory
- * @date 28/10/2010
  *
  * This file is part of Mantid.
  *
@@ -73,12 +58,6 @@ private:
   /// Execution code
   void exec();
 
-  /// the number of bins in each histogram, as the histogram must have common
-  /// bins this shouldn't change
-  size_t nBins;
-  /// The filename of the output file
-  std::string filename;
-
   // Some constants to be written for masked values.
   /// Value for data if pixel is masked
   static const double MASK_FLAG;
@@ -86,6 +65,8 @@ private:
   static const double MASK_ERROR;
   /// file format version
   static const std::string NXSPE_VER;
+  /// The size in bytes of a chunk to accumulate to write to the file at once
+  static const size_t MAX_CHUNK_SIZE;
 };
 
 } // namespace DataHandling
diff --git a/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/SaveNXTomo.h b/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/SaveNXTomo.h
index 772f97c030611d85c57553d084a7fa35f6fff496..2144bc53f8ae131c369c412d3a982fcb4131c0f7 100644
--- a/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/SaveNXTomo.h
+++ b/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/SaveNXTomo.h
@@ -65,17 +65,16 @@ public:
 
   /// Algorithm's category for identification
   virtual const std::string category() const {
-    return "DataHandling\\Nexus;DataHandling\\Tomo;Diffraction";
+    return "DataHandling\\Nexus;DataHandling\\Tomography;Diffraction";
   }
 
-  /// Run instead of exec when operating on groups
-  bool processGroups();
-
 private:
   /// Initialisation code
   void init();
   /// Execution code : Single workspace
   void exec();
+  /// Alternative execution code when operating on a WorkspaceGroup
+  bool processGroups();
 
   /// Creates the format for the output file if it doesn't exist
   ::NeXus::File setupFile();
diff --git a/Code/Mantid/Framework/DataHandling/src/DownloadFile.cpp b/Code/Mantid/Framework/DataHandling/src/DownloadFile.cpp
index 6376bf2b58cea5fa5b4e73b1233683f9533ee3bf..1ba943f92e41bc71ba900e21f1a1184d3c51186a 100644
--- a/Code/Mantid/Framework/DataHandling/src/DownloadFile.cpp
+++ b/Code/Mantid/Framework/DataHandling/src/DownloadFile.cpp
@@ -56,8 +56,7 @@ const std::string DownloadFile::summary() const {
 void DownloadFile::init() {
   declareProperty("Address", "",
                   boost::make_shared<MandatoryValidator<std::string>>(),
-                  "The address of the network resource to download. This "
-                  "should start http:// or https:// .",
+                  "The address of the network resource to download.",
                   Direction::InOut);
   declareProperty(new FileProperty("Filename", "", FileProperty::Save),
                   "The filename to save the download to.");
@@ -83,4 +82,4 @@ void DownloadFile::exec() {
 }
 
 } // namespace DataHandling
-} // namespace Mantid
\ No newline at end of file
+} // namespace Mantid
diff --git a/Code/Mantid/Framework/DataHandling/src/ISISRunLogs.cpp b/Code/Mantid/Framework/DataHandling/src/ISISRunLogs.cpp
index df6ad62377d4be85d4f684d9414256acf43b5e52..5502c31b438857fe7263e889effb98a5935478e4 100644
--- a/Code/Mantid/Framework/DataHandling/src/ISISRunLogs.cpp
+++ b/Code/Mantid/Framework/DataHandling/src/ISISRunLogs.cpp
@@ -86,5 +86,14 @@ void ISISRunLogs::addPeriodLogs(const int period, API::Run &exptRun) {
   }
 }
 
+/**
+ * Add the period log to a run.
+ * @param period :: A period number.
+ * @param exptRun :: The run to add the log to.
+ */
+void ISISRunLogs::addPeriodLog(const int period, API::Run &exptRun) {
+  exptRun.addLogData(m_logParser->createPeriodLog(period));
+}
+
 } // namespace DataHandling
 } // namespace Mantid
diff --git a/Code/Mantid/Framework/DataHandling/src/LoadEventNexus.cpp b/Code/Mantid/Framework/DataHandling/src/LoadEventNexus.cpp
index 3af9cf516d245aac17cbfa9735c6e9e40482ba3c..16e56ec9f5e7e2a614f5b250fe5d97a2f55553f0 100644
--- a/Code/Mantid/Framework/DataHandling/src/LoadEventNexus.cpp
+++ b/Code/Mantid/Framework/DataHandling/src/LoadEventNexus.cpp
@@ -5,6 +5,7 @@
 
 #include <boost/random/mersenne_twister.hpp>
 #include <boost/random/uniform_real.hpp>
+#include <boost/shared_ptr.hpp>
 #include <boost/shared_array.hpp>
 
 #include "MantidKernel/ArrayProperty.h"
@@ -2365,16 +2366,37 @@ void LoadEventNexus::runLoadMonitors() {
     loadMonitors->setPropertyValue("MonitorsAsEvents",
                                    this->getProperty("MonitorsAsEvents"));
     loadMonitors->execute();
-    MatrixWorkspace_sptr mons = loadMonitors->getProperty("OutputWorkspace");
-    this->declareProperty(new WorkspaceProperty<>("MonitorWorkspace",
-                                                  mon_wsname,
-                                                  Direction::Output),
-                          "Monitors from the Event NeXus file");
-    this->setProperty("MonitorWorkspace", mons);
-    // Set the internal monitor workspace pointer as well
-    WS->setMonitorWorkspace(mons);
-
-    filterDuringPause(mons);
+    Workspace_sptr monsOut = loadMonitors->getProperty("OutputWorkspace");
+    this->declareProperty(new WorkspaceProperty<Workspace>("MonitorWorkspace",
+                                                    mon_wsname,
+                                                    Direction::Output),
+                            "Monitors from the Event NeXus file");
+    this->setProperty("MonitorWorkspace", monsOut);
+    //The output will either be a group workspace or a matrix workspace
+    MatrixWorkspace_sptr mons = boost::dynamic_pointer_cast<MatrixWorkspace>(monsOut);
+    if (mons) {
+      // Set the internal monitor workspace pointer as well
+      WS->setMonitorWorkspace(mons);
+
+      filterDuringPause(mons);
+    } else {
+      WorkspaceGroup_sptr monsGrp = boost::dynamic_pointer_cast<WorkspaceGroup>(monsOut);
+      if (monsGrp) {
+        //declare a property for each member of the group
+        for (int i = 0; i < monsGrp->getNumberOfEntries(); i++)
+        {
+          std::stringstream ssWsName;
+          ssWsName << mon_wsname << "_" << i+1;    
+          std::stringstream ssPropName;
+          ssPropName << "MonitorWorkspace" << "_" << i+1;
+          this->declareProperty(new WorkspaceProperty<MatrixWorkspace>(ssPropName.str(),
+                                                      ssWsName.str(),
+                                                      Direction::Output),
+                              "Monitors from the Event NeXus file");
+          this->setProperty(ssPropName.str(), monsGrp->getItem(i));
+        }
+      }
+    }
   } catch (...) {
     g_log.error("Error while loading the monitors from the file. File may "
                 "contain no monitors.");
diff --git a/Code/Mantid/Framework/DataHandling/src/LoadFITS.cpp b/Code/Mantid/Framework/DataHandling/src/LoadFITS.cpp
index d717eb0f547ce0c99ac9ec4d21fb0d8f87e4006f..19de2c253b74c8db162ca08f49d10e546b81908e 100644
--- a/Code/Mantid/Framework/DataHandling/src/LoadFITS.cpp
+++ b/Code/Mantid/Framework/DataHandling/src/LoadFITS.cpp
@@ -1,15 +1,17 @@
-#include "MantidAPI/MultipleFileProperty.h"
 #include "MantidAPI/FileProperty.h"
+#include "MantidAPI/MultipleFileProperty.h"
+#include "MantidAPI/NumericAxis.h"
 #include "MantidAPI/RegisterFileLoader.h"
 #include "MantidDataHandling/LoadFITS.h"
 #include "MantidDataObjects/Workspace2D.h"
+#include "MantidKernel/BoundedValidator.h"
 #include "MantidKernel/UnitFactory.h"
 
 #include <boost/algorithm/string.hpp>
+
 #include <Poco/BinaryReader.h>
 #include <Poco/FileStream.h>
 
-
 using namespace Mantid::DataHandling;
 using namespace Mantid::DataObjects;
 using namespace Mantid::API;
@@ -24,13 +26,13 @@ namespace DataHandling {
 // Register the algorithm into the AlgorithmFactory
 DECLARE_FILELOADER_ALGORITHM(LoadFITS)
 
-const std::string LoadFITS::m_BIT_DEPTH_NAME = "BitDepthName";
-const std::string LoadFITS::m_ROTATION_NAME = "RotationName";
-const std::string LoadFITS::m_AXIS_NAMES_NAME = "AxisNames";
-const std::string LoadFITS::m_IMAGE_KEY_NAME = "ImageKeyName";
-const std::string LoadFITS::m_HEADER_MAP_NAME = "HeaderMapFile";
+const std::string LoadFITS::g_BIT_DEPTH_NAME = "BitDepthName";
+const std::string LoadFITS::g_ROTATION_NAME = "RotationName";
+const std::string LoadFITS::g_AXIS_NAMES_NAME = "AxisNames";
+const std::string LoadFITS::g_IMAGE_KEY_NAME = "ImageKeyName";
+const std::string LoadFITS::g_HEADER_MAP_NAME = "HeaderMapFile";
 
-const std::string LoadFITS::m_defaultImgType = "SAMPLE";
+const std::string LoadFITS::g_defaultImgType = "SAMPLE";
 
 /**
  * Constructor. Just initialize everything to prevent issues.
@@ -38,7 +40,8 @@ const std::string LoadFITS::m_defaultImgType = "SAMPLE";
 LoadFITS::LoadFITS()
     : m_headerScaleKey(), m_headerOffsetKey(), m_headerBitDepthKey(),
       m_headerRotationKey(), m_headerImageKeyKey(), m_headerAxisNameKeys(),
-      m_mapFile(), m_baseName(), m_spectraCount(0), m_progress(NULL) {
+      m_mapFile(), m_baseName(), m_pixelCount(0), m_rebin(1),
+      m_noiseThresh(0.0), m_progress(NULL) {
   setupDefaultKeywordNames();
 }
 
@@ -99,14 +102,37 @@ void LoadFITS::init() {
   exts2.push_back(".*");
 
   declareProperty(new MultipleFileProperty("Filename", exts),
-                  "The name of the input file (you can give "
+                  "The name of the input file (note that you can give "
                   "multiple file names separated by commas).");
 
   declareProperty(new API::WorkspaceProperty<API::Workspace>(
       "OutputWorkspace", "", Kernel::Direction::Output));
 
   declareProperty(
-      new FileProperty(m_HEADER_MAP_NAME, "", FileProperty::OptionalDirectory,
+      new Kernel::PropertyWithValue<bool>("LoadAsRectImg", false,
+                                          Kernel::Direction::Input),
+      "If enabled (not by default), the output Workspace2D will have "
+      "one histogram per row and one bin per pixel, such that a 2D "
+      "color plot (color fill plot) will display an image.");
+
+  auto zeroOrPosDbl = boost::make_shared<BoundedValidator<double>>();
+  zeroOrPosDbl->setLower(0.0);
+  declareProperty("FilterNoiseLevel", 0.0, zeroOrPosDbl,
+                  "Threshold to remove noisy pixels. Try 50 for example.");
+
+  auto posInt = boost::make_shared<BoundedValidator<int>>();
+  posInt->setLower(1);
+  declareProperty("BinSize", 1, posInt,
+                  "Rebunch n*n on both axes, generating pixels with sums of "
+                  "blocks of n by n original pixels.");
+
+  auto posDbl = boost::make_shared<BoundedValidator<double>>();
+  posDbl->setLower(std::numeric_limits<double>::epsilon());
+  declareProperty("Scale", 80.0, posDbl, "Pixels per cm.",
+                  Kernel::Direction::Input);
+
+  declareProperty(
+      new FileProperty(g_HEADER_MAP_NAME, "", FileProperty::OptionalDirectory,
                        "", Kernel::Direction::Input),
       "A file mapping header key names to non-standard names [line separated "
       "values in the format KEY=VALUE, e.g. BitDepthName=BITPIX] - do not use "
@@ -120,39 +146,68 @@ void LoadFITS::exec() {
   // for non-standard headers, by default won't do anything
   mapHeaderKeys();
 
-  string fName = getPropertyValue("Filename");
-
+  std::string fName = getPropertyValue("Filename");
   std::vector<std::string> paths;
   boost::split(paths, fName, boost::is_any_of(","));
-  doLoadFiles(paths);
+
+  m_rebin = getProperty("BinSize");
+  m_noiseThresh = getProperty("FilterNoiseLevel");
+  bool loadAsRectImg = getProperty("LoadAsRectImg");
+  const std::string outWSName = getPropertyValue("OutputWorkspace");
+
+  doLoadFiles(paths, outWSName, loadAsRectImg);
 }
 
 /**
  * Create FITS file information for each file selected. Loads headers
- * and data from the files and fills the output workspace(s).
+ * and data from the files and creates and fills the output
+ * workspace(s).
  *
  * @param paths File names as given in the algorithm input property
+ *
+ * @param outWSName name of the output (group) workspace to create
+ *
+ * @param loadAsRectImg Load files with 1 spectrum per row and 1 bin
+ * per column, so a color fill plot displays the image
+ *
+ * @throw std::runtime_error when load fails (for example a memory
+ * allocation issue, wrong rebin requested, etc.)
  */
-void LoadFITS::doLoadFiles(const std::vector<std::string> &paths) {
+void LoadFITS::doLoadFiles(const std::vector<std::string> &paths,
+                           const std::string &outWSName, bool loadAsRectImg) {
   std::vector<FITSInfo> headers;
 
   doLoadHeaders(paths, headers);
 
   // No extension is set -> it's the standard format which we can parse.
   if (headers[0].numberOfAxis > 0)
-    m_spectraCount += headers[0].axisPixelLengths[0];
+    m_pixelCount += headers[0].axisPixelLengths[0];
 
   // Presumably 2 axis, but futureproofing.
   for (int i = 1; i < headers[0].numberOfAxis; ++i) {
-    m_spectraCount *= headers[0].axisPixelLengths[i];
+    m_pixelCount *= headers[0].axisPixelLengths[i];
   }
 
-  MantidImage imageY(headers[0].axisPixelLengths[0],
-                     vector<double>(headers[0].axisPixelLengths[1]));
-  MantidImage imageE(headers[0].axisPixelLengths[0],
-                     vector<double>(headers[0].axisPixelLengths[1]));
+  // Check consistency of m_rebin asap
+  for (int i = 0; i < headers[0].numberOfAxis; ++i) {
+    if (0 != (headers[0].axisPixelLengths[i] % m_rebin)) {
+      throw std::runtime_error(
+          "Cannot rebin this image in blocks of " +
+          boost::lexical_cast<std::string>(m_rebin) + " x " +
+          boost::lexical_cast<std::string>(m_rebin) +
+          " pixels as requested because the size of dimension " +
+          boost::lexical_cast<std::string>(i + 1) + " (" +
+          boost::lexical_cast<std::string>(headers[0].axisPixelLengths[i]) +
+          ") is not a multiple of the bin size.");
+    }
+  }
 
-  size_t bytes = (headers[0].bitsPerPixel / 8) * m_spectraCount;
+  MantidImage imageY(headers[0].axisPixelLengths[1],
+                     vector<double>(headers[0].axisPixelLengths[0]));
+  MantidImage imageE(headers[0].axisPixelLengths[1],
+                     vector<double>(headers[0].axisPixelLengths[0]));
+
+  size_t bytes = (headers[0].bitsPerPixel / 8) * m_pixelCount;
   std::vector<char> buffer;
   try {
     buffer.resize(bytes);
@@ -164,7 +219,7 @@ void LoadFITS::doLoadFiles(const std::vector<std::string> &paths) {
 
   // Create a group for these new workspaces, if the group already exists, add
   // to it.
-  string groupName = getPropertyValue("OutputWorkspace");
+  string groupName = outWSName;
 
   // This forms the name of the group
   m_baseName = getPropertyValue("OutputWorkspace") + "_";
@@ -193,28 +248,36 @@ void LoadFITS::doLoadFiles(const std::vector<std::string> &paths) {
   // a template for creating others
   Workspace2D_sptr latestWS;
   latestWS = makeWorkspace(headers[0], fileNumberInGroup, buffer, imageY,
-                           imageE, latestWS);
+                           imageE, latestWS, loadAsRectImg);
 
-  map<size_t, Workspace2D_sptr> wsOrdered;
+  std::map<size_t, Workspace2D_sptr> wsOrdered;
   wsOrdered[0] = latestWS;
-  try {
-    IAlgorithm_sptr loadInst = createChildAlgorithm("LoadInstrument");
-    std::string directoryName =
-        Kernel::ConfigService::Instance().getInstrumentDirectory();
-    directoryName = directoryName + "/IMAT_Definition.xml";
-    loadInst->setPropertyValue("Filename", directoryName);
-    loadInst->setProperty<MatrixWorkspace_sptr>(
-        "Workspace", dynamic_pointer_cast<MatrixWorkspace>(latestWS));
-    loadInst->execute();
-  } catch (std::exception &ex) {
-    g_log.information("Cannot load the instrument definition. " +
-                      string(ex.what()));
+
+  if (isInstrOtherThanIMAT(headers[0])) {
+    // For now we assume IMAT except when specific headers are found by
+    // isInstrOtherThanIMAT()
+    //
+    // TODO: do this conditional on INSTR='IMAT' when we have proper IMAT .fits
+    // files
+    try {
+      IAlgorithm_sptr loadInst = createChildAlgorithm("LoadInstrument");
+      std::string directoryName =
+          Kernel::ConfigService::Instance().getInstrumentDirectory();
+      directoryName = directoryName + "/IMAT_Definition.xml";
+      loadInst->setPropertyValue("Filename", directoryName);
+      loadInst->setProperty<MatrixWorkspace_sptr>(
+          "Workspace", dynamic_pointer_cast<MatrixWorkspace>(latestWS));
+      loadInst->execute();
+    } catch (std::exception &ex) {
+      g_log.information("Cannot load the instrument definition. " +
+                        string(ex.what()));
+    }
   }
 
   PARALLEL_FOR_NO_WSP_CHECK()
   for (int64_t i = 1; i < static_cast<int64_t>(headers.size()); ++i) {
     latestWS = makeWorkspace(headers[i], fileNumberInGroup, buffer, imageY,
-                             imageE, latestWS);
+                             imageE, latestWS, loadAsRectImg);
     wsOrdered[i] = latestWS;
   }
 
@@ -244,7 +307,8 @@ void LoadFITS::doLoadHeaders(const std::vector<std::string> &paths,
   for (size_t i = 0; i < paths.size(); ++i) {
     headers[i].extension = "";
     headers[i].filePath = paths[i];
-    // Get various pieces of information from the file header which are used to
+    // Get various pieces of information from the file header which are used
+    // to
     // create the workspace
     try {
       parseHeader(headers[i]);
@@ -262,7 +326,7 @@ void LoadFITS::doLoadHeaders(const std::vector<std::string> &paths,
     // needed to know how to load the data: BITPIX, NAXIS, NAXISi (where i =
     // 1..NAXIS, e.g. NAXIS2 for two axis).
     try {
-      string tmpBitPix = headers[i].headerKeys[m_headerBitDepthKey];
+      std::string tmpBitPix = headers[i].headerKeys[m_headerBitDepthKey];
       if (boost::contains(tmpBitPix, "-")) {
         boost::erase_all(tmpBitPix, "-");
         headers[i].isFloat = true;
@@ -270,7 +334,13 @@ void LoadFITS::doLoadHeaders(const std::vector<std::string> &paths,
         headers[i].isFloat = false;
       }
 
-      headers[i].bitsPerPixel = lexical_cast<int>(tmpBitPix);
+      try {
+        headers[i].bitsPerPixel = lexical_cast<int>(tmpBitPix);
+      } catch (std::exception &e) {
+        throw std::runtime_error(
+            "Coult not interpret the entry number of bits per pixel (" +
+            m_headerBitDepthKey + ") as an integer. Error: " + e.what());
+      }
       // Check that the files use bit depths of either 8, 16 or 32
       if (headers[i].bitsPerPixel != 8 && headers[i].bitsPerPixel != 16 &&
           headers[i].bitsPerPixel != 32 && headers[i].bitsPerPixel != 64)
@@ -293,7 +363,7 @@ void LoadFITS::doLoadHeaders(const std::vector<std::string> &paths,
       if (headers[i].headerKeys.end() != it) {
         headers[i].imageKey = it->second;
       } else {
-        headers[i].imageKey = m_defaultImgType;
+        headers[i].imageKey = g_defaultImgType;
       }
     } catch (std::exception &e) {
       throw std::runtime_error("Failed to process the '" + m_headerImageKeyKey +
@@ -308,6 +378,9 @@ void LoadFITS::doLoadHeaders(const std::vector<std::string> &paths,
       for (int j = 0; headers.size() > i && j < headers[i].numberOfAxis; ++j) {
         headers[i].axisPixelLengths.push_back(lexical_cast<size_t>(
             headers[i].headerKeys[m_headerAxisNameKeys[j]]));
+        g_log.information()
+            << "Found axis length header entry: " << m_headerAxisNameKeys[j]
+            << " = " << headers[i].axisPixelLengths.back() << std::endl;
       }
 
       // Various extensions to the FITS format are used elsewhere, and
@@ -321,14 +394,59 @@ void LoadFITS::doLoadHeaders(const std::vector<std::string> &paths,
           ". Error description: " + e.what());
     }
 
-    headers[i].scale =
-        (headers[i].headerKeys[m_headerScaleKey] == "")
-            ? 1
-            : lexical_cast<double>(headers[i].headerKeys[m_headerScaleKey]);
-    headers[i].offset =
-        (headers[i].headerKeys[m_headerOffsetKey] == "")
-            ? 0
-            : lexical_cast<int>(headers[i].headerKeys[m_headerOffsetKey]);
+    // scale parameter, header BSCALE in the fits standard
+    if ("" == headers[i].headerKeys[m_headerScaleKey]) {
+      headers[i].scale = 1;
+    } else {
+      try {
+        headers[i].scale =
+            lexical_cast<double>(headers[i].headerKeys[m_headerScaleKey]);
+      } catch (std::exception &e) {
+        throw std::runtime_error(
+            "Coult not interpret the entry number of bits per pixel (" +
+            m_headerBitDepthKey + " = " +
+            headers[i].headerKeys[m_headerScaleKey] +
+            ") as a floating point number (double). Error: " + e.what());
+      }
+    }
+
+    // data offsset parameter, header BZERO in the fits standard
+    if ("" == headers[i].headerKeys[m_headerOffsetKey]) {
+      headers[i].offset = 0;
+    } else {
+      try {
+        headers[i].offset =
+            lexical_cast<int>(headers[i].headerKeys[m_headerOffsetKey]);
+      } catch (std::exception & /*e*/) {
+        // still, second try with floating point format (as used for example
+        // by
+        // Starlight XPRESS cameras)
+        try {
+          double doff =
+              lexical_cast<double>(headers[i].headerKeys[m_headerOffsetKey]);
+          double intPart;
+          if (0 != modf(doff, &intPart)) {
+            // anyway we'll do a cast, but warn if there was a fraction
+            g_log.warning()
+                << "The value given in the FITS header entry for the data "
+                   "offset (" +
+                       m_headerOffsetKey + " = " +
+                       headers[i].headerKeys[m_headerOffsetKey] +
+                       ") has a fractional part, and it will be ignored!"
+                << std::endl;
+          }
+          headers[i].offset = static_cast<int>(doff);
+        } catch (std::exception &e) {
+          throw std::runtime_error(
+              "Coult not interpret the entry number of data offset (" +
+              m_headerOffsetKey + " = " +
+              headers[i].headerKeys[m_headerOffsetKey] +
+              ") as an integer number nor a floating point "
+              "number (double). Error: " +
+              e.what());
+        }
+      }
+    }
 
     // Check each header is valid/supported: standard (no extension to
     // FITS), and has two axis
@@ -400,34 +518,116 @@ void LoadFITS::parseHeader(FITSInfo &headerInfo) {
  * @param buffer pre-allocated buffer to contain data values
  * @param imageY Object to set the Y data values in
  * @param imageE Object to set the E data values in
+ *
  * @param parent A workspace which can be used to copy initialisation
  * information from (size/instrument def etc)
  *
+ * @param loadAsRectImg if true, the new workspace will have one
+ * spectrum per row and one bin per column, instead of the (default)
+ * as many spectra as pixels.
+ *
  * @returns A newly created Workspace2D, as a shared pointer
  */
 Workspace2D_sptr
 LoadFITS::makeWorkspace(const FITSInfo &fileInfo, size_t &newFileNumber,
                         std::vector<char> &buffer, MantidImage &imageY,
-                        MantidImage &imageE, const Workspace2D_sptr parent) {
+                        MantidImage &imageE, const Workspace2D_sptr parent,
+                        bool loadAsRectImg) {
+
+  string currNumberS = padZeros(newFileNumber, g_DIGIT_SIZE_APPEND);
+  ++newFileNumber;
+
+  string baseName = m_baseName + currNumberS;
+
+  // set data
+  readDataToImgs(fileInfo, imageY, imageE, buffer);
+
   // Create ws
   Workspace2D_sptr ws;
   if (!parent) {
-    ws = dynamic_pointer_cast<Workspace2D>(WorkspaceFactory::Instance().create(
-        "Workspace2D", m_spectraCount, 2, 1));
+    if (!loadAsRectImg) {
+      size_t finalPixelCount = m_pixelCount / m_rebin * m_rebin;
+      ws =
+          dynamic_pointer_cast<Workspace2D>(WorkspaceFactory::Instance().create(
+              "Workspace2D", finalPixelCount, 2, 1));
+    } else {
+      ws =
+          dynamic_pointer_cast<Workspace2D>(WorkspaceFactory::Instance().create(
+              "Workspace2D",
+              fileInfo.axisPixelLengths[1] / m_rebin, // one bin per column
+              fileInfo.axisPixelLengths[0] / m_rebin +
+                  1, // one spectrum per row
+              fileInfo.axisPixelLengths[0] / m_rebin));
+    }
   } else {
     ws = dynamic_pointer_cast<Workspace2D>(
         WorkspaceFactory::Instance().create(parent));
   }
 
-  string currNumberS = padZeros(newFileNumber, DIGIT_SIZE_APPEND);
-  ++newFileNumber;
+  doFilterNoise(m_noiseThresh, imageY, imageE);
 
-  string baseName = m_baseName + currNumberS;
+  // this pixel scale property is used to set the workspace X values
+  double cm_1 = getProperty("Scale");
+  // amount of width units (e.g. cm) per pixel
+  double cmpp = 1; // cm per pixel == bin width
+  if (0.0 != cm_1)
+    cmpp /= cm_1;
+  cmpp *= static_cast<double>(m_rebin);
+
+  // Set in WS
+  // Note this can change the sizes of the images and the number of pixels
+  if (1 == m_rebin) {
+    ws->setImageYAndE(imageY, imageE, 0, loadAsRectImg, cmpp,
+                      false /* no parallel load */);
+  } else {
+    MantidImage rebinnedY(imageY.size() / m_rebin,
+                          std::vector<double>(imageY[0].size() / m_rebin));
+    MantidImage rebinnedE(imageE.size() / m_rebin,
+                          std::vector<double>(imageE[0].size() / m_rebin));
+
+    doRebin(m_rebin, imageY, imageE, rebinnedY, rebinnedE);
+    ws->setImageYAndE(rebinnedY, rebinnedE, 0, loadAsRectImg, cmpp,
+                      false /* no parallel load */);
+  }
 
   ws->setTitle(baseName);
 
-  // set data
-  readDataToWorkspace2D(ws, fileInfo, imageY, imageE, buffer);
+  // add axes
+  size_t width = fileInfo.axisPixelLengths[0] / m_rebin;
+  size_t height = fileInfo.axisPixelLengths[1] / m_rebin;
+  if (loadAsRectImg) {
+    // width/X axis
+    auto axw = new Mantid::API::NumericAxis(width + 1);
+    axw->title() = "width";
+    for (size_t i = 0; i < width + 1; i++) {
+      axw->setValue(i, static_cast<double>(i) * cmpp);
+    }
+    ws->replaceAxis(0, axw);
+    // "cm" width label unit
+    boost::shared_ptr<Kernel::Units::Label> unitLbl =
+        boost::dynamic_pointer_cast<Kernel::Units::Label>(
+            UnitFactory::Instance().create("Label"));
+    unitLbl->setLabel("width", "cm");
+    ws->getAxis(0)->unit() = unitLbl;
+
+    // height/Y axis
+    auto axh = new Mantid::API::NumericAxis(height);
+    axh->title() = "height";
+    for (size_t i = 0; i < height; i++) {
+      axh->setValue(i, static_cast<double>(i) * cmpp);
+    }
+    ws->replaceAxis(1, axh);
+    // "cm" height label unit
+    unitLbl = boost::dynamic_pointer_cast<Kernel::Units::Label>(
+        UnitFactory::Instance().create("Label"));
+    unitLbl->setLabel("height", "cm");
+    ws->getAxis(1)->unit() = unitLbl;
+
+    ws->isDistribution(true);
+  } else {
+    // TODO: what to do when loading 1pixel - 1 spectrum?
+  }
+  ws->setYUnitLabel("brightness");
 
   // Add all header info to log.
   for (auto it = fileInfo.headerKeys.begin(); it != fileInfo.headerKeys.end();
@@ -467,26 +667,23 @@ LoadFITS::makeWorkspace(const FITSInfo &fileInfo, size_t &newFileNumber,
 }
 
 /**
- * Reads the data (matrix) from a single FITS file into a workspace
+ * Reads the data (matrix) from a single FITS file into image objects.
  *
- * @param ws Workspace to populate with the data
- * @param fileInfo information pertaining to the FITS file to load
+ * @param fileInfo information on the FITS file to load, including its path
  * @param imageY Object to set the Y data values in
  * @param imageE Object to set the E data values in
  * @param buffer pre-allocated buffer to contain data values
  *
  * @throws std::runtime_error if there are file input issues
  */
-void LoadFITS::readDataToWorkspace2D(Workspace2D_sptr ws,
-                                     const FITSInfo &fileInfo,
-                                     MantidImage &imageY, MantidImage &imageE,
-                                     std::vector<char> &buffer) {
+void LoadFITS::readDataToImgs(const FITSInfo &fileInfo, MantidImage &imageY,
+                              MantidImage &imageE, std::vector<char> &buffer) {
   std::string filename = fileInfo.filePath;
   Poco::FileStream file(filename, std::ios::in);
 
   size_t bytespp = (fileInfo.bitsPerPixel / 8);
-  size_t len = m_spectraCount * bytespp;
-  file.seekg(BASE_HEADER_SIZE * fileInfo.headerSizeMultiplier);
+  size_t len = m_pixelCount * bytespp;
+  file.seekg(g_BASE_HEADER_SIZE * fileInfo.headerSizeMultiplier);
   file.read(&buffer[0], len);
   if (!file) {
     throw std::runtime_error(
@@ -504,8 +701,8 @@ void LoadFITS::readDataToWorkspace2D(Workspace2D_sptr ws,
   std::vector<char> buf(bytespp);
   char *tmp = &buf.front();
   size_t start = 0;
-  for (size_t i = 0; i < fileInfo.axisPixelLengths[0]; ++i) {
-    for (size_t j = 0; j < fileInfo.axisPixelLengths[1]; ++j) {
+  for (size_t i = 0; i < fileInfo.axisPixelLengths[1]; ++i) {   // width
+    for (size_t j = 0; j < fileInfo.axisPixelLengths[0]; ++j) { // height
       // If you wanted to PARALLEL_...ize these loops (which doesn't
       // seem to provide any speed up, you cannot use the
       // start+=bytespp at the end of this loop. You'd need something
@@ -546,9 +743,103 @@ void LoadFITS::readDataToWorkspace2D(Workspace2D_sptr ws,
       start += bytespp;
     }
   }
+}
 
-  // Set in WS
-  ws->setImageYAndE(imageY, imageE, 0, false);
+/**
+ * Apply a simple noise filter by averaging threshold-filtered
+ * neighbor pixels (with 4-neighbohood / 4-connectivity). The
+ * filtering is done in place for both imageY and imageE.
+ *
+ * @param thresh Threshold to apply on pixels
+ * @param imageY raw data (Y values)
+ * @param imageE raw data (E/error values)
+ */
+void LoadFITS::doFilterNoise(double thresh, MantidImage &imageY,
+                             MantidImage &imageE) {
+  if (thresh <= 0.0)
+    return;
+
+  MantidImage goodY = imageY;
+  MantidImage goodE = imageE;
+
+  // TODO: this is not very smart about the edge pixels (leftmost and
+  // rightmost columns, topmost and bottom rows)
+  for (size_t j = 1; j < (imageY.size() - 1); ++j) {
+    for (size_t i = 1; i < (imageY[0].size() - 1); ++i) {
+
+      if (((imageY[j][i] - imageY[j][i - 1]) > thresh) &&
+          ((imageY[j][i] - imageY[j][i + 1]) > thresh) &&
+          ((imageY[j][i] - imageY[j - 1][i]) > thresh) &&
+          ((imageY[j][i] - imageY[j + 1][i]) > thresh))
+        goodY[j][i] = 0;
+      else
+        goodY[j][i] = 1;
+
+      if (((imageE[j][i] - imageE[j][i - 1]) > thresh) &&
+          ((imageE[j][i] - imageE[j][i + 1]) > thresh) &&
+          ((imageE[j][i] - imageE[j - 1][i]) > thresh) &&
+          ((imageE[j][i] - imageE[j + 1][i]) > thresh))
+        goodE[j][i] = 0;
+      else
+        goodE[j][i] = 1;
+    }
+  }
+
+  for (size_t j = 1; j < (imageY.size() - 1); ++j) {
+    for (size_t i = 1; i < (imageY[0].size() - 1); ++i) {
+      if (!goodY[j][i]) {
+        if (goodY[j - 1][i] || goodY[j + 1][i] || goodY[j][i - 1] ||
+            goodY[j][i + 1]) {
+          imageY[j][i] = goodY[j - 1][i] * imageY[j - 1][i] +
+                         goodY[j + 1][i] * imageY[j + 1][i] +
+                         goodY[j][i - 1] * imageY[j][i - 1] +
+                         goodY[j][i + 1] * imageY[j][i + 1];
+        }
+      }
+
+      if (!goodE[j][i]) {
+        if (goodE[j - 1][i] || goodE[j + 1][i] || goodE[j][i - 1] ||
+            goodE[j][i + 1]) {
+          imageE[j][i] = goodE[j - 1][i] * imageE[j - 1][i] +
+                         goodE[j + 1][i] * imageE[j + 1][i] +
+                         goodE[j][i - 1] * imageE[j][i - 1] +
+                         goodE[j][i + 1] * imageE[j][i + 1];
+        }
+      }
+    }
+  }
+}
+
+/**
+ * Group pixels in blocks of rebin X rebin.
+ *
+ * @param rebin bin size (n to make blocks of n*n pixels)
+ * @param imageY raw data (Y values)
+ * @param imageE raw data (E/error values)
+ * @param rebinnedY raw data after rebin (Y values)
+ * @param rebinnedE raw data after rebin (E/error values)
+ */
+void LoadFITS::doRebin(size_t rebin, MantidImage &imageY, MantidImage &imageE,
+                       MantidImage &rebinnedY, MantidImage &rebinnedE) {
+  if (1 >= rebin)
+    return;
+
+  for (size_t j = 0; j < (rebinnedY.size() - rebin + 1); ++j) {
+    for (size_t i = 0; i < (rebinnedY[0].size() - rebin + 1); ++i) {
+      double accumY = 0.0;
+      double accumE = 0.0;
+      size_t origJ = j*rebin;
+      size_t origI = i*rebin;
+      for (size_t k = 0; k < rebin; ++k) {
+        for (size_t l = 0; l < rebin; ++l) {
+          accumY += imageY[origJ + k][origI + l];
+          accumE += imageE[origJ + k][origI + l];
+        }
+      }
+      rebinnedY[j][i] = accumY;
+      rebinnedE[j][i] = accumE;
+    }
+  }
 }
 
 /**
@@ -558,7 +849,8 @@ void LoadFITS::readDataToWorkspace2D(Workspace2D_sptr ws,
  *
  * @param hdr FITS header struct loaded from a file - to check
  *
- * @param hdrFirst FITS header struct loaded from a (first) reference file - to
+ * @param hdrFirst FITS header struct loaded from a (first) reference file -
+ *to
  * compare against
  *
  * @throws std::exception if there's any issue or unsupported entry in the
@@ -610,6 +902,39 @@ void LoadFITS::headerSanityCheck(const FITSInfo &hdr,
   }
 }
 
+/**
+ * Looks for headers used by specific instruments/cameras, or finds if
+ * the instrument does not appear to be IMAT, which is the only one
+ * for which we have a camera-instrument definition and because of
+ * that is the only one loaded for the moment.
+ *
+ * @param hdr FITS header information
+ *
+ * @return whether this file seems to come from 'another' camera such
+ * as Starlight Xpress, etc.
+ */
+bool LoadFITS::isInstrOtherThanIMAT(FITSInfo &hdr) {
+  bool res = false;
+
+  // Images taken with Starlight camera contain this header entry:
+  // INSTRUME='Starlight Xpress CCD'
+  auto it = hdr.headerKeys.find("INSTRUME");
+  if (hdr.headerKeys.end() != it && boost::contains(it->second, "Starlight")) {
+    // For now, do nothing, just tell
+    // Cameras used for HiFi and EMU are in principle only used
+    // occasionally for calibration
+    g_log.information()
+        << "Found this in the file headers: " << it->first << " = "
+        << it->second
+        << ". This file seems to come from a Starlight camera, "
+           "as used for calibration of the instruments HiFi and EMU (and"
+           "possibly others). Not "
+           "loading instrument definition." << std::endl;
+  }
+
+  return res;
+}
+
 /**
  * Returns the trailing number from a string minus leading 0's (so 25 from
  * workspace_00025)the confidence with with this algorithm can load the file
@@ -631,10 +956,11 @@ size_t LoadFITS::fetchNumber(const std::string &name) {
 }
 
 /**
- * Adds 0's to the front of a number to create a string of size totalDigitCount
- * including number
+ * Adds 0's to the front of a number to create a string of size
+ * totalDigitCount including number
  *
  * @param number input number to add padding to
+ *
  * @param totalDigitCount width of the resulting string with 0s followed by
  * number
  *
@@ -653,11 +979,11 @@ std::string LoadFITS::padZeros(const size_t number,
  *  Maps the header keys to specified values
  */
 void LoadFITS::mapHeaderKeys() {
-  if ("" == getPropertyValue(m_HEADER_MAP_NAME))
+  if ("" == getPropertyValue(g_HEADER_MAP_NAME))
     return;
 
   // If a map file is selected, use that.
-  std::string name = getPropertyValue(m_HEADER_MAP_NAME);
+  std::string name = getPropertyValue(g_HEADER_MAP_NAME);
   ifstream fStream(name.c_str());
 
   try {
@@ -669,19 +995,19 @@ void LoadFITS::mapHeaderKeys() {
       while (getline(fStream, line)) {
         boost::split(lineSplit, line, boost::is_any_of("="));
 
-        if (lineSplit[0] == m_ROTATION_NAME && lineSplit[1] != "")
+        if (lineSplit[0] == g_ROTATION_NAME && lineSplit[1] != "")
           m_headerRotationKey = lineSplit[1];
 
-        if (lineSplit[0] == m_BIT_DEPTH_NAME && lineSplit[1] != "")
+        if (lineSplit[0] == g_BIT_DEPTH_NAME && lineSplit[1] != "")
           m_headerBitDepthKey = lineSplit[1];
 
-        if (lineSplit[0] == m_AXIS_NAMES_NAME && lineSplit[1] != "") {
+        if (lineSplit[0] == g_AXIS_NAMES_NAME && lineSplit[1] != "") {
           m_headerAxisNameKeys.clear();
           boost::split(m_headerAxisNameKeys, lineSplit[1],
                        boost::is_any_of(","));
         }
 
-        if (lineSplit[0] == m_IMAGE_KEY_NAME && lineSplit[1] != "") {
+        if (lineSplit[0] == g_IMAGE_KEY_NAME && lineSplit[1] != "") {
           m_headerImageKeyKey = lineSplit[1];
         }
       }
diff --git a/Code/Mantid/Framework/DataHandling/src/LoadMuonNexus1.cpp b/Code/Mantid/Framework/DataHandling/src/LoadMuonNexus1.cpp
index 6f59be7278a4eb1fd693a87b332f46917f7f4928..4f8020811e1623acbcc7f1fa237e088ce06c05f4 100644
--- a/Code/Mantid/Framework/DataHandling/src/LoadMuonNexus1.cpp
+++ b/Code/Mantid/Framework/DataHandling/src/LoadMuonNexus1.cpp
@@ -1,11 +1,13 @@
 //----------------------------------------------------------------------
 // Includes
 //----------------------------------------------------------------------
+#include "MantidDataHandling/LoadMuonNexus1.h"
+
 #include "MantidAPI/FileProperty.h"
 #include "MantidAPI/Progress.h"
 #include "MantidAPI/RegisterFileLoader.h"
 #include "MantidAPI/TableRow.h"
-#include "MantidDataHandling/LoadMuonNexus1.h"
+#include "MantidDataHandling/ISISRunLogs.h"
 #include "MantidDataObjects/TableWorkspace.h"
 #include "MantidDataObjects/Workspace2D.h"
 #include "MantidGeometry/Instrument/Detector.h"
@@ -232,6 +234,7 @@ void LoadMuonNexus1::exec() {
       localWorkspace->setTitle(title);
       localWorkspace->setComment(notes);
     }
+    addPeriodLog(localWorkspace,period);
 
     size_t counter = 0;
     for (int64_t i = m_spec_min; i < m_spec_max; ++i) {
@@ -708,6 +711,32 @@ void LoadMuonNexus1::runLoadLog(DataObjects::Workspace2D_sptr localWorkspace) {
   } catch (...) {
     setProperty("MainFieldDirection", "Longitudinal");
   }
+
+  auto &run = localWorkspace->mutableRun();
+  int n = static_cast<int>(m_numberOfPeriods);
+  ISISRunLogs runLogs(run, n);
+  runLogs.addStatusLog(run);
+}
+
+/**
+ * Add the 'period i' log to a workspace.
+ * @param localWorkspace A workspace to add the log to.
+ * @param period A period for this workspace.
+ */
+void LoadMuonNexus1::addPeriodLog(DataObjects::Workspace2D_sptr localWorkspace, int64_t period)
+{
+  auto &run = localWorkspace->mutableRun();
+  int n = static_cast<int>(m_numberOfPeriods);
+  ISISRunLogs runLogs(run, n);
+  if ( period == 0 )
+  {
+    runLogs.addPeriodLogs(1, run);
+  }
+  else
+  {
+    run.removeLogData("period 1");
+    runLogs.addPeriodLog(static_cast<int>(period) + 1, run);
+  }
 }
 
 /**
diff --git a/Code/Mantid/Framework/DataHandling/src/LoadNexusMonitors.cpp b/Code/Mantid/Framework/DataHandling/src/LoadNexusMonitors.cpp
index 7bf7f6bcf216a6de9e91f27126262e4d921bfdbc..fe371b2416c965c6047e17266275b333b746c8c1 100644
--- a/Code/Mantid/Framework/DataHandling/src/LoadNexusMonitors.cpp
+++ b/Code/Mantid/Framework/DataHandling/src/LoadNexusMonitors.cpp
@@ -1,10 +1,11 @@
 #include "MantidDataHandling/LoadNexusMonitors.h"
 #include "MantidDataHandling/LoadEventNexus.h"
+#include "MantidDataHandling/ISISRunLogs.h"
 #include "MantidAPI/FileProperty.h"
+#include "MantidAPI/WorkspaceGroup.h"
 #include "MantidKernel/ConfigService.h"
 #include "MantidKernel/DateAndTime.h"
 #include "MantidKernel/UnitFactory.h"
-
 #include <Poco/File.h>
 #include <Poco/Path.h>
 #include <boost/lexical_cast.hpp>
@@ -15,6 +16,8 @@
 
 using Mantid::DataObjects::EventWorkspace;
 using Mantid::DataObjects::EventWorkspace_sptr;
+using Mantid::API::WorkspaceGroup;
+using Mantid::API::WorkspaceGroup_sptr;
 
 namespace Mantid {
 namespace DataHandling {
@@ -42,7 +45,7 @@ void LoadNexusMonitors::init() {
       "attempt to load. The file extension must either be .nxs or .NXS");
 
   declareProperty(
-      new API::WorkspaceProperty<API::MatrixWorkspace>(
+      new API::WorkspaceProperty<API::Workspace>(
           "OutputWorkspace", "", Kernel::Direction::Output),
       "The name of the output workspace in which to load the NeXus monitors.");
 
@@ -91,6 +94,7 @@ void LoadNexusMonitors::exec() {
   std::vector<std::string> monitorNames;
   size_t numHistMon = 0;
   size_t numEventMon = 0;
+  size_t numPeriods = 0;
   // we want to sort monitors by monitor_number if they are present
   std::map<int, std::string> monitorNumber2Name;
   prog1.report();
@@ -136,6 +140,13 @@ void LoadNexusMonitors::exec() {
           file.closeData();
           monitorNumber2Name[monitorNo] = entry_name;
         }
+        if((numPeriods == 0) && (inner_entries.find("period_index") != inner_entries.end())) {
+          MantidVec period_data;
+          file.openData("period_index");
+          file.getDataCoerce(period_data);
+          file.closeData();
+          numPeriods = period_data.size();
+        }
       }
       file.closeGroup(); // close NXmonitor
     }
@@ -144,8 +155,13 @@ void LoadNexusMonitors::exec() {
   this->nMonitors = monitorNames.size();
 
   // Nothing to do
-  if (0 == nMonitors)
-    return;
+  if (0 == nMonitors) {
+    //previous version just used to return, but that
+    //threw an error when the OutputWorkspace property was not set.
+    //and the error message was confusing.
+    //This has changed to throw a specific error.
+    throw std::invalid_argument(this->filename + " does not contain any monitors");
+  }
 
   // With this property you can make the exception that even if there's event
   // data, monitors will be loaded
@@ -414,10 +430,16 @@ void LoadNexusMonitors::exec() {
     WS->getSpectrum(i)->setSpectrumNo(spectra_numbers[i]);
     WS->getSpectrum(i)->setDetectorID(detector_numbers[i]);
   }
-
   // add filename
   WS->mutableRun().addProperty("Filename", this->filename);
-  this->setProperty("OutputWorkspace", this->WS);
+
+  //if multiperiod histogram data
+  if ((numPeriods > 1) && (!useEventMon)) {
+    splitMutiPeriodHistrogramData(numPeriods);
+  }
+  else {
+    this->setProperty("OutputWorkspace", this->WS);
+  }
 }
 
 /**
@@ -535,5 +557,91 @@ bool LoadNexusMonitors::canOpenAsNeXus(const std::string &fname) {
   return res;
 }
 
+/**
+ * Splits multiperiod histogram data into seperate workspaces and puts them in a group
+ *
+ * @param numPeriods :: number of periods
+ **/
+void LoadNexusMonitors::splitMutiPeriodHistrogramData(const size_t numPeriods) {
+
+  //protection - we should not have entered the routine if these are not true
+  // More than 1 period
+  if (numPeriods < 2) {
+    g_log.warning() << "Attempted to split multiperiod histogram workspace with " 
+      << numPeriods << "periods, aborted." << std::endl;
+    return;
+  }
+
+  // Y array should be divisible by the number of periods
+  if (this->WS->blocksize() % numPeriods != 0) {
+    g_log.warning() << "Attempted to split multiperiod histogram workspace with " 
+      << this->WS->blocksize() << "data entries, into " << numPeriods << "periods." 
+      " Aborted."<< std::endl;
+    return;
+  }
+
+  WorkspaceGroup_sptr wsGroup(new WorkspaceGroup);
+  size_t yLength = this->WS->blocksize() / numPeriods;
+  size_t xLength = yLength + 1;
+  size_t numSpectra = this->WS->getNumberHistograms();
+  ISISRunLogs monLogCreator(this->WS->run(), static_cast<int>(numPeriods));
+  for (size_t i = 0; i < numPeriods; i++)
+  {
+    //create the period workspace
+    API::MatrixWorkspace_sptr wsPeriod = API::WorkspaceFactory::Instance().create(
+      this->WS,
+      numSpectra,
+      xLength,
+      yLength);
+
+    //assign x values - restart at start for all periods
+    for (size_t specIndex = 0; specIndex < numSpectra; specIndex++) {
+      MantidVec& outputVec = wsPeriod->dataX(specIndex);
+      const MantidVec& inputVec = this->WS->readX(specIndex);
+      for (size_t index = 0; index < xLength; index++) {
+        outputVec[index] = inputVec[index];
+      }
+    }
+    
+    //assign y values - use the values offset by the period number
+    for (size_t specIndex = 0; specIndex < numSpectra; specIndex++) {
+      MantidVec& outputVec = wsPeriod->dataY(specIndex);
+      const MantidVec& inputVec = this->WS->readY(specIndex);
+      for (size_t index = 0; index < yLength; index++) {
+        outputVec[index] = inputVec[(yLength * i) + index];
+      }
+    }
+
+    //assign E values
+    for (size_t specIndex = 0; specIndex < numSpectra; specIndex++) {
+      MantidVec& outputVec = wsPeriod->dataE(specIndex);
+      const MantidVec& inputVec = this->WS->readE(specIndex);
+      for (size_t index = 0; index < yLength; index++) {
+        outputVec[index] = inputVec[(yLength * i) + index];
+      }
+    }
+    
+    //add period logs
+    monLogCreator.addPeriodLogs(static_cast<int>(i+1), wsPeriod->mutableRun());
+
+    //add to workspace group
+    wsGroup->addWorkspace(wsPeriod);
+
+    //create additional output workspace property
+    std::stringstream ssWsName;
+    ssWsName << this->WS->name() << "_" << i+1;    
+    std::stringstream ssPropName;
+    ssPropName << "OutputWorkspace" << "_" << i+1;
+    declareProperty(
+      new API::WorkspaceProperty<API::Workspace>(
+          ssPropName.str(), ssWsName.str(), Kernel::Direction::Output),
+      "Additional output workspace for multi period monitors.");
+    setProperty(ssPropName.str(),wsPeriod);
+  }
+
+  // set the output workspace
+  this->setProperty("OutputWorkspace", wsGroup);
+}
+
 } // end DataHandling
 } // end Mantid
diff --git a/Code/Mantid/Framework/DataHandling/src/SaveAscii2.cpp b/Code/Mantid/Framework/DataHandling/src/SaveAscii2.cpp
index cb6390ba3ec65b3f2d3f632a5403fe5cdfc96e91..5969682c41b2adca9816ec3fa27467b19e34c55d 100644
--- a/Code/Mantid/Framework/DataHandling/src/SaveAscii2.cpp
+++ b/Code/Mantid/Framework/DataHandling/src/SaveAscii2.cpp
@@ -117,8 +117,6 @@ void SaveAscii2::exec() {
   m_isHistogram = m_ws->isHistogramData();
   m_isCommonBins = m_ws->isCommonBins(); // checking for ragged workspace
   m_writeID = getProperty("WriteSpectrumID");
-  if (nSpectra != 1)
-    m_writeID = true;
 
   // Get the properties
   std::vector<int> spec_list = getProperty("SpectrumList");
diff --git a/Code/Mantid/Framework/DataHandling/src/SaveMask.cpp b/Code/Mantid/Framework/DataHandling/src/SaveMask.cpp
index 22da9d34e6621d78b9f8dd9f7bd6d1bfd0b84ea0..6100cd482a81e4f00e1a8d4ffe72844f6079df42 100644
--- a/Code/Mantid/Framework/DataHandling/src/SaveMask.cpp
+++ b/Code/Mantid/Framework/DataHandling/src/SaveMask.cpp
@@ -72,7 +72,7 @@ void SaveMask::exec() {
   if (!inpWS) {
     // extract the masking and use that
     Algorithm_sptr emAlg =
-        this->createChildAlgorithm("ExtractMasking", 0.0, 0.5, false);
+        this->createChildAlgorithm("ExtractMask", 0.0, 0.5, false);
     emAlg->setProperty("InputWorkspace", userInputWS);
     emAlg->setPropertyValue("OutputWorkspace", "tmp");
     emAlg->execute();
diff --git a/Code/Mantid/Framework/DataHandling/src/SaveNXSPE.cpp b/Code/Mantid/Framework/DataHandling/src/SaveNXSPE.cpp
index 11f870c3b7daf2cafbafa8a4f46c03f558e1ceea..e07c856189d1a7392aed34a9b1ac945f6799dbb3 100644
--- a/Code/Mantid/Framework/DataHandling/src/SaveNXSPE.cpp
+++ b/Code/Mantid/Framework/DataHandling/src/SaveNXSPE.cpp
@@ -1,13 +1,13 @@
 #include "MantidDataHandling/SaveNXSPE.h"
+
 #include "MantidAPI/FileProperty.h"
-#include "MantidKernel/ConfigService.h"
-#include "MantidKernel/MantidVersion.h"
 #include "MantidAPI/WorkspaceValidators.h"
 #include "MantidAPI/WorkspaceOpOverloads.h"
 #include "MantidGeometry/Instrument/Detector.h"
-#include "MantidGeometry/Instrument/ObjComponent.h"
 #include "MantidDataHandling/FindDetectorsPar.h"
+#include "MantidKernel/MantidVersion.h"
 
+#include <boost/scoped_array.hpp>
 #include <Poco/File.h>
 #include <Poco/Path.h>
 #include <limits>
@@ -26,6 +26,8 @@ const double SaveNXSPE::MASK_ERROR = 0.0;
 // works fine but there were cases that some compilers crush on this (VS2008 in
 // mixed .net environment ?)
 const std::string SaveNXSPE::NXSPE_VER = "1.2";
+// 4MB chunk size
+const size_t SaveNXSPE::MAX_CHUNK_SIZE = 4194304;
 
 SaveNXSPE::SaveNXSPE() : API::Algorithm() {}
 
@@ -71,7 +73,7 @@ void SaveNXSPE::init() {
  */
 void SaveNXSPE::exec() {
   // Retrieve the input workspace
-  const MatrixWorkspace_const_sptr inputWS = getProperty("InputWorkspace");
+  MatrixWorkspace_sptr inputWS = getProperty("InputWorkspace");
 
   // Do the full check for common binning
   if (!WorkspaceHelpers::commonBoundaries(inputWS)) {
@@ -80,22 +82,22 @@ void SaveNXSPE::exec() {
   }
 
   // Number of spectra
-  const int nHist = static_cast<int>(inputWS->getNumberHistograms());
+  const int64_t nHist = static_cast<int64_t>(inputWS->getNumberHistograms());
   // Number of energy bins
-  this->nBins = inputWS->blocksize();
-
-  // Get a pointer to the sample
-  Geometry::IComponent_const_sptr sample =
-      inputWS->getInstrument()->getSample();
+  const int64_t nBins = static_cast<int64_t>(inputWS->blocksize());
 
   // Retrieve the filename from the properties
-  this->filename = getPropertyValue("Filename");
+  std::string filename = getPropertyValue("Filename");
 
   // Create the file.
-  ::NeXus::File nxFile(this->filename, NXACC_CREATE5);
+  ::NeXus::File nxFile(filename, NXACC_CREATE5);
 
   // Make the top level entry (and open it)
-  nxFile.makeGroup(inputWS->getName(), "NXentry", true);
+  std::string entryName = getPropertyValue("InputWorkspace");
+  if (entryName.empty()) {
+    entryName = "mantid_workspace";
+  }
+  nxFile.makeGroup(entryName, "NXentry", true);
 
   // Definition name and version
   nxFile.writeData("definition", "NXSPE");
@@ -116,7 +118,7 @@ void SaveNXSPE::exec() {
   double efixed = getProperty("Efixed");
   if (isEmpty(efixed))
     efixed = MASK_FLAG;
-  // Now lets check to see if the workspace nows better.
+  // Now lets check to see if the workspace knows better.
   // TODO: Check that this is the way round we want to do it.
   const API::Run &run = inputWS->run();
   if (run.hasProperty("Ei")) {
@@ -185,13 +187,12 @@ void SaveNXSPE::exec() {
   nxFile.closeData();
 
   // let's create some blank arrays in the nexus file
-
-  std::vector<int> array_dims;
-  array_dims.push_back((int)nHist);
-  array_dims.push_back((int)nBins);
-
-  nxFile.makeData("data", ::NeXus::FLOAT64, array_dims, false);
-  nxFile.makeData("error", ::NeXus::FLOAT64, array_dims, false);
+  typedef std::vector<int64_t> Dimensions;
+  Dimensions arrayDims(2);
+  arrayDims[0] = nHist;
+  arrayDims[1] = nBins;
+  nxFile.makeData("data", ::NeXus::FLOAT64, arrayDims, false);
+  nxFile.makeData("error", ::NeXus::FLOAT64, arrayDims, false);
 
   // Add the axes attributes to the data
   nxFile.openData("data");
@@ -199,89 +200,85 @@ void SaveNXSPE::exec() {
   nxFile.putAttr("axes", "polar:energy");
   nxFile.closeData();
 
-  std::vector<int64_t> slab_start;
-  std::vector<int64_t> slab_size;
-
   // What size slabs are we going to write...
-  slab_size.push_back(1);
-  slab_size.push_back((int64_t)nBins);
-
-  // And let's start at the beginning
-  slab_start.push_back(0);
-  slab_start.push_back(0);
-
-  // define the data and error vectors for masked detectors
-  std::vector<double> masked_data(nBins, MASK_FLAG);
-  std::vector<double> masked_error(nBins, MASK_ERROR);
-
-  // Create a progress reporting object
-  Progress progress(this, 0, 1, 100);
-  const int progStep = (int)(ceil(nHist / 100.0));
-  Geometry::IDetector_const_sptr det;
-  // Loop over spectra
-  for (int i = 0; i < nHist; i++) {
+  // Use an intermediate in-memory buffer to reduce the number
+  // of calls to putslab, i.e disk writes but still write whole rows
+  Dimensions slabStart(2, 0), slabSize(2, 0);
+  Dimensions::value_type chunkRows =
+      static_cast<Dimensions::value_type>(MAX_CHUNK_SIZE / 8 / nBins);
+  if (nHist < chunkRows) {
+    chunkRows = nHist;
+  }
+  // slab size for all but final write
+  slabSize[0] = chunkRows;
+  slabSize[1] = nBins;
+
+  // Allocate the temporary buffers for the signal and errors
+  typedef boost::scoped_array<double> Buffer;
+  const size_t bufferSize(slabSize[0] * slabSize[1]);
+  Buffer signalBuffer(new double[bufferSize]);
+  Buffer errorBuffer(new double[bufferSize]);
+
+  // Write the data
+  Progress progress(this, 0, 1, nHist);
+  int64_t bufferCounter(0);
+  for (int64_t i = 0; i < nHist; ++i) {
+    progress.report();
+
+    Geometry::IDetector_const_sptr det;
     try { // detector exist
       det = inputWS->getDetector(i);
-      // Check that we aren't writing a monitor...
-      if (!det->isMonitor()) {
-        Geometry::IDetector_const_sptr det = inputWS->getDetector(i);
-
-        if (!det->isMasked()) {
-          // no masking...
-          // Open the data
-          nxFile.openData("data");
-          slab_start[0] = i;
-          nxFile.putSlab(const_cast<MantidVec &>(inputWS->readY(i)), slab_start,
-                         slab_size);
-          // Close the data
-          nxFile.closeData();
-
-          // Open the error
-          nxFile.openData("error");
-          // MantidVec& tmparr = const_cast<MantidVec&>(inputWS->dataE(i));
-          // nxFile.putSlab((void*)(&(tmparr[0])), slab_start, slab_size);
-          nxFile.putSlab(const_cast<MantidVec &>(inputWS->readE(i)), slab_start,
-                         slab_size);
-          // Close the error
-          nxFile.closeData();
-        } else {
-          // Write a masked value...
-          // Open the data
-          nxFile.openData("data");
-          slab_start[0] = i;
-          nxFile.putSlab(masked_data, slab_start, slab_size);
-          // Close the data
-          nxFile.closeData();
-
-          // Open the error
-          nxFile.openData("error");
-          nxFile.putSlab(masked_error, slab_start, slab_size);
-          // Close the error
-          nxFile.closeData();
-        }
-      }
     } catch (Exception::NotFoundError &) {
-      // Catch if no detector. Next line tests whether this happened - test
-      // placed
-      // outside here because Mac Intel compiler doesn't like 'continue' in a
-      // catch
-      // in an openmp block.
     }
-    // If no detector found, skip onto the next spectrum
-    if (!det)
-      continue;
 
-    // make regular progress reports and check for canceling the algorithm
-    if (i % progStep == 0) {
-      progress.report();
+    double *signalBufferStart = signalBuffer.get() + bufferCounter * nBins;
+    double *errorBufferStart = errorBuffer.get() + bufferCounter * nBins;
+    if (det && !det->isMonitor()) {
+      // a detector but not a monitor
+      if (!det->isMasked()) {
+        const auto &inY = inputWS->readY(i);
+        std::copy(inY.begin(), inY.end(), signalBufferStart);
+        const auto &inE = inputWS->readE(i);
+        std::copy(inE.begin(), inE.end(), errorBufferStart);
+      } else {
+        std::fill_n(signalBufferStart, nBins, MASK_FLAG);
+        std::fill_n(errorBufferStart, nBins, MASK_ERROR);
+      }
+    } else {
+      // no detector gets zeroes.
+      std::fill_n(signalBufferStart, nBins, 0.0);
+      std::fill_n(errorBufferStart, nBins, 0.0);
+    }
+    ++bufferCounter;
+
+    // Do we need to flush the buffer. Either we have filled the buffer
+    // or we have reached the end of the workspace and not completely filled
+    // the buffer
+    if (bufferCounter == chunkRows || i == nHist - 1) {
+      // techincally only need to update for the very last slab but
+      // this is always correct and avoids an if statement
+      slabSize[0] = bufferCounter;
+      nxFile.openData("data");
+      nxFile.putSlab(signalBuffer.get(), slabStart, slabSize);
+      nxFile.closeData();
+
+      // Open the error
+      nxFile.openData("error");
+      nxFile.putSlab(errorBuffer.get(), slabStart, slabSize);
+      nxFile.closeData();
+
+      // Reset counters for next time
+      slabStart[0] += bufferCounter;
+      bufferCounter = 0;
     }
   }
-  // execute the ChildAlgorithm to calculate the detector's parameters;
+
+  // execute the algorithm to calculate the detector's parameters;
   IAlgorithm_sptr spCalcDetPar =
       this->createChildAlgorithm("FindDetectorsPar", 0, 1, true, 1);
 
   spCalcDetPar->initialize();
-  spCalcDetPar->setPropertyValue("InputWorkspace", inputWS->getName());
+  spCalcDetPar->setProperty("InputWorkspace", inputWS);
   std::string parFileName = this->getPropertyValue("ParFile");
   if (!(parFileName.empty() || parFileName == "not_used.par")) {
     spCalcDetPar->setPropertyValue("ParFile", parFileName);
diff --git a/Code/Mantid/Framework/DataHandling/src/SaveNXTomo.cpp b/Code/Mantid/Framework/DataHandling/src/SaveNXTomo.cpp
index 95e3eeb899a720707ebdf579415f990c716b8ea9..48ff035011ef2f4cb643fd1bb17b42c809678ed9 100644
--- a/Code/Mantid/Framework/DataHandling/src/SaveNXTomo.cpp
+++ b/Code/Mantid/Framework/DataHandling/src/SaveNXTomo.cpp
@@ -35,9 +35,12 @@ void SaveNXTomo::init() {
   wsValidator->add<API::CommonBinsValidator>();
   wsValidator->add<API::HistogramValidator>();
 
-  declareProperty(new WorkspaceProperty<>("InputWorkspaces", "",
-                                          Direction::Input, wsValidator),
-                  "The name of the workspaces to save.");
+  declareProperty(
+      new WorkspaceProperty<>("InputWorkspaces", "", Direction::Input,
+                              wsValidator),
+      "The name of the workspace(s) to save - this can be the name of a single "
+      "Workspace2D or the name of a WorkspaceGroup in which case all the "
+      "Workspace2Ds included in the group will be saved.");
 
   declareProperty(
       new API::FileProperty("Filename", "", FileProperty::Save,
@@ -55,7 +58,8 @@ void SaveNXTomo::init() {
 }
 
 /**
- * Execute the algorithm : Single workspace
+ * Execute the algorithm for the single workspace (no group) case. See
+ * processGroups() for when a workspace group is given as input.
  */
 void SaveNXTomo::exec() {
   try {
@@ -68,6 +72,28 @@ void SaveNXTomo::exec() {
     processAll();
 }
 
+/**
+* Run instead of exec when operating on groups
+*/
+bool SaveNXTomo::processGroups() {
+  try {
+    std::string name = getPropertyValue("InputWorkspaces");
+    WorkspaceGroup_sptr groupWS =
+        AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(name);
+
+    for (int i = 0; i < groupWS->getNumberOfEntries(); ++i) {
+      m_workspaces.push_back(
+          boost::dynamic_pointer_cast<Workspace2D>(groupWS->getItem(i)));
+    }
+  } catch (...) {
+  }
+
+  if (m_workspaces.size() != 0)
+    processAll();
+
+  return true;
+}
+
 /**
  * Main exec routine, called for group or individual workspace processing.
  *
@@ -440,27 +466,5 @@ SaveNXTomo::writeIntensityValue(const DataObjects::Workspace2D_sptr workspace,
   nxFile.closeData();
 }
 
-/**
-* Run instead of exec when operating on groups
-*/
-bool SaveNXTomo::processGroups() {
-  try {
-    std::string name = getPropertyValue("InputWorkspaces");
-    WorkspaceGroup_sptr groupWS =
-        AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(name);
-
-    for (int i = 0; i < groupWS->getNumberOfEntries(); ++i) {
-      m_workspaces.push_back(
-          boost::dynamic_pointer_cast<Workspace2D>(groupWS->getItem(i)));
-    }
-  } catch (...) {
-  }
-
-  if (m_workspaces.size() != 0)
-    processAll();
-
-  return true;
-}
-
 } // namespace DataHandling
 } // namespace Mantid
diff --git a/Code/Mantid/Framework/DataHandling/src/SavePDFGui.cpp b/Code/Mantid/Framework/DataHandling/src/SavePDFGui.cpp
index 1c1ecabaeddc63bfa12f73352abff9bd6a5b3fdd..daf86a836cbcfd8e80cfa193cec4fab60e48b6b5 100644
--- a/Code/Mantid/Framework/DataHandling/src/SavePDFGui.cpp
+++ b/Code/Mantid/Framework/DataHandling/src/SavePDFGui.cpp
@@ -82,7 +82,24 @@ void SavePDFGui::exec() {
   std::ofstream out;
   out.open(filename.c_str(), std::ios_base::out);
 
-  // --------- write the header // TODO
+  // --------- write the header in the style of
+  //#Comment: neutron, Qmin=0.5, Qmax=31.42, Qdamp=0.017659, Qbroad= 0.0191822, Temperature = 300
+  out << "#Comment: neutron";
+  auto run = inputWS->run();
+  if (run.hasProperty("Qmin")) {
+      out << ", Qmin=" << run.getPropertyAsSingleValue("Qmin");
+  }
+  if (run.hasProperty("Qmax")) {
+      out << ", Qmax=" << run.getPropertyAsSingleValue("Qmax");
+  }
+  if (run.hasProperty("Qdamp")) {
+      out << ", Qdamp=" << run.getPropertyAsSingleValue("Qdamp");
+  }
+  if (run.hasProperty("Qbroad")) {
+      out << ", Qbroad=" << run.getPropertyAsSingleValue("Qbroad");
+  }
+  // TODO add the sample temperature
+  out << "\n";
 
   // --------- write the label for the data
   out << "##### start data\n";
diff --git a/Code/Mantid/Framework/DataHandling/test/CMakeLists.txt b/Code/Mantid/Framework/DataHandling/test/CMakeLists.txt
index 3b14df4d40ef64899de31fd28df1d7eaa2f65d9f..70ca84c27430cafd4687ca189051af340cef01c5 100644
--- a/Code/Mantid/Framework/DataHandling/test/CMakeLists.txt
+++ b/Code/Mantid/Framework/DataHandling/test/CMakeLists.txt
@@ -12,7 +12,7 @@ if ( CXXTEST_FOUND )
       )
 
   cxxtest_add_test ( DataHandlingTest ${TEST_FILES} )
-  target_link_libraries( DataHandlingTest DataHandling )
+  target_link_libraries( DataHandlingTest DataHandling ${HDF5_LIBRARIES} )
   add_dependencies ( DataHandlingTest Algorithms MDAlgorithms )
   add_dependencies ( FrameworkTests DataHandlingTest )
   # Test data
@@ -21,4 +21,3 @@ if ( CXXTEST_FOUND )
   # Add to the 'FrameworkTests' group in VS
   set_property ( TARGET DataHandlingTest PROPERTY FOLDER "UnitTests" )
 endif ()
-
diff --git a/Code/Mantid/Framework/DataHandling/test/LoadFITSTest.h b/Code/Mantid/Framework/DataHandling/test/LoadFITSTest.h
index 95ff18df83794367f217b95328e8b6de93e03882..9a0aa59aeb4708590723c4c2508c53ccad54e634 100644
--- a/Code/Mantid/Framework/DataHandling/test/LoadFITSTest.h
+++ b/Code/Mantid/Framework/DataHandling/test/LoadFITSTest.h
@@ -70,6 +70,14 @@ public:
     TS_ASSERT_THROWS(lf.setPropertyValue("FITS", "anything"),
                      std::runtime_error);
 
+    TS_ASSERT_THROWS(lf.setPropertyValue("BinSize", "-1"),
+                     std::invalid_argument);
+    TS_ASSERT_THROWS(lf.setPropertyValue("BinSize", "0"),
+                     std::invalid_argument);
+    TS_ASSERT_THROWS(lf.setPropertyValue("FilterNoiseLevel", "-10"),
+                     std::invalid_argument);
+    TS_ASSERT_THROWS_NOTHING(lf.setPropertyValue("FilterNoiseLevel", "0"));
+
     TS_ASSERT_THROWS(lf.setPropertyValue("ImageKey", "anything"),
                      Mantid::Kernel::Exception::NotFoundError);
     TS_ASSERT_THROWS(lf.setPropertyValue("BITPIX", "anything"),
@@ -80,7 +88,7 @@ public:
                      std::runtime_error);
   }
 
-  void test_init() {
+  void test_initGood() {
     TS_ASSERT_THROWS_NOTHING(algToBeTested.initialize());
     TS_ASSERT(algToBeTested.isInitialized());
 
@@ -98,8 +106,8 @@ public:
 
     // Set the ImageKey to be 0 (this used to be required, but the key
     // should not be there any longer);
-    TS_ASSERT_THROWS( algToBeTested.setProperty<int>("ImageKey", 0),
-                      Mantid::Kernel::Exception::NotFoundError);
+    TS_ASSERT_THROWS(algToBeTested.setProperty<int>("ImageKey", 0),
+                     Mantid::Kernel::Exception::NotFoundError);
   }
 
   void test_performAssertions() {
@@ -140,10 +148,165 @@ public:
     // should be 375.183
     double sumE =
         ws1->readE(SPECTRA_COUNT - 1)[0] + ws2->readE(SPECTRA_COUNT - 1)[0];
-    TS_ASSERT_LESS_THAN(abs(sumE - 23.4489), 0.0001); // Include a small
-                                                      // tolerance check with
-                                                      // the assert - not
-                                                      // exactly 375.183
+    TS_ASSERT_LESS_THAN(std::abs(sumE - 23.4489), 0.0001); // Include a small
+    // tolerance check with
+    // the assert - not
+    // exactly 375.183
+  }
+
+  void test_noiseFilter() {
+    testAlg =
+        Mantid::API::AlgorithmManager::Instance().create("LoadFITS" /*, 1*/);
+
+    TS_ASSERT_THROWS_NOTHING(testAlg->initialize());
+    TS_ASSERT(testAlg->isInitialized());
+
+    outputSpace = "LoadFITSFiltered";
+    testAlg->setPropertyValue("OutputWorkspace", outputSpace);
+    testAlg->setProperty("FilterNoiseLevel", 200.0);
+
+    inputFile = smallFname1 + ", " + smallFname2;
+    testAlg->setPropertyValue("Filename", inputFile);
+
+    TS_ASSERT_THROWS_NOTHING(testAlg->execute());
+
+    WorkspaceGroup_sptr out;
+    TS_ASSERT(AnalysisDataService::Instance().doesExist(outputSpace));
+    TS_ASSERT_THROWS_NOTHING(
+        out = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(
+            outputSpace));
+    const int nws = 2;
+    TS_ASSERT_EQUALS(out->getNumberOfEntries(), nws);
+
+    double expectedY[nws] = {144, 149.0};
+    double expectedE[nws] = {12, 12.2066};
+    for (int i = 0; i < out->getNumberOfEntries(); ++i) {
+      MatrixWorkspace_sptr ws;
+      TS_ASSERT_THROWS_NOTHING(
+          ws = boost::dynamic_pointer_cast<MatrixWorkspace>(out->getItem(i)));
+
+      TS_ASSERT_EQUALS(ws->getNumberHistograms(), SPECTRA_COUNT);
+
+      // check Y and Error
+      TS_ASSERT_EQUALS(ws->readY(SPECTRA_COUNT - 100)[0], expectedY[i]);
+      TS_ASSERT_LESS_THAN(
+          std::abs(ws->readE(SPECTRA_COUNT - 100)[0] - expectedE[i]), 0.0001);
+    }
+  }
+
+  void test_rebinWrong() {
+    testAlg =
+        Mantid::API::AlgorithmManager::Instance().create("LoadFITS" /*, 1*/);
+
+    TS_ASSERT_THROWS_NOTHING(testAlg->initialize());
+    TS_ASSERT(testAlg->isInitialized());
+
+    inputFile = smallFname1 + ", " + smallFname2;
+    testAlg->setPropertyValue("Filename", inputFile);
+    testAlg->setProperty("BinSize", 3);
+    // this should fail - width and height not multiple of 3
+    outputSpace = "LoadFITSx3";
+    testAlg->setPropertyValue("OutputWorkspace", outputSpace);
+
+    TS_ASSERT_THROWS_NOTHING(testAlg->execute());
+    TS_ASSERT(!AnalysisDataService::Instance().doesExist(outputSpace));
+  }
+
+  void test_rebinOK() {
+    testAlg =
+        Mantid::API::AlgorithmManager::Instance().create("LoadFITS" /*, 1*/);
+
+    TS_ASSERT_THROWS_NOTHING(testAlg->initialize());
+    TS_ASSERT(testAlg->isInitialized());
+
+    inputFile = smallFname1 + ", " + smallFname2;
+    testAlg->setPropertyValue("Filename", inputFile);
+    int binSize = 2;
+    testAlg->setProperty("BinSize", 2);
+    testAlg->setProperty("LoadAsRectImg", true);
+    outputSpace = "LoadFITSx2";
+    testAlg->setPropertyValue("OutputWorkspace", outputSpace);
+
+    TS_ASSERT_THROWS_NOTHING(testAlg->execute());
+
+    WorkspaceGroup_sptr out;
+    TS_ASSERT(AnalysisDataService::Instance().doesExist(outputSpace));
+    TS_ASSERT_THROWS_NOTHING(
+        out = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(
+            outputSpace));
+    TS_ASSERT_EQUALS(out->getNumberOfEntries(), 2);
+
+    for (int i = 0; i < out->getNumberOfEntries(); ++i) {
+      MatrixWorkspace_sptr ws;
+      TS_ASSERT_THROWS_NOTHING(
+          ws = boost::dynamic_pointer_cast<MatrixWorkspace>(out->getItem(i)));
+
+      TS_ASSERT_EQUALS(ws->getNumberHistograms(), SPECTRA_COUNT_ASRECT / binSize);
+    }
+
+    // try 8, 512x512 => 64x64 image
+    binSize = 8;
+    testAlg =
+      Mantid::API::AlgorithmManager::Instance().create("LoadFITS" /*, 1*/);
+
+    TS_ASSERT_THROWS_NOTHING(testAlg->initialize());
+    TS_ASSERT(testAlg->isInitialized());
+
+    inputFile = smallFname1 + ", " + smallFname2;
+    testAlg->setPropertyValue("Filename", inputFile);
+    testAlg->setProperty("BinSize", binSize);
+    testAlg->setProperty("LoadAsRectImg", true);
+    outputSpace = "LoadFITSx8";
+    testAlg->setPropertyValue("OutputWorkspace", outputSpace);
+
+    TS_ASSERT_THROWS_NOTHING(testAlg->execute());
+
+    TS_ASSERT(AnalysisDataService::Instance().doesExist(outputSpace));
+    TS_ASSERT_THROWS_NOTHING(
+        out = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(
+            outputSpace));
+    TS_ASSERT_EQUALS(out->getNumberOfEntries(), 2);
+
+    for (int i = 0; i < out->getNumberOfEntries(); ++i) {
+      MatrixWorkspace_sptr ws;
+      TS_ASSERT_THROWS_NOTHING(
+          ws = boost::dynamic_pointer_cast<MatrixWorkspace>(out->getItem(i)));
+
+      TS_ASSERT_EQUALS(ws->getNumberHistograms(), SPECTRA_COUNT_ASRECT / binSize);
+    }
+
+  }
+
+  void test_loadAsRect() {
+    testAlg =
+        Mantid::API::AlgorithmManager::Instance().create("LoadFITS" /*, 1*/);
+
+    TS_ASSERT_THROWS_NOTHING(testAlg->initialize());
+    TS_ASSERT(testAlg->isInitialized());
+
+    outputSpace = "LoadFITSRect";
+    testAlg->setPropertyValue("OutputWorkspace", outputSpace);
+    testAlg->setProperty("LoadAsRectImg", true);
+
+    inputFile = smallFname1 + ", " + smallFname2;
+    testAlg->setPropertyValue("Filename", inputFile);
+
+    TS_ASSERT_THROWS_NOTHING(testAlg->execute());
+
+    WorkspaceGroup_sptr out;
+    TS_ASSERT(AnalysisDataService::Instance().doesExist(outputSpace));
+    TS_ASSERT_THROWS_NOTHING(
+        out = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(
+            outputSpace));
+    TS_ASSERT_EQUALS(out->getNumberOfEntries(), 2);
+
+    for (int i = 0; i < out->getNumberOfEntries(); ++i) {
+      MatrixWorkspace_sptr ws;
+      TS_ASSERT_THROWS_NOTHING(
+          ws = boost::dynamic_pointer_cast<MatrixWorkspace>(out->getItem(i)));
+
+      TS_ASSERT_EQUALS(ws->getNumberHistograms(), SPECTRA_COUNT_ASRECT);
+    }
   }
 
 private:
@@ -158,6 +321,7 @@ private:
   const static size_t xdim = 512;
   const static size_t ydim = 512;
   const static size_t SPECTRA_COUNT = xdim * ydim;
+  const static size_t SPECTRA_COUNT_ASRECT = ydim;
   // FITS headers
   const static std::string hdrSIMPLE;
   const static std::string hdrBITPIX;
diff --git a/Code/Mantid/Framework/DataHandling/test/LoadRaw3Test.h b/Code/Mantid/Framework/DataHandling/test/LoadRaw3Test.h
index 9db6077bfe752a0ae3999728775d0b67e4db25ed..6e7d580a68af47ca88edceb331dc9446ede2aa3f 100644
--- a/Code/Mantid/Framework/DataHandling/test/LoadRaw3Test.h
+++ b/Code/Mantid/Framework/DataHandling/test/LoadRaw3Test.h
@@ -399,7 +399,7 @@ public:
     TS_ASSERT_EQUALS( ptrDet->getID(), 60);
 
     Mantid::Geometry::ParameterMap& pmap = output2D->instrumentParameters();
-    TS_ASSERT_EQUALS( static_cast<int>(pmap.size()), 159);
+    TS_ASSERT_EQUALS( static_cast<int>(pmap.size()), 160);
     AnalysisDataService::Instance().remove("parameterIDF");
   }
 
diff --git a/Code/Mantid/Framework/DataHandling/test/SaveNXSPETest.h b/Code/Mantid/Framework/DataHandling/test/SaveNXSPETest.h
index 5fa165c4d154bdb10779aa43f722912a51db85fb..a0e5ceaad005fd52792e989c8dc1feed1ec1107d 100644
--- a/Code/Mantid/Framework/DataHandling/test/SaveNXSPETest.h
+++ b/Code/Mantid/Framework/DataHandling/test/SaveNXSPETest.h
@@ -9,8 +9,19 @@
 #include "MantidAPI/NumericAxis.h"
 #include "MantidAPI/FrameworkManager.h"
 #include "MantidDataHandling/LoadInstrument.h"
+#include "MantidTestHelpers/ComponentCreationHelper.h"
+
+#include <boost/math/special_functions/fpclassify.hpp>
+#include <boost/shared_array.hpp>
+#include "boost/tuple/tuple.hpp"
+
+#include <hdf5.h>
+#include <hdf5_hl.h>
+
 #include <Poco/File.h>
 
+#include <limits>
+
 using namespace Mantid::API;
 using namespace Mantid::DataHandling;
 using Mantid::Kernel::UnitFactory;
@@ -18,13 +29,7 @@ using Mantid::Geometry::ParameterMap;
 using Mantid::Geometry::Instrument;
 using Mantid::Geometry::IDetector_const_sptr;
 
-
-static const double MASK_FLAG=-1e30;   // values here need to match what is in the SaveNXSPE.h file
-static const double MASK_ERROR=0.0;
-
-static const int NHIST = 3;
 static const int THEMASKED = 2;
-static const int DEFAU_Y = 2;
 
 class SaveNXSPETest : public CxxTest::TestSuite
 {
@@ -32,149 +37,135 @@ public:
   static SaveNXSPETest *createSuite() { return new SaveNXSPETest(); }
   static void destroySuite(SaveNXSPETest *suite) { delete suite; }
 
-  SaveNXSPETest()
-  {// the functioning of SaveNXSPE is affected by a function call in the FrameworkManager's constructor, creating the algorithm in this way ensures that function is executed
-    saver = FrameworkManager::Instance().createAlgorithm("SaveNXSPE");
-  }
-
   void testName()
   {
-    TS_ASSERT_EQUALS( saver->name(), "SaveNXSPE" );
+    SaveNXSPE saver;
+    TS_ASSERT_EQUALS( saver.name(), "SaveNXSPE" );
   }
 
   void testVersion()
   {
-    TS_ASSERT_EQUALS( saver->version(), 1 );
+    SaveNXSPE saver;
+    TS_ASSERT_EQUALS( saver.version(), 1 );
   }
 
   void testInit()
   {
-    TS_ASSERT_THROWS_NOTHING( saver->initialize() );
-    TS_ASSERT( saver->isInitialized() );
+    SaveNXSPE saver;
+    TS_ASSERT_THROWS_NOTHING( saver.initialize() );
+    TS_ASSERT( saver.isInitialized() );
 
-    TS_ASSERT_EQUALS( static_cast<int>(saver->getProperties().size()), 6 );
+    TS_ASSERT_EQUALS( static_cast<int>(saver.getProperties().size()), 6 );
   }
 
-  void testExec()
+  void test_Saving_Workspace_Smaller_Than_Chunk_Size()
   {
     // Create a small test workspace
-    std::string WSName = "saveNXSPETest_input";
-    MatrixWorkspace_const_sptr input = makeWorkspace(WSName);
-
-    TS_ASSERT_THROWS_NOTHING( saver->setPropertyValue("InputWorkspace", WSName) );
-    std::string outputFile("testNXSPE.nxspe");
-    TS_ASSERT_THROWS_NOTHING( saver->setPropertyValue("Filename",outputFile) );
-    outputFile = saver->getPropertyValue("Filename");//get absolute path
-
-    TS_ASSERT_THROWS_NOTHING( saver->setProperty("Efixed", 0.0));
-    TS_ASSERT_THROWS_NOTHING( saver->setProperty("Psi", 0.0));
-    TS_ASSERT_THROWS_NOTHING( saver->setProperty("KiOverKfScaling", true));
-
-
-    TS_ASSERT_THROWS_NOTHING( saver->execute() );
-    TS_ASSERT( saver->isExecuted() );
-
-    TS_ASSERT( Poco::File(outputFile).exists() );
-
-    // TODO: Test the files contents...
+    const int nhist(3), nx(10);
+    MatrixWorkspace_sptr input = makeWorkspace(nhist, nx);
+    auto loadedData = saveAndReloadWorkspace(input);
+    auto dims = loadedData.get<0>();
+    auto signal = loadedData.get<1>();
+    auto error = loadedData.get<2>();
+
+    double tolerance(1e-08);
+    TS_ASSERT_EQUALS(nhist, dims[0]);
+    TS_ASSERT_EQUALS(nx, dims[1]);
+    // element 0,0
+    TS_ASSERT_DELTA(0.0, signal[0], tolerance);
+    TS_ASSERT_DELTA(0.0, error[0], tolerance);
+    // element 0,9
+    TS_ASSERT_DELTA(9.0, signal[9], tolerance);
+    TS_ASSERT_DELTA(18.0, error[9], tolerance);
+    // element 1,2 in 2D flat buffer
+    TS_ASSERT(boost::math::isnan(signal[1*dims[1] + 2]));
+    TS_ASSERT_DELTA(0.0, error[1*dims[1] + 2], tolerance);
+    // final element
+    TS_ASSERT_DELTA(29.0, signal[dims[0]*dims[1] - 1], tolerance);
+    TS_ASSERT_DELTA(58.0, error[dims[0]*dims[1] - 1], tolerance);
+  }
 
-    AnalysisDataService::Instance().remove(WSName);
-    if( Poco::File(outputFile).exists() )
-      Poco::File(outputFile).remove();
+  void test_Saving_Workspace_Larger_Than_Chunk_Size()
+  {
+    // Create a test workspace
+    const int nhist(5250), nx(100);
+    MatrixWorkspace_sptr input = makeWorkspace(nhist, nx);
+    auto loadedData = saveAndReloadWorkspace(input);
+    auto dims = loadedData.get<0>();
+    auto signal = loadedData.get<1>();
+    auto error = loadedData.get<2>();
+
+    double tolerance(1e-08);
+    TS_ASSERT_EQUALS(nhist, dims[0]);
+    TS_ASSERT_EQUALS(nx, dims[1]);
+    // element 0,0
+    TS_ASSERT_DELTA(0.0, signal[0], tolerance);
+    TS_ASSERT_DELTA(0.0, error[0], tolerance);
+    // element 0,9
+    TS_ASSERT_DELTA(99.0, signal[99], tolerance);
+    TS_ASSERT_DELTA(198.0, error[99], tolerance);
+    // element 1,2 in 2D flat buffer
+    TS_ASSERT(boost::math::isnan(signal[1*dims[1] + 2]));
+    TS_ASSERT_DELTA(0.0, error[1*dims[1] + 2], tolerance);
+    // final element
+    TS_ASSERT_DELTA(524999.0, signal[dims[0]*dims[1] - 1], tolerance);
+    TS_ASSERT_DELTA(1049998.0, error[dims[0]*dims[1] - 1], tolerance);
   }
+
   void testExecWithParFile()
   {
-   
-     std::string WSName = "saveNXSPETest_input";
-     MatrixWorkspace_const_sptr input = makeWorkspace(WSName);
+     MatrixWorkspace_sptr input = makeWorkspace();
 
-     TS_ASSERT_THROWS_NOTHING( saver->setPropertyValue("InputWorkspace", WSName) );
-     TS_ASSERT_THROWS_NOTHING( saver->setProperty("ParFile","testParFile.par"));
-     std::string outputFile("testNXSPE.nxspe");
-     TS_ASSERT_THROWS_NOTHING( saver->setPropertyValue("Filename",outputFile) );
-      outputFile = saver->getPropertyValue("Filename");//get absolute path
+     SaveNXSPE saver;
+     saver.initialize();
+     saver.setChild(true);
+     TS_ASSERT_THROWS_NOTHING( saver.setProperty("InputWorkspace", input) );
+     TS_ASSERT_THROWS_NOTHING( saver.setProperty("ParFile","testParFile.par"));
+     std::string outputFile("SaveNXSPETest_testExecWithParFile.nxspe");
+     TS_ASSERT_THROWS_NOTHING( saver.setPropertyValue("Filename",outputFile) );
+     outputFile = saver.getPropertyValue("Filename");//get absolute path
 
     // throws file not exist from ChildAlgorithm
-      saver->setRethrows(true);
-      TS_ASSERT_THROWS( saver->execute(),Mantid::Kernel::Exception::FileError);
-  
+      saver.setRethrows(true);
+      TS_ASSERT_THROWS( saver.execute(),Mantid::Kernel::Exception::FileError);
       TS_ASSERT( Poco::File(outputFile).exists() );
 
-   
       if( Poco::File(outputFile).exists() ) Poco::File(outputFile).remove();
-      AnalysisDataService::Instance().remove(WSName);
-  }
-  void xtestThatOutputIsValidFromWorkspaceWithNumericAxis()
-  {
-    // Create a small test workspace
-    std::string WSName = "saveNXSPETestB_input";
-    MatrixWorkspace_sptr input = makeWorkspaceWithNumericAxis(WSName);
-
-    TS_ASSERT_THROWS_NOTHING( saver->setPropertyValue("InputWorkspace", WSName) );
-    const std::string outputFile("testNXSPE_Axis.nxspe");
-    TS_ASSERT_THROWS_NOTHING( saver->setPropertyValue("Filename",outputFile) );
-    // do not forget to nullify parFile property, as it will keep it from previous set 
-    TS_ASSERT_THROWS_NOTHING(saver->setProperty("ParFile", ""))
-    saver->setRethrows(true);
-    saver->execute();
-    TS_ASSERT( saver->isExecuted() );
-
-    TS_ASSERT( Poco::File(outputFile).exists() );
-    if( Poco::File(outputFile).exists() )
-    {
-      Poco::File(outputFile).remove();
-    }
   }
 
 private:
-
-  MatrixWorkspace_sptr makeWorkspace(const std::string & input)
-  {
-    // all the Y values in this new workspace are set to DEFAU_Y, which currently = 2
-    MatrixWorkspace_sptr inputWS = WorkspaceCreationHelper::Create2DWorkspaceBinned(NHIST,10,1.0);
-    return setUpWorkspace(input, inputWS);
-  }
-
-  MatrixWorkspace_sptr makeWorkspaceWithNumericAxis(const std::string & input)
+  
+  MatrixWorkspace_sptr makeWorkspace(int nhist = 3, int nx = 10)
   {
-    // all the Y values in this new workspace are set to DEFAU_Y, which currently = 2
-    MatrixWorkspace_sptr inputWS = WorkspaceCreationHelper::Create2DWorkspaceBinned(NHIST,10,1.0);
-    inputWS = setUpWorkspace(input, inputWS);
-    Axis * axisOne = inputWS->getAxis(1);
-    NumericAxis *newAxisOne = new NumericAxis(axisOne->length());
-    for(size_t i = 0; i < axisOne->length(); ++i)
-    {
-      newAxisOne->setValue(i, axisOne->operator()((i)));
+    auto testWS = WorkspaceCreationHelper::Create2DWorkspaceBinned(nhist,nx,1.0);
+    // Fill workspace with increasing counter to properly check saving
+    for(int i = 0; i < nhist; ++i) {
+      auto & outY = testWS->dataY(i);
+      auto & outE = testWS->dataE(i);
+      for(int j = 0; j < nx; ++j) {
+        outY[j] = i*nx + j;
+        outE[j] = outY[j]*2.0;
+      }
     }
-    // Set the units
-    inputWS->replaceAxis(1, newAxisOne);
-    inputWS->getAxis(1)->unit() = UnitFactory::Instance().create("Energy");
-    inputWS->setYUnit("MyCaption");
-    return inputWS;
+    return setUpWorkspace(testWS);
   }
 
-  MatrixWorkspace_sptr setUpWorkspace(const std::string & input, MatrixWorkspace_sptr inputWS)
+  MatrixWorkspace_sptr setUpWorkspace(MatrixWorkspace_sptr inputWS)
   {
     inputWS->getAxis(0)->unit() = Mantid::Kernel::UnitFactory::Instance().create("DeltaE");
-
-    // the following is largely about associating detectors with the workspace
-    for (int j = 0; j < NHIST; ++j)
+    // Create an instrument but we don't care where they are
+    std::vector<double> dummy(inputWS->getNumberHistograms(), 0.0);
+    auto testInst = 
+        ComponentCreationHelper::createCylInstrumentWithDetInGivenPositions(dummy, dummy, dummy);
+    inputWS->setInstrument(testInst);
+
+    // Associate detectors with the workspace
+    for (size_t j = 0; j < inputWS->getNumberHistograms(); ++j)
     {
       // Just set the spectrum number to match the index
-      inputWS->getSpectrum(j)->setSpectrumNo(j+1);
+      inputWS->getSpectrum(j)->setSpectrumNo(static_cast<Mantid::specid_t>(j+1));
     }
 
-    AnalysisDataService::Instance().add(input,inputWS);
-
-    // Load the instrument data
-    Mantid::DataHandling::LoadInstrument loader;
-    loader.initialize();
-    // Path to test input file assumes Test directory checked out from SVN
-    std::string inputFile = "INES_Definition.xml";
-    loader.setPropertyValue("Filename", inputFile);
-    loader.setPropertyValue("Workspace", input);
-    loader.execute();
-
     // mask the detector
     ParameterMap* m_Pmap = &(inputWS->instrumentParameters());
     boost::shared_ptr<const Instrument> instru = inputWS->getInstrument();
@@ -187,9 +178,61 @@ private:
 
     return inputWS;
   }
- 
-private:
-  IAlgorithm* saver;
+  
+  typedef boost::tuple<boost::shared_array<hsize_t>,
+                       boost::shared_array<double>, 
+                       boost::shared_array<double>> DataHolder;
+  
+  DataHolder saveAndReloadWorkspace(const MatrixWorkspace_sptr inputWS)
+  {
+    SaveNXSPE saver;
+    saver.initialize();
+    saver.setChild(true);
+    TS_ASSERT_THROWS_NOTHING( saver.setProperty("InputWorkspace", inputWS) );
+    std::string outputFile("SaveNXSPETest_testEXEC.nxspe");
+    TS_ASSERT_THROWS_NOTHING( saver.setPropertyValue("Filename",outputFile) );
+    outputFile = saver.getPropertyValue("Filename");//get absolute path
+
+    TS_ASSERT_THROWS_NOTHING( saver.setProperty("Efixed", 0.0));
+    TS_ASSERT_THROWS_NOTHING( saver.setProperty("Psi", 0.0));
+    TS_ASSERT_THROWS_NOTHING( saver.setProperty("KiOverKfScaling", true));
+    TS_ASSERT_THROWS_NOTHING( saver.execute() );
+    TS_ASSERT( saver.isExecuted() );
+
+    TS_ASSERT( Poco::File(outputFile).exists() );
+    if( !Poco::File(outputFile).exists() ) {
+      return boost::make_tuple(boost::shared_array<hsize_t>(), boost::shared_array<double>(),
+                               boost::shared_array<double>());
+    }
+
+    auto h5file = H5Fopen(outputFile.c_str(), H5F_ACC_RDWR, H5P_DEFAULT);
+    const char * dset = "/mantid_workspace/data/data";
+    int rank(0);
+    herr_t status = H5LTget_dataset_ndims(h5file, dset, &rank);
+    TS_ASSERT_EQUALS(0, status);
+    TS_ASSERT_EQUALS(2, rank);
+
+    boost::shared_array<hsize_t> dims(new hsize_t[rank]);
+    H5T_class_t classId(H5T_NO_CLASS);
+    size_t typeSize(0);
+    status = H5LTget_dataset_info(h5file, dset, dims.get(), &classId, &typeSize);
+    TS_ASSERT_EQUALS(0, status);
+    TS_ASSERT_EQUALS(H5T_FLOAT, classId);
+    TS_ASSERT_EQUALS(8, typeSize);
+
+    size_t bufferSize(dims[0]*dims[1]);
+    boost::shared_array<double> signal(new double[bufferSize]), error(new double[bufferSize]);
+    status = H5LTread_dataset_double(h5file, dset, signal.get());
+    TS_ASSERT_EQUALS(0, status);
+
+    const char * dsetErr = "/mantid_workspace/data/error";
+    status = H5LTread_dataset_double(h5file, dsetErr, error.get());
+    TS_ASSERT_EQUALS(0, status);
+    H5Fclose(h5file);
+    //Poco::File(outputFile).remove();
+
+    return boost::make_tuple(dims, signal, error);
+  }
 };
 
 #endif /*SAVENXSPETEST_H_*/
diff --git a/Code/Mantid/Framework/DataHandling/test/SavePDFGuiTest.h b/Code/Mantid/Framework/DataHandling/test/SavePDFGuiTest.h
index 6782e6a6b1538dc6c3775b2862a4cc3eae0d8f22..51ac934f78630565d66dcbb31dcd37feedfbcc17 100644
--- a/Code/Mantid/Framework/DataHandling/test/SavePDFGuiTest.h
+++ b/Code/Mantid/Framework/DataHandling/test/SavePDFGuiTest.h
@@ -89,7 +89,7 @@ public:
     // do the checks
     Poco::File outFile(outFilename);
     TS_ASSERT( outFile.isFile());
-    TS_ASSERT_EQUALS( countLines(outFilename), 1003);
+    TS_ASSERT_EQUALS( countLines(outFilename), 1004);
 
     // Remove workspace from the data service.
     AnalysisDataService::Instance().remove(wsName);
diff --git a/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/MDGridBox.h b/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/MDGridBox.h
index 16b7af7ccc87f358838780758d900a1638a973a2..a96da012e77dda87bc4aba639aa112763b9f24f9 100644
--- a/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/MDGridBox.h
+++ b/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/MDGridBox.h
@@ -238,7 +238,7 @@ private:
   /**Private constructor as it does not work without box controller */
   MDGridBox() {}
   /// common part of MDGridBox contstructor;
-  void initGridBox();
+  size_t initGridBox();
 };
 
 #ifndef __INTEL_COMPILER
diff --git a/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/MDHistoWorkspaceIterator.h b/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/MDHistoWorkspaceIterator.h
index 5a914cbb28f10b974934fbdf3e2352fc8f2c0e46..454bb4ea833518726525c45821694cbe297607e2 100644
--- a/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/MDHistoWorkspaceIterator.h
+++ b/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/MDHistoWorkspaceIterator.h
@@ -8,12 +8,17 @@
 #include "MantidDataObjects/SkippingPolicy.h"
 #include <map>
 #include <vector>
+#include <boost/tuple/tuple.hpp>
 
 namespace Mantid {
 namespace DataObjects {
 
-// Typdef for a map for mapping width of neighbours (key) to permutations needed in the calcualtion.
+// Typedef for a map for mapping width of neighbours (key) to permutations needed in the calcualtion.
 typedef std::map<std::vector<int>, std::vector<int64_t> > PermutationsMap;
+// Typedef for extents
+typedef boost::tuple<Mantid::coord_t, Mantid::coord_t> MDExtentPair; // Min/Max pair
+// Typedef for vector of extents
+typedef std::vector<MDExtentPair> VecMDExtents;
 
 /** An implementation of IMDIterator that iterates through
   a MDHistoWorkspace. It treats the bin in the workspace as
@@ -78,6 +83,8 @@ public:
 
   virtual void jumpTo(size_t index);
 
+  virtual coord_t jumpToNearest(const Mantid::Kernel::VMD& fromLocation);
+
   virtual signal_t getNormalizedSignal() const;
 
   virtual signal_t getNormalizedError() const;
@@ -96,6 +103,8 @@ public:
 
   virtual size_t getNumEvents() const;
 
+  virtual signal_t getNumEventsFraction() const;
+
   virtual uint16_t getInnerRunIndex(size_t index) const;
 
   virtual int32_t getInnerDetectorID(size_t index) const;
@@ -122,6 +131,8 @@ public:
 
   size_t permutationCacheSize() const;
 
+  VecMDExtents getBoxExtents() const;
+
 protected:
   /// The MDHistoWorkspace being iterated.
   const MDHistoWorkspace *m_ws;
diff --git a/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/MDLeanEvent.h b/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/MDLeanEvent.h
index bc07aad83dfb006177098c18ead1540cbc9b42a1..bfcc62532abdbdbda75c73ba6a41cef4c87da25f 100644
--- a/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/MDLeanEvent.h
+++ b/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/MDLeanEvent.h
@@ -2,11 +2,13 @@
 #define MANTID_DATAOBJECTS_MDLEANEVENT_H_
 
 #include "MantidKernel/System.h"
-#include "MantidGeometry/MDGeometry/IMDDimension.h"
 #include "MantidGeometry/MDGeometry/MDTypes.h"
-#include "MantidAPI/BoxController.h"
-#include <numeric>
+#include <algorithm>
 #include <cmath>
+#include <numeric>
+#include <string>
+#include <vector>
+#include <stdexcept>
 
 namespace Mantid {
 namespace DataObjects {
@@ -14,7 +16,7 @@ namespace DataObjects {
 /** Templated class holding data about a neutron detection event
  * in N-dimensions (for example, Qx, Qy, Qz, E).
  *
- *   Each neutron has a signal (a float, can be != 1) and an error. This
+ *  Each neutron has a signal (a float, can be != 1) and an error. This
  * is the same principle as the WeightedEvent in EventWorkspace's
  *
  * This class is meant to be as small in memory as possible, since there
diff --git a/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/Workspace2D.h b/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/Workspace2D.h
index db7f4f1a7129048b410478454a088a051b043e4a..a3dcad884de14165e09d825677f53f270904272d 100644
--- a/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/Workspace2D.h
+++ b/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/Workspace2D.h
@@ -85,6 +85,8 @@ public:
   /// Copy the data from an image to this workspace's (Y's) and errors.
   void setImageYAndE(const API::MantidImage &imageY,
                      const API::MantidImage &imageE, size_t start = 0,
+                     bool loadAsRectImg = false,
+                     double scale_1 = 1.0,
                      bool parallelExecution = true);
 
 protected:
diff --git a/Code/Mantid/Framework/DataObjects/src/CoordTransformAffine.cpp b/Code/Mantid/Framework/DataObjects/src/CoordTransformAffine.cpp
index 01e909be080955126254cc9f35b82dc41dfe5874..fcbe484f95ab17c881719ebfdc3c6069f93e753d 100644
--- a/Code/Mantid/Framework/DataObjects/src/CoordTransformAffine.cpp
+++ b/Code/Mantid/Framework/DataObjects/src/CoordTransformAffine.cpp
@@ -246,7 +246,7 @@ std::string CoordTransformAffine::toXMLString() const {
 
   AutoPtr<Element> coordTransformTypeElement = pDoc->createElement("Type");
   coordTransformTypeElement->appendChild(
-      pDoc->createTextNode("CoordTransformAffine"));
+     AutoPtr<Node>(pDoc->createTextNode("CoordTransformAffine")));
   coordTransformElement->appendChild(coordTransformTypeElement);
 
   AutoPtr<Element> paramListElement = pDoc->createElement("ParameterList");
@@ -301,6 +301,7 @@ CoordTransformAffine::combineTransformations(CoordTransform *first,
                              "same as the # of input dimensions of second.");
   // Convert both inputs to affine matrices, if needed
   CoordTransformAffine *firstAff = dynamic_cast<CoordTransformAffine *>(first);
+  bool ownFirstAff(false);
   if (!firstAff) {
     CoordTransformAligned *firstAl =
         dynamic_cast<CoordTransformAligned *>(first);
@@ -310,9 +311,11 @@ CoordTransformAffine::combineTransformations(CoordTransform *first,
           "must be either CoordTransformAffine or CoordTransformAligned.");
     firstAff = new CoordTransformAffine(firstAl->getInD(), firstAl->getOutD());
     firstAff->setMatrix(firstAl->makeAffineMatrix());
+    ownFirstAff = true;
   }
   CoordTransformAffine *secondAff =
       dynamic_cast<CoordTransformAffine *>(second);
+  bool ownSecondAff(false);
   if (!secondAff) {
     CoordTransformAligned *secondAl =
         dynamic_cast<CoordTransformAligned *>(second);
@@ -323,15 +326,18 @@ CoordTransformAffine::combineTransformations(CoordTransform *first,
     secondAff =
         new CoordTransformAffine(secondAl->getInD(), secondAl->getOutD());
     secondAff->setMatrix(secondAl->makeAffineMatrix());
+    ownSecondAff = true;
   }
   // Initialize the affine matrix
   CoordTransformAffine *out =
       new CoordTransformAffine(firstAff->getInD(), secondAff->getOutD());
   // Multiply the two matrices together
   Matrix<coord_t> outMat = secondAff->getMatrix() * firstAff->getMatrix();
-  std::cout << "Creating combined matrix " << outMat << std::endl;
   // Set in the output
   out->setMatrix(outMat);
+  // Clean up
+  if(ownFirstAff) delete firstAff;
+  if(ownSecondAff) delete secondAff;
   return out;
 }
 
diff --git a/Code/Mantid/Framework/DataObjects/src/CoordTransformAffineParser.cpp b/Code/Mantid/Framework/DataObjects/src/CoordTransformAffineParser.cpp
index 2fa78604972253880b65cf7c2e89f8e072f58074..edc45647319f161071e123075b65ef9366cc52ed 100644
--- a/Code/Mantid/Framework/DataObjects/src/CoordTransformAffineParser.cpp
+++ b/Code/Mantid/Framework/DataObjects/src/CoordTransformAffineParser.cpp
@@ -42,7 +42,7 @@ Mantid::API::CoordTransform *CoordTransformAffineParser::createTransform(
 
   Element *paramListElement =
       coordTransElement->getChildElement("ParameterList");
-  Poco::XML::NodeList *parameters =
+  Poco::AutoPtr<Poco::XML::NodeList> parameters =
       paramListElement->getElementsByTagName("Parameter");
 
   // Add input dimension parameter.
diff --git a/Code/Mantid/Framework/DataObjects/src/CoordTransformAligned.cpp b/Code/Mantid/Framework/DataObjects/src/CoordTransformAligned.cpp
index e541a274f052e3c526086ffb0c46dd4e253c514b..7f2cbd045d418923d4023a129b8fb1822bcd57fe 100644
--- a/Code/Mantid/Framework/DataObjects/src/CoordTransformAligned.cpp
+++ b/Code/Mantid/Framework/DataObjects/src/CoordTransformAligned.cpp
@@ -38,12 +38,16 @@ CoordTransformAligned::CoordTransformAligned(const size_t inD,
   m_scaling = new coord_t[outD];
   for (size_t d = 0; d < outD; d++) {
     m_dimensionToBinFrom[d] = dimensionToBinFrom[d];
-    if (m_dimensionToBinFrom[d] >= inD)
+    if (m_dimensionToBinFrom[d] >= inD) {
+      delete [] m_dimensionToBinFrom;
+      delete [] m_origin;
+      delete [] m_scaling;
       throw std::runtime_error(
           "CoordTransformAligned::ctor(): invalid entry in "
           "dimensionToBinFrom[" +
           Mantid::Kernel::Strings::toString(d) +
           "]. Cannot build the coordinate transformation.");
+    }
     m_origin[d] = origin[d];
     m_scaling[d] = scaling[d];
   }
@@ -78,12 +82,16 @@ CoordTransformAligned::CoordTransformAligned(
   m_scaling = new coord_t[outD];
   for (size_t d = 0; d < outD; d++) {
     m_dimensionToBinFrom[d] = dimensionToBinFrom[d];
-    if (m_dimensionToBinFrom[d] >= inD)
+    if (m_dimensionToBinFrom[d] >= inD) {
+      delete [] m_dimensionToBinFrom;
+      delete [] m_origin;
+      delete [] m_scaling;
       throw std::runtime_error(
           "CoordTransformAligned::ctor(): invalid entry in "
           "dimensionToBinFrom[" +
           Mantid::Kernel::Strings::toString(d) +
           "]. Cannot build the coordinate transformation.");
+    }
     m_origin[d] = origin[d];
     m_scaling[d] = scaling[d];
   }
diff --git a/Code/Mantid/Framework/DataObjects/src/CoordTransformDistance.cpp b/Code/Mantid/Framework/DataObjects/src/CoordTransformDistance.cpp
index ee41225d04592fd9076a696825c402a033f970f8..ed863adc5c26f6c3ca7dcd4ae9bb6079d2ede5b3 100644
--- a/Code/Mantid/Framework/DataObjects/src/CoordTransformDistance.cpp
+++ b/Code/Mantid/Framework/DataObjects/src/CoordTransformDistance.cpp
@@ -112,7 +112,7 @@ std::string CoordTransformDistance::toXMLString() const {
 
   AutoPtr<Element> coordTransformTypeElement = pDoc->createElement("Type");
   coordTransformTypeElement->appendChild(
-      pDoc->createTextNode("CoordTransformDistance"));
+      AutoPtr<Text>(pDoc->createTextNode("CoordTransformDistance")));
   coordTransformElement->appendChild(coordTransformTypeElement);
 
   AutoPtr<Element> paramListElement = pDoc->createElement("ParameterList");
diff --git a/Code/Mantid/Framework/DataObjects/src/MDBoxBase.cpp b/Code/Mantid/Framework/DataObjects/src/MDBoxBase.cpp
index 30dc2b64a82a0d0b903e147f7d9fa59d8376cdfd..afc5f140685fec268832568583f8133a7cd8e15e 100644
--- a/Code/Mantid/Framework/DataObjects/src/MDBoxBase.cpp
+++ b/Code/Mantid/Framework/DataObjects/src/MDBoxBase.cpp
@@ -65,7 +65,7 @@ TMDE(MDBoxBase)::MDBoxBase(const MDBoxBase<MDE, nd> &box,
     : m_signal(box.m_signal), m_errorSquared(box.m_errorSquared),
       m_totalWeight(box.m_totalWeight), m_BoxController(otherBC),
       m_inverseVolume(box.m_inverseVolume), m_depth(box.m_depth),
-      m_parent(box.m_parent), m_fileID(box.m_fileID) {
+      m_parent(box.m_parent), m_fileID(box.m_fileID), m_dataMutex() {
 
   // Copy the extents
   for (size_t d = 0; d < nd; d++)
diff --git a/Code/Mantid/Framework/DataObjects/src/MDBoxFlatTree.cpp b/Code/Mantid/Framework/DataObjects/src/MDBoxFlatTree.cpp
index 3ff70adccbb15a821235e11dd5bfbfdbac8a03fb..4bbb537e1cd78f44d495132e0aac1a576c5cdef9 100644
--- a/Code/Mantid/Framework/DataObjects/src/MDBoxFlatTree.cpp
+++ b/Code/Mantid/Framework/DataObjects/src/MDBoxFlatTree.cpp
@@ -7,11 +7,13 @@
 #include "MantidDataObjects/MDEventFactory.h"
 #include <Poco/File.h>
 
+// clang-format off
 #if defined(__GLIBCXX__) && __GLIBCXX__ >= 20100121 // libstdc++-4.4.3
 typedef std::unique_ptr< ::NeXus::File> file_holder_type;
 #else
 typedef std::auto_ptr< ::NeXus::File> file_holder_type;
 #endif
+// clang-format on
 
 namespace Mantid {
 namespace DataObjects {
diff --git a/Code/Mantid/Framework/DataObjects/src/MDEventWorkspace.cpp b/Code/Mantid/Framework/DataObjects/src/MDEventWorkspace.cpp
index 4d80b6e407ec97bacaa1443a3fa7fa108d3669c2..6fe12748021e7675555bc45748cb5042b14c3aab 100644
--- a/Code/Mantid/Framework/DataObjects/src/MDEventWorkspace.cpp
+++ b/Code/Mantid/Framework/DataObjects/src/MDEventWorkspace.cpp
@@ -34,7 +34,8 @@ namespace DataObjects {
 /** Default constructor
  */
 TMDE(MDEventWorkspace)::MDEventWorkspace()
-    : data(NULL), m_BoxController(new BoxController(nd)), m_coordSystem(None) {
+    : API::IMDEventWorkspace(), data(NULL),
+      m_BoxController(new BoxController(nd)), m_coordSystem(None) {
   // First box is at depth 0, and has this default boxController
   data = new MDBox<MDE, nd>(m_BoxController.get(), 0);
 }
@@ -43,8 +44,8 @@ TMDE(MDEventWorkspace)::MDEventWorkspace()
 /** Copy constructor
  */
 TMDE(MDEventWorkspace)::MDEventWorkspace(const MDEventWorkspace<MDE, nd> &other)
-    : IMDEventWorkspace(other),
-      m_BoxController(other.m_BoxController->clone()) {
+    : IMDEventWorkspace(other), data(NULL),
+      m_BoxController(other.m_BoxController->clone()), m_coordSystem(other.m_coordSystem) {
 
   const MDBox<MDE, nd> *mdbox =
       dynamic_cast<const MDBox<MDE, nd> *>(other.data);
diff --git a/Code/Mantid/Framework/DataObjects/src/MDGridBox.cpp b/Code/Mantid/Framework/DataObjects/src/MDGridBox.cpp
index ffbbbb5348b0136a4c05eb416a06582456fba397..d03eb54542a77ee0bdd2b9cd5f04adcf3020215a 100644
--- a/Code/Mantid/Framework/DataObjects/src/MDGridBox.cpp
+++ b/Code/Mantid/Framework/DataObjects/src/MDGridBox.cpp
@@ -42,8 +42,8 @@ TMDE(MDGridBox)::MDGridBox(
     BoxController *const bc, const uint32_t depth,
     const std::vector<
         Mantid::Geometry::MDDimensionExtents<coord_t>> &extentsVector)
-    : MDBoxBase<MDE, nd>(bc, depth, UNDEF_SIZET, extentsVector), numBoxes(0),
-      nPoints(0) {
+    : MDBoxBase<MDE, nd>(bc, depth, UNDEF_SIZET, extentsVector),
+      numBoxes(0), m_Children(), diagonalSquared(0.f), nPoints(0) {
   initGridBox();
 }
 
@@ -58,11 +58,11 @@ TMDE(MDGridBox)::MDGridBox(
     const std::vector<
         Mantid::Geometry::MDDimensionExtents<coord_t>> &extentsVector)
     : MDBoxBase<MDE, nd>(bc.get(), depth, UNDEF_SIZET, extentsVector),
-      numBoxes(0), nPoints(0) {
+      numBoxes(0), m_Children(), diagonalSquared(0.f), nPoints(0) {
   initGridBox();
 }
 /// common part of MDGridBox contstructor;
-template <typename MDE, size_t nd> void MDGridBox<MDE, nd>::initGridBox() {
+template <typename MDE, size_t nd> size_t MDGridBox<MDE, nd>::initGridBox() {
   if (!this->m_BoxController)
     throw std::runtime_error(
         "MDGridBox::ctor(): No BoxController specified in box.");
@@ -86,6 +86,7 @@ template <typename MDE, size_t nd> void MDGridBox<MDE, nd>::initGridBox() {
   if (tot == 0)
     throw std::runtime_error(
         "MDGridBox::ctor(): Invalid splitting criterion (one was zero).");
+  return tot;
 }
 
 //-----------------------------------------------------------------------------------------------
@@ -93,41 +94,18 @@ template <typename MDE, size_t nd> void MDGridBox<MDE, nd>::initGridBox() {
  * @param box :: MDBox containing the events to split
  */
 TMDE(MDGridBox)::MDGridBox(MDBox<MDE, nd> *box)
-    : MDBoxBase<MDE, nd>(*box, box->getBoxController()), nPoints(0) {
-  if (!this->m_BoxController)
-    throw std::runtime_error("MDGridBox::ctor(): constructing from box:: No "
-                             "BoxController specified in box.");
-
-  //    std::cout << "Splitting MDBox ID " << box->getId() << " with " <<
-  //    box->getNPoints() << " events into MDGridBox" << std::endl;
-
-  // How many is it split?
-  // If we are at the top level and we have a specific top level split, then set it.
-  boost::optional<std::vector<size_t>> splitTopInto = this->m_BoxController->getSplitTopInto();
-  if (this->getDepth() == 0 && splitTopInto)
-  {
-    for (size_t d = 0; d < nd; d++)
-      split[d] = splitTopInto.get()[d];
-  }
-  else
-  {
-   for (size_t d = 0; d < nd; d++)
-    split[d] = this->m_BoxController->getSplitInto(d);
-  }
-
-  // Compute sizes etc.
-  size_t tot = computeSizesFromSplit();
-  if (tot == 0)
-    throw std::runtime_error("MDGridBox::ctor(): constructing from "
-                             "box::Invalid splitting criterion (one was "
-                             "zero).");
+    : MDBoxBase<MDE, nd>(*box, box->getBoxController()), split(),
+      splitCumul(), m_SubBoxSize(), numBoxes(0), m_Children(),
+      diagonalSquared(0.f), nPoints(0)
+{
+  size_t totalSize = initGridBox();
 
   double ChildVol(1);
   for (size_t d = 0; d < nd; d++)
     ChildVol *= m_SubBoxSize[d];
 
   // Splitting an input MDBox requires creating a bunch of children
-  fillBoxShell(tot, coord_t(1. / ChildVol));
+  fillBoxShell(totalSize, coord_t(1. / ChildVol));
 
   // Prepare to distribute the events that were in the box before, this will
   // load missing events from HDD in file based ws if there are some.
@@ -210,7 +188,7 @@ void MDGridBox<MDE, nd>::fillBoxShell(const size_t tot,
  */
 TMDE(MDGridBox)::MDGridBox(const MDGridBox<MDE, nd> &other,
                            Mantid::API::BoxController *const otherBC)
-    : MDBoxBase<MDE, nd>(other, otherBC), numBoxes(other.numBoxes),
+    : MDBoxBase<MDE, nd>(other, otherBC), numBoxes(other.numBoxes), m_Children(),
       diagonalSquared(other.diagonalSquared), nPoints(other.nPoints) {
   for (size_t d = 0; d < nd; d++) 
   {
@@ -437,7 +415,7 @@ TMDE(std::vector<MDE> *MDGridBox)::getEventsCopy() {
  */
 TMDE(void MDGridBox)::getBoxes(std::vector<API::IMDNode *> &outBoxes,
                                size_t maxDepth, bool leafOnly) {
-  // Add this box, unless we only want the leaves
+ //Add this box, unless we only want the leaves
   if (!leafOnly)
     outBoxes.push_back(this);
 
@@ -1315,7 +1293,9 @@ TMDE(void MDGridBox)::centroidSphere(CoordTransform &radiusTransform,
   } // (for each box)
 }
 //-----------------------------------------------------------------------------------------------
+// clang-format off
 GCC_DIAG_OFF(array-bounds)
+// clang-format on
 /** Integrate the signal within a sphere; for example, to perform single-crystal
  * peak integration.
  * The CoordTransform object could be used for more complex shapes, e.g.
@@ -1516,7 +1496,9 @@ TMDE(void MDGridBox)::integrateCylinder(
   delete[] verticesContained;
   delete[] boxMightTouch;
 }
+// clang-format off
 GCC_DIAG_ON(array-bounds)
+// clang-format on
 
 /**
 Getter for the masking status of the gridded box.
@@ -1660,7 +1642,7 @@ TMDE(void MDGridBox)::buildAndAddEventUnsafe(const signal_t Signal,
  * @param event :: reference to a MDLeanEvent to add.
  * */
 TMDE(inline void MDGridBox)::addEvent(const MDE &event) {
-  size_t index = 0;
+  size_t cindex = 0;
   for (size_t d = 0; d < nd; d++) {
     coord_t x = event.getCenter(d);
     int i = int((x - this->extents[d].getMin()) / m_SubBoxSize[d]);
@@ -1668,12 +1650,14 @@ TMDE(inline void MDGridBox)::addEvent(const MDE &event) {
     // if (i < 0 || i >= int(split[d])) return;
 
     // Accumulate the index
-    index += (i * splitCumul[d]);
+    cindex += (i * splitCumul[d]);
   }
 
   // Add it to the contained box
-  if (index < numBoxes) // avoid segfaults for floating point round-off errors.
-    m_Children[index]->addEvent(event);
+  // avoid segfaults for floating point round-off errors.
+  if (cindex < numBoxes) {
+    m_Children[cindex]->addEvent(event);
+  }
 }
 //-----------------------------------------------------------------------------------------------
 /** Add a single MDLeanEvent to the grid box. If the boxes
@@ -1692,18 +1676,19 @@ TMDE(inline void MDGridBox)::addEvent(const MDE &event) {
  * @param event :: reference to a MDEvent to add.
  * */
 TMDE(inline void MDGridBox)::addEventUnsafe(const MDE &event) {
-  size_t index = 0;
+  size_t cindex = 0;
   for (size_t d = 0; d < nd; d++) {
 
     coord_t x = event.getCenter(d);
     int i = int((x - this->extents[d].getMin()) / m_SubBoxSize[d]);
     // Accumulate the index
-    index += (i * splitCumul[d]);
+    cindex += (i * splitCumul[d]);
   }
 
   // Add it to the contained box
-  if (index < numBoxes) // avoid segfaults for floating point round-off errors.
-    m_Children[index]->addEventUnsafe(event);
+  if (cindex < numBoxes) {
+    m_Children[cindex]->addEventUnsafe(event);
+  }
 }
 
 /**Sets particular child MDgridBox at the index, specified by the input
diff --git a/Code/Mantid/Framework/DataObjects/src/MDHistoWorkspace.cpp b/Code/Mantid/Framework/DataObjects/src/MDHistoWorkspace.cpp
index 2ab9a0911192b3b58416bc817ca3cd2979f69d75..ffd19c151f406eb4a905239352a685e7aeae4964 100644
--- a/Code/Mantid/Framework/DataObjects/src/MDHistoWorkspace.cpp
+++ b/Code/Mantid/Framework/DataObjects/src/MDHistoWorkspace.cpp
@@ -12,6 +12,7 @@
 #include "MantidAPI/IMDIterator.h"
 #include <boost/scoped_array.hpp>
 #include <boost/make_shared.hpp>
+#include <boost/math/special_functions/fpclassify.hpp>
 
 using namespace Mantid::Kernel;
 using namespace Mantid::Geometry;
@@ -600,7 +601,12 @@ void MDHistoWorkspace::getLinePlot(const Mantid::Kernel::VMD &start,
           break;
         }
         // And add the normalized signal/error to the list too
-        y.push_back(this->getSignalAt(linearIndex) * normalizer);
+        auto signal = this->getSignalAt(linearIndex) * normalizer;
+        if (boost::math::isinf(signal)){
+          // The plotting library (qwt) doesn't like infs.
+          signal = std::numeric_limits<signal_t>::quiet_NaN();
+        }
+        y.push_back(signal);
         e.push_back(this->getErrorAt(linearIndex) * normalizer);
         // Save the position for next bin
         lastPos = pos;
diff --git a/Code/Mantid/Framework/DataObjects/src/MDHistoWorkspaceIterator.cpp b/Code/Mantid/Framework/DataObjects/src/MDHistoWorkspaceIterator.cpp
index c30405614890f9203f1efb2565a8265682b7cd2d..f18a82bc58547428832e5c940dd95d5af83acb72 100644
--- a/Code/Mantid/Framework/DataObjects/src/MDHistoWorkspaceIterator.cpp
+++ b/Code/Mantid/Framework/DataObjects/src/MDHistoWorkspaceIterator.cpp
@@ -205,7 +205,30 @@ size_t MDHistoWorkspaceIterator::getDataSize() const {
  * @param index :: point to jump to. Must be 0 <= index < getDataSize().
  */
 void MDHistoWorkspaceIterator::jumpTo(size_t index) {
-  m_pos = uint64_t(index + m_begin);
+    m_pos = uint64_t(index + m_begin);
+}
+
+/**
+ * Jump the iterator to the nearest valid position correspoinding to the centre current position of the desired iterator position.
+ * @param fromLocation : destination or nearest to.
+ * @return absolute distance of end position from requested position.
+ */
+Mantid::coord_t MDHistoWorkspaceIterator::jumpToNearest(const VMD& fromLocation)
+{
+
+    std::vector<size_t> indexes(m_nd);
+    coord_t sqDiff = 0;
+    for(size_t d = 0; d < m_nd; ++d) {
+        coord_t dExact = (fromLocation[d] - m_origin[d]) / m_binWidth[d]; // Index position in this space.
+        size_t dRound = size_t(dExact + 0.5); // Round to nearest bin edge.
+        sqDiff += (dExact - coord_t(dRound)) * (dExact - coord_t(dRound)) * m_binWidth[d] * m_binWidth[d];
+        indexes[d] = dRound;
+    }
+
+    const size_t linearIndex = Utils::NestedForLoop::GetLinearIndex(m_nd, &indexes[0],
+                                  m_indexMaker);
+    this->jumpTo(linearIndex);
+    return std::sqrt(sqDiff);
 }
 
 //----------------------------------------------------------------------------------------------
@@ -237,12 +260,14 @@ bool MDHistoWorkspaceIterator::next() {
   } else {
     ++m_pos;
   }
-  // Keep calling next if the current position is masked.
   bool ret = m_pos < m_max;
-  while (m_skippingPolicy->keepGoing()) {
-    ret = this->next();
-    if (!ret)
-      break;
+  if(ret) {
+    // Keep calling next if the current position is masked and still valid.
+    while (m_skippingPolicy->keepGoing()) {
+      ret = this->next();
+      if (!ret)
+        break;
+    }
   }
   // Go through every point;
   return ret;
@@ -323,16 +348,45 @@ Mantid::Kernel::VMD MDHistoWorkspaceIterator::getCenter() const {
   Utils::NestedForLoop::GetIndicesFromLinearIndex(m_nd, m_pos, m_indexMaker,
                                                   m_indexMax, m_index);
   // Find the center
-  for (size_t d = 0; d < m_nd; d++)
+  for (size_t d = 0; d < m_nd; ++d) {
     m_center[d] = m_origin[d] + (coord_t(m_index[d]) + 0.5f) * m_binWidth[d];
+  }
   return VMD(m_nd, m_center);
 }
 
+/**
+ * Get the extents in n-dimensions corresponding to the position of the box of the current iterator.
+ * @return pairs of min/max extents.
+ */
+VecMDExtents MDHistoWorkspaceIterator::getBoxExtents() const
+{
+
+    // Get the indexes.
+    Utils::NestedForLoop::GetIndicesFromLinearIndex(m_nd, m_pos, m_indexMaker,
+                                                    m_indexMax, m_index);
+    VecMDExtents extents(m_nd);
+    // Find the extents.
+    for (size_t d = 0; d < m_nd; ++d) {
+      const coord_t min = m_origin[d] + coord_t(m_index[d]) * m_binWidth[d]; // Min in d
+      const coord_t max = min + m_binWidth[d]; // Max in d
+      extents[d] = MDExtentPair(min, max);
+    }
+
+    return extents;
+}
+
 //----------------------------------------------------------------------------------------------
 /// Returns the number of events/points contained in this box
-/// @return 1 always: e.g. there is one (fake) event in the middle of the box.
+/// @return truncated number of events
 size_t MDHistoWorkspaceIterator::getNumEvents() const {
-  return static_cast<size_t>(m_ws->getNumEventsAt(m_pos));
+  return static_cast<size_t>(this->getNumEventsFraction());
+}
+
+//----------------------------------------------------------------------------------------------
+/// Returns the number of events/points contained in this box
+/// @return eact number of events (weights may be applied)
+signal_t MDHistoWorkspaceIterator::getNumEventsFraction() const {
+  return m_ws->getNumEventsAt(m_pos);
 }
 
 //----------------------------------------------------------------------------------------------
@@ -534,7 +588,8 @@ MDHistoWorkspaceIterator::findNeighbourIndexesByWidth(const std::vector<int>& wi
 
   // Filter out indexes that are are not actually neighbours.
   // Accumulate neighbour indexes.
-  std::vector<size_t> neighbourIndexes;
+  std::vector<size_t> neighbourIndexes(permutationsVertexTouching.size());
+  size_t nextFree = 0;
   for (size_t i = 0; i < permutationsVertexTouching.size(); ++i) {
     if (permutationsVertexTouching[i] == 0) {
       continue;
@@ -544,9 +599,10 @@ MDHistoWorkspaceIterator::findNeighbourIndexesByWidth(const std::vector<int>& wi
     if (neighbour_index < m_ws->getNPoints() &&
         Utils::isNeighbourOfSubject(m_nd, neighbour_index, m_index,
                                     m_indexMaker, m_indexMax, widths) ) {
-      neighbourIndexes.push_back(neighbour_index);
+      neighbourIndexes[nextFree++] = neighbour_index;
     }
   }
+  neighbourIndexes.resize(nextFree);
 
   // Remove duplicates
   std::sort(neighbourIndexes.begin(), neighbourIndexes.end());
diff --git a/Code/Mantid/Framework/DataObjects/src/Workspace2D.cpp b/Code/Mantid/Framework/DataObjects/src/Workspace2D.cpp
index 36c116864efa0dd5de20e9b23d51ce3752a3ead0..3498393dc535b1c6a77e0a38a22d1a6248e7c216 100644
--- a/Code/Mantid/Framework/DataObjects/src/Workspace2D.cpp
+++ b/Code/Mantid/Framework/DataObjects/src/Workspace2D.cpp
@@ -23,15 +23,13 @@ Workspace2D::Workspace2D() {}
 Workspace2D::~Workspace2D() {
 // Clear out the memory
 
-// The omp loop is here primarily MSVC. On MSVC 2012
-// when you allocate memory in a multithreaded loop, like our cow_ptrs will do,
-// the deallocation time increases by a huge amount if the memory is just
-// naively deallocated in a serial order. This is because when it was allocated
-// in the omp loop then the actual memory ends up being interleaved and
-// then trying to deallocate this serially leads to lots of swapping in and out
-// of
-// memory.
-// See
+// The omp loop is here primarily MSVC. On MSVC 2012 when you allocate
+// memory in a multithreaded loop, like our cow_ptrs will do, the
+// deallocation time increases by a huge amount if the memory is just
+// naively deallocated in a serial order. This is because when it was
+// allocated in the omp loop then the actual memory ends up being
+// interleaved and then trying to deallocate this serially leads to
+// lots of swapping in and out of memory. See
 // http://social.msdn.microsoft.com/Forums/en-US/2fe4cfc7-ca5c-4665-8026-42e0ba634214/visual-studio-2012-slow-deallocation-when-new-called-within-openmp-loop?forum=vcgeneral
 
 #ifdef _MSC_VER
@@ -42,13 +40,17 @@ Workspace2D::~Workspace2D() {
   }
 }
 
-/** Sets the size of the workspace and initializes arrays to zero
-*  @param NVectors :: The number of vectors/histograms/detectors in the
-* workspace
-*  @param XLength :: The number of X data points/bin boundaries in each vector
-* (must all be the same)
-*  @param YLength :: The number of data/error points in each vector (must all be
-* the same)
+/**
+ * Sets the size of the workspace and initializes arrays to zero
+ *
+ * @param NVectors :: The number of vectors/histograms/detectors in the
+ * workspace
+ *
+ * @param XLength :: The number of X data points/bin boundaries in each vector
+ * (must all be the same)
+ *
+ * @param YLength :: The number of data/error points in each vector (must all be
+ * the same)
 */
 void Workspace2D::init(const std::size_t &NVectors, const std::size_t &XLength,
                        const std::size_t &YLength) {
@@ -90,7 +92,9 @@ size_t Workspace2D::size() const { return data.size() * blocksize(); }
 
 /// get the size of each vector
 size_t Workspace2D::blocksize() const {
-  return (data.size() > 0) ? static_cast<ISpectrum const *>(data[0])->dataY().size() : 0;
+  return (data.size() > 0)
+             ? static_cast<ISpectrum const *>(data[0])->dataY().size()
+             : 0;
 }
 
 /**
@@ -118,16 +122,27 @@ void Workspace2D::setImageE(const MantidImage &image, size_t start,
 }
 
 /**
-  * Copy the data from an image to the (Y's) and the errors for this workspace.
+  * Copy the data from an image to the (Y's) and the errors for this
+  * workspace.
+  *
   * @param imageY :: An image to copy the data from.
   * @param imageE :: An image to copy the errors from.
   * @param start :: Startinf workspace indx to copy data to.
+  *
+  * @param loadAsRectImg :: load using one histogram per row and one
+  * bin per column, instead of the default one histogram per pixel
+  *
+  * @param scale_1 :: scale factor for the X axis (norammly
+  * representing the inverse of the pixel width or similar.
+  *
   * @param parallelExecution :: Should inner loop run as parallel operation
   */
-
 void Workspace2D::setImageYAndE(const API::MantidImage &imageY,
                                 const API::MantidImage &imageE, size_t start,
+                                bool loadAsRectImg, double scale_1,
                                 bool parallelExecution) {
+  UNUSED_ARG(parallelExecution) // for parallel for
+
   if (imageY.empty() && imageE.empty())
     return;
   if (imageY.empty() && imageE[0].empty())
@@ -135,14 +150,15 @@ void Workspace2D::setImageYAndE(const API::MantidImage &imageY,
   if (imageE.empty() && imageY[0].empty())
     return;
 
-  if (blocksize() != 1) {
+  if (!loadAsRectImg && blocksize() != 1) {
     throw std::runtime_error(
-        "Cannot set image: a single bin workspace is expected.");
+        "Cannot set image in workspace: a single bin workspace is "
+        "required when initializing a workspace from an "
+        "image using a histogram per pixel.");
   }
 
   size_t height;
   size_t width;
-
   if (!imageY.empty()) {
     height = imageY.size();
     width = imageY.front().size();
@@ -152,30 +168,64 @@ void Workspace2D::setImageYAndE(const API::MantidImage &imageY,
   }
   size_t dataSize = width * height;
 
-  if (start + dataSize > getNumberHistograms()) {
+  if (start + dataSize > getNumberHistograms() * blocksize()) {
     throw std::runtime_error(
         "Cannot set image: image is bigger than workspace.");
   }
 
-  PARALLEL_FOR_IF(parallelExecution)
-  for (int i = 0; i < static_cast<int>(height); ++i) {
-    const auto &rowY = imageY[i];
-    const auto &rowE = imageE[i];
-
-    size_t spec = start + static_cast<size_t>(i) * width;
-    auto rowYEnd = rowY.end();
-    auto rowEEnd = rowE.end();
-
-    auto pixelE = rowE.begin();
-    for (auto pixelY = rowY.begin(); pixelY != rowYEnd && pixelE != rowEEnd;
-         ++pixelY, ++pixelE, ++spec) {
-      if (rowY.begin() != rowY.end())
-        (*data[spec]).dataY()[0] = *pixelY;
-      if (rowE.begin() != rowE.end())
-        (*data[spec]).dataE()[0] = *pixelE;
+  if (!loadAsRectImg) {
+    // 1 pixel - one spectrum
+    PARALLEL_FOR_IF(parallelExecution)
+    for (int i = 0; i < static_cast<int>(height); ++i) {
+
+      const auto &rowY = imageY[i];
+      const auto &rowE = imageE[i];
+      size_t spec = start + static_cast<size_t>(i) * width;
+      auto pE = rowE.begin();
+      for (auto pY = rowY.begin(); pY != rowY.end() && pE != rowE.end();
+           ++pY, ++pE, ++spec) {
+        data[spec]->dataY()[0] = *pY;
+        data[spec]->dataE()[0] = *pE;
+      }
+    }
+  } else {
+
+    if (height != (getNumberHistograms()))
+      throw std::runtime_error(
+          std::string("To load an image into a workspace with one spectrum per "
+                      "row, then number of spectra (") +
+          boost::lexical_cast<std::string>(getNumberHistograms()) +
+          ") needs to be equal to the height (rows) of the image (" +
+          boost::lexical_cast<std::string>(height) + ")");
+
+    if (width != blocksize())
+      throw std::runtime_error(
+          std::string("To load an image into a workspace with one spectrum per "
+                      "row, then number of bins (") +
+          boost::lexical_cast<std::string>(blocksize()) +
+          ") needs to be equal to the width (columns) of the image (" +
+          boost::lexical_cast<std::string>(width) + ")");
+
+    // one spectrum - one row
+    PARALLEL_FOR_IF(parallelExecution)
+    for (int i = 0; i < static_cast<int>(height); ++i) {
+
+      const auto &rowY = imageY[i];
+      const auto &rowE = imageE[i];
+      data[i]->dataY() = rowY;
+      data[i]->dataE() = rowE;
+    }
+    // X values. Set first spectrum and copy/propagate that one to all the other
+    // spectra
+    PARALLEL_FOR_IF(parallelExecution)
+    for (int i = 0; i < static_cast<int>(width) + 1; ++i) {
+      data[0]->dataX()[i] = i * scale_1;
+    }
+    PARALLEL_FOR_IF(parallelExecution)
+    for (int i = 1; i < static_cast<int>(height); ++i) {
+      data[i]->setX(data[0]->dataX());
     }
   }
-  UNUSED_ARG(parallelExecution)
 }
 
 //--------------------------------------------------------------------------------------------
diff --git a/Code/Mantid/Framework/DataObjects/test/CoordTransformAffineParserTest.h b/Code/Mantid/Framework/DataObjects/test/CoordTransformAffineParserTest.h
index 92c4bf5c06da74e2ca336c010897d8928e1c3483..4667200c054884de93535291d995afc60946ec9d 100644
--- a/Code/Mantid/Framework/DataObjects/test/CoordTransformAffineParserTest.h
+++ b/Code/Mantid/Framework/DataObjects/test/CoordTransformAffineParserTest.h
@@ -43,7 +43,6 @@ public:
 
    CoordTransformAffineParser parser;
    CoordTransformAffine* transform = dynamic_cast<CoordTransformAffine*>(parser.createTransform(pRootElem));
-
    AffineMatrixType product = transform->getMatrix();
 
    //Check that matrix is recovered.
diff --git a/Code/Mantid/Framework/DataObjects/test/CoordTransformAffineTest.h b/Code/Mantid/Framework/DataObjects/test/CoordTransformAffineTest.h
index 3616f51a39bbc614fee263ab2930158a412232d7..1bfbeaefa8e9d872145d9fb4b9a699f0bc3be07e 100644
--- a/Code/Mantid/Framework/DataObjects/test/CoordTransformAffineTest.h
+++ b/Code/Mantid/Framework/DataObjects/test/CoordTransformAffineTest.h
@@ -11,8 +11,8 @@
 #include "MantidDataObjects/CoordTransformDistance.h"
 #include "MantidDataObjects/MDEventFactory.h"
 #include <cxxtest/TestSuite.h>
-#include <iomanip>
-#include <iostream>
+
+#include <boost/scoped_ptr.hpp>
 
 using namespace Mantid;
 using namespace Mantid::Kernel;
@@ -113,7 +113,7 @@ public:
     ct.addTranslation(translation);
 
     // Clone and check the clone works
-    CoordTransform * clone = ct.clone();
+    boost::scoped_ptr<CoordTransform> clone(ct.clone());
     clone->apply(in, out);
     compare(2, out, expected);
   }
@@ -269,7 +269,9 @@ public:
     TSM_ASSERT_THROWS_ANYTHING("Null input fails.", CoordTransformAffine::combineTransformations(NULL, &ct43) );
     TSM_ASSERT_THROWS_ANYTHING("Incompatible # of dimensions", CoordTransformAffine::combineTransformations(&ct42, &ct32) );
     TSM_ASSERT_THROWS_ANYTHING("Incompatible # of dimensions", CoordTransformAffine::combineTransformations(&ct32, &ct43) );
-    TSM_ASSERT_THROWS_NOTHING("Compatible # of dimensions", CoordTransformAffine::combineTransformations(&ct43, &ct32) );
+    CoordTransformAffine *ct(NULL);
+    TSM_ASSERT_THROWS_NOTHING("Compatible # of dimensions", ct = CoordTransformAffine::combineTransformations(&ct43, &ct32) );
+    delete ct;
     coord_t center[3] = {1,2,3};
     bool bools[3] = {true, true, true};
     CoordTransformDistance ctd(3, center, bools);
@@ -291,7 +293,7 @@ public:
     CoordTransformAffine ct2(2,2);
     ct2.addTranslation(translation2);
     // Combine them
-    CoordTransformAffine * combined = CoordTransformAffine::combineTransformations(&ct1, &ct2);
+    boost::scoped_ptr<CoordTransformAffine> combined(CoordTransformAffine::combineTransformations(&ct1, &ct2));
     combined->apply(in, out);
     compare(2, out, expected);
   }
@@ -311,7 +313,7 @@ public:
     ct2->apply(out1, out2);
 
     // Combine them
-    CoordTransformAffine * combined = CoordTransformAffine::combineTransformations(ct1, ct2);
+    boost::scoped_ptr<CoordTransformAffine> combined(CoordTransformAffine::combineTransformations(ct1, ct2));
     combined->apply(in, out_combined);
 
     // Applying the combined one = same as each one in sequence
@@ -434,4 +436,3 @@ public:
 
 
 #endif /* MANTID_DATAOBJECTS_COORDTRANSFORMAFFINETEST_H_ */
-
diff --git a/Code/Mantid/Framework/DataObjects/test/CoordTransformAlignedTest.h b/Code/Mantid/Framework/DataObjects/test/CoordTransformAlignedTest.h
index 7585b31134d9dc4e1145dd6daa924913cacf3522..6163cc2db8827204d4743c6bcdd8ed636f56e574 100644
--- a/Code/Mantid/Framework/DataObjects/test/CoordTransformAlignedTest.h
+++ b/Code/Mantid/Framework/DataObjects/test/CoordTransformAlignedTest.h
@@ -11,6 +11,8 @@
 #include "MantidKernel/Matrix.h"
 #include "MantidDataObjects/CoordTransformAffine.h"
 
+#include <boost/scoped_ptr.hpp>
+
 using namespace Mantid;
 using namespace Mantid::DataObjects;
 using namespace Mantid::API;
@@ -28,10 +30,12 @@ public:
     size_t dimToBinFrom[3] = {4, 1, 0};
     coord_t origin[3] = {5, 10, 15};
     coord_t scaling[3] = {1, 2, 3};
-    TSM_ASSERT_THROWS_ANYTHING( "DimtoBinFrom has too high an index", CoordTransformAligned ct(4,3, dimToBinFrom, origin, scaling); );
+    TSM_ASSERT_THROWS_ANYTHING( "DimtoBinFrom has too high an index", 
+                                 CoordTransformAligned(4,3, dimToBinFrom, origin, scaling) );
     std::vector<size_t> d(3);
     std::vector<coord_t> o(2), s(3);
-    TSM_ASSERT_THROWS_ANYTHING( "Non-matching vector lengths", CoordTransformAligned ct(3,3, d,o,s); );
+    TSM_ASSERT_THROWS_ANYTHING( "Non-matching vector lengths",
+                                 CoordTransformAligned(3,3, d,o,s) );
   }
 
   /** Construct from vector */
@@ -74,7 +78,7 @@ public:
     coord_t origin[3] = {5, 10, 15};
     coord_t scaling[3] = {1, 2, 3};
     CoordTransformAligned ct(4,3, dimToBinFrom, origin, scaling);
-    CoordTransform * clone = ct.clone();
+    boost::scoped_ptr<CoordTransform> clone(ct.clone());
 
     coord_t input[4] = {16, 11, 11111111 /*ignored*/, 6};
     coord_t output[3] = {0,0,0};
diff --git a/Code/Mantid/Framework/DataObjects/test/CoordTransformDistanceTest.h b/Code/Mantid/Framework/DataObjects/test/CoordTransformDistanceTest.h
index d014723917d32c71f2f614a80360dd27fad509ca..fb87f3f7a955691085570660a142217bd4216c87 100644
--- a/Code/Mantid/Framework/DataObjects/test/CoordTransformDistanceTest.h
+++ b/Code/Mantid/Framework/DataObjects/test/CoordTransformDistanceTest.h
@@ -9,6 +9,8 @@
 #include <iostream>
 #include "MantidAPI/CoordTransform.h"
 
+#include <boost/scoped_ptr.hpp>
+
 using namespace Mantid;
 using namespace Mantid::DataObjects;
 using Mantid::API::CoordTransform;
@@ -30,13 +32,14 @@ public:
     bool used[4] = {true, false, true, true};
     CoordTransformDistance ct(4, center, used);
     // A copy was made
-    TS_ASSERT_DIFFERS(ct.getCenter(), center);
+    const coord_t *transformCentres = ct.getCenter();
+    TS_ASSERT_DIFFERS(transformCentres, center);
+    const bool * usedDims = ct.getDimensionsUsed();
     TS_ASSERT_DIFFERS(ct.getDimensionsUsed(), used);
-
     // Contents are good
     compare(4, center, ct.getCenter());
     for (size_t i=0; i<4; i++)
-      TS_ASSERT_EQUALS( used[i], ct.getDimensionsUsed()[i]);
+      TS_ASSERT_EQUALS( used[i], usedDims[i]);
   }
 
 
@@ -48,7 +51,7 @@ public:
     bool used[2] = {true, true};
     CoordTransformDistance ct(2,center,used);
 
-    CoordTransform * clone = ct.clone();
+    boost::scoped_ptr<CoordTransform> clone(ct.clone());
     coord_t out = 0;
     coord_t in1[2] = {0, 3};
     TS_ASSERT_THROWS_NOTHING( clone->apply(in1, &out) );
diff --git a/Code/Mantid/Framework/DataObjects/test/MDBoxBaseTest.h b/Code/Mantid/Framework/DataObjects/test/MDBoxBaseTest.h
index 6f6125c1ec44a3f6c7dae5828af0bea457ca891b..c0efc3014edda7d1992f099f4726094afa2dae0b 100644
--- a/Code/Mantid/Framework/DataObjects/test/MDBoxBaseTest.h
+++ b/Code/Mantid/Framework/DataObjects/test/MDBoxBaseTest.h
@@ -249,6 +249,7 @@ public:
     MDBoxBaseTester<MDLeanEvent<3>,3> c(b);
     TS_ASSERT_EQUALS( c.getParent(), daddy);
 
+    delete daddy;
   }
 
   /** Setting and getting the extents;
@@ -432,15 +433,14 @@ public:
     delete [] v;
   }
 
-  void test_sortBoxesByFilePos()
+  void xtest_sortBoxesByFilePos()
   {
-    std::vector<API::IMDNode *> boxes;
-    // 10 to 1 in reverse order
-
-    for (uint64_t i=0; i<10; i++)
-    {
-      boxes.push_back(new MDBoxBaseTester<MDLeanEvent<1>,1>(10-i));
-    }
+//    std::vector<API::IMDNode *> boxes;
+//    // 10 to 1 in reverse order
+//    for (uint64_t i=0; i<10; i++)
+//    {
+//      boxes.push_back(new MDBoxBaseTester<MDLeanEvent<1>,1>(10-i));
+//    }
     //TODO:
     //Kernel::ISaveable::sortObjByFilePos(boxes);
     //// After sorting, they are in the right order 1,2,3, etc.
diff --git a/Code/Mantid/Framework/DataObjects/test/MDBoxFlatTreeTest.h b/Code/Mantid/Framework/DataObjects/test/MDBoxFlatTreeTest.h
index 4bdcfbc47339c9365c8b0cbb4e9ea3651e5b091a..4c1f956f877dbb2aad714314f94bc6de4c4d8f5b 100644
--- a/Code/Mantid/Framework/DataObjects/test/MDBoxFlatTreeTest.h
+++ b/Code/Mantid/Framework/DataObjects/test/MDBoxFlatTreeTest.h
@@ -78,7 +78,18 @@ public:
       }
     }
 
-
+    // Clean up MDGridBoxes as they will take care of their children
+    // If we delete directly in the first loop over then the pointers later in the list
+    // become invalid
+    std::vector<size_t> gridIndices;
+    for(size_t i = 0; i < Boxes.size(); ++i) {
+      if(!Boxes[i]->isBox()) gridIndices.push_back(i);
+    }
+    for(size_t i = 0; i < gridIndices.size(); ++i) {
+      delete Boxes[gridIndices[i]];
+    }
+    
+    // Clean up file
     if(testFile.exists())
       testFile.remove();
   }
diff --git a/Code/Mantid/Framework/DataObjects/test/MDBoxIteratorTest.h b/Code/Mantid/Framework/DataObjects/test/MDBoxIteratorTest.h
index 813299daa61593297fe750fb084e95521653adb5..2ace33cd724bf794b5f53456417f7246afe0315d 100644
--- a/Code/Mantid/Framework/DataObjects/test/MDBoxIteratorTest.h
+++ b/Code/Mantid/Framework/DataObjects/test/MDBoxIteratorTest.h
@@ -79,6 +79,12 @@ public:
     D212 = dynamic_cast<ibox_t *>(C21->getChild(2));
     D213 = dynamic_cast<ibox_t *>(C21->getChild(3));
   }
+  
+  void tearDown()
+  {
+    delete A->getBoxController();
+    delete A;
+  }
 
   //--------------------------------------------------------------------------------------
   void test_ctor_with_null_box_fails()
@@ -125,6 +131,8 @@ public:
     // Calling next again does not cause problems.
     TS_ASSERT( !it->next() );
     TS_ASSERT( !it->next() );
+
+    delete it;
   }
 
   void test_depth_limit_1()
@@ -138,6 +146,8 @@ public:
     TS_ASSERT( nextIs(it, B3) );
     TS_ASSERT( !it->next() );
     TS_ASSERT( !it->next() );
+
+    delete it;
   }
 
   void test_depth_limit_0()
@@ -147,6 +157,8 @@ public:
     TS_ASSERT_EQUALS( it->getBox(), A);
     TS_ASSERT( !it->next() );
     TS_ASSERT( !it->next() );
+
+    delete it;
   }
 
   void test_starting_deeper()
@@ -160,6 +172,8 @@ public:
     TS_ASSERT( nextIs(it, C03) );
     TS_ASSERT( !it->next() );
     TS_ASSERT( !it->next() );
+
+    delete it;
   }
 
   void test_leaf_only()
@@ -184,6 +198,8 @@ public:
     // No more!
     TS_ASSERT( !it->next() );
     TS_ASSERT( !it->next() );
+
+    delete it;
   }
 
   void test_leaf_only_depth_2()
@@ -204,6 +220,8 @@ public:
     TS_ASSERT( nextIs(it, B3) );
     TS_ASSERT( !it->next() );
     TS_ASSERT( !it->next() );
+
+    delete it;
   }
 
   void test_leaf_only_depth_1()
@@ -217,6 +235,8 @@ public:
     TS_ASSERT( nextIs(it, B3) );
     TS_ASSERT( !it->next() );
     TS_ASSERT( !it->next() );
+
+    delete it;
   }
 
   void test_leaf_only_depth_0()
@@ -227,6 +247,8 @@ public:
     TS_ASSERT_EQUALS( it->getBox(), A);
     TS_ASSERT( !it->next() );
     TS_ASSERT( !it->next() );
+
+    delete it;
   }
 
   void test_leaf_only_starting_deeper()
@@ -242,6 +264,8 @@ public:
     TS_ASSERT( nextIs(it, C23) );
     TS_ASSERT( !it->next() );
     TS_ASSERT( !it->next() );
+    
+    delete it;
   }
 
   void test_leaf_only_starting_deeper_depth_limited()
@@ -254,6 +278,8 @@ public:
     TS_ASSERT( nextIs(it, C23) );
     TS_ASSERT( !it->next() );
     TS_ASSERT( !it->next() );
+
+    delete it;
   }
 
   //--------------------------------------------------------------------------------------
@@ -271,6 +297,8 @@ public:
 
     BoxController *const bc = A->getBoxController();
     delete bc;
+    delete it;
+    delete A;
   }
 
   //--------------------------------------------------------------------------------------
@@ -302,7 +330,8 @@ public:
 
     BoxController *const bc = A->getBoxController();
     delete bc;
-
+    delete it;
+    delete A;
   }
   //--------------------------------------------------------------------------------------
   void test_iterator_withImplicitFunction_above11()
@@ -314,6 +343,7 @@ public:
 
     // Create an iterator
     it = new MDBoxIterator<MDLeanEvent<1>,1>(A, 20, false, func);
+    delete func;
 
     // Start with the top one
     TS_ASSERT_EQUALS( it->getBox(), A);
@@ -335,6 +365,8 @@ public:
     // No more!
     TS_ASSERT( !it->next() );
     TS_ASSERT( !it->next() );
+
+    delete it;
   }
 
   //--------------------------------------------------------------------------------------
@@ -347,6 +379,7 @@ public:
 
     // Create an iterator
     it = new MDBoxIterator<MDLeanEvent<1>,1>(A, 20, true, func);
+    delete func;
 
     // C00-C01 are outside the range, so the first one is C02
     TS_ASSERT_EQUALS( it->getBox(), C02);
@@ -363,6 +396,8 @@ public:
     // No more!
     TS_ASSERT( !it->next() );
     TS_ASSERT( !it->next() );
+
+    delete it;
   }
 
 
@@ -376,6 +411,7 @@ public:
 
     // Create an iterator
     it = new MDBoxIterator<MDLeanEvent<1>,1>(A, 20, false, func);
+    delete func;
 
     // Start with the top one
     TS_ASSERT_EQUALS( it->getBox(), A);
@@ -394,6 +430,8 @@ public:
     // No more!
     TS_ASSERT( !it->next() );
     TS_ASSERT( !it->next() );
+
+    delete it;
   }
 
 
@@ -408,6 +446,7 @@ public:
 
     // Create an iterator
     it = new MDBoxIterator<MDLeanEvent<1>,1>(A, 20, false, func);
+    delete func;
 
     // Go down to the only two leaf boxes that are in range
     TS_ASSERT_EQUALS( it->getBox(), A);
@@ -418,6 +457,8 @@ public:
     // No more!
     TS_ASSERT( !it->next() );
     TS_ASSERT( !it->next() );
+
+    delete it;
   }
 
   //--------------------------------------------------------------------------------------
@@ -431,6 +472,7 @@ public:
 
     // Create an iterator
     it = new MDBoxIterator<MDLeanEvent<1>,1>(A, 20, true, func);
+    delete func;
 
     // Only two leaf boxes are in range
     TS_ASSERT_EQUALS( it->getBox(), D211);
@@ -438,6 +480,8 @@ public:
     // No more!
     TS_ASSERT( !it->next() );
     TS_ASSERT( !it->next() );
+
+    delete it;
   }
 
   //--------------------------------------------------------------------------------------
@@ -449,11 +493,14 @@ public:
 
     // Create an iterator
     it = new MDBoxIterator<MDLeanEvent<1>,1>(A, 20, false, func);
+    delete func;
 
     // Returns the first box but that's it
     TS_ASSERT_EQUALS( it->getBox(), A);
     TS_ASSERT( !it->next() );
     TS_ASSERT( !it->next() );
+    
+    delete it;
   }
 
   //--------------------------------------------------------------------------------------
@@ -465,10 +512,14 @@ public:
 
     // Create an iterator
     it = new MDBoxIterator<MDLeanEvent<1>,1>(A, 20, true, func);
+    delete func;
+    
     // Nothing in the iterator!
     TS_ASSERT_EQUALS( it->getDataSize(), 0);
     TS_ASSERT( !it->next() );
     TS_ASSERT( !it->next() );
+
+    delete it;
   }
 
   void test_getIsMasked()
@@ -542,6 +593,9 @@ public:
     TSM_ASSERT_EQUALS("Should NOT have skipped to the second box", 2, evaluationIterator->getPosition());
     TS_ASSERT_THROWS_NOTHING(evaluationIterator->next());
     TSM_ASSERT_EQUALS("Should NOT have skipped to the third box", 3, evaluationIterator->getPosition());
+
+    delete setupIterator;
+    delete evaluationIterator;
   }
 
   void test_custom_skipping_policy()
diff --git a/Code/Mantid/Framework/DataObjects/test/MDBoxSaveableTest.h b/Code/Mantid/Framework/DataObjects/test/MDBoxSaveableTest.h
index 7b4897705b131b7907e13a66dfbb1c914f08a1f8..52f6f8f8e59c2a1b0ff1526de10e725f27f0e7c4 100644
--- a/Code/Mantid/Framework/DataObjects/test/MDBoxSaveableTest.h
+++ b/Code/Mantid/Framework/DataObjects/test/MDBoxSaveableTest.h
@@ -1,6 +1,7 @@
 #ifndef MDBOX_SAVEABLE_TEST_H
 #define MDBOX_SAVEABLE_TEST_H
 
+#include <boost/scoped_ptr.hpp>
 #include <cxxtest/TestSuite.h>
 #include <map>
 #include <memory>
@@ -266,6 +267,8 @@ static void destroySuite(MDBoxSaveableTest * suite) { delete suite; }
     TSM_ASSERT_EQUALS( "Child is NOT on disk", b->getISaveable()->wasSaved(), false);
 
     bc->getFileIO()->closeFile();      
+    delete gb;
+    delete c;
     do_deleteNexusFile("MDGridBoxTest.nxs");
   }
 
@@ -745,7 +748,7 @@ static void destroySuite(MDBoxSaveableTest * suite) { delete suite; }
 
    
     // Create the grid box and make it file-backed.
-    MDBoxBase<MDE,2> * b = MDEventsTestHelper::makeMDGridBox<2>();
+    MDBoxBase<MDE,2> *b = MDEventsTestHelper::makeMDGridBox<2>();
     // box controlled is owned by the workspace, so here we make shared pointer from the box pointer as it is owned by this function
     BoxController_sptr spBc = boost::shared_ptr<BoxController >(b->getBoxController());
 
@@ -814,7 +817,7 @@ static void destroySuite(MDBoxSaveableTest * suite) { delete suite; }
     TSM_ASSERT_LESS_THAN("And the events were properly saved sequentially in the files.", minimumSaved, maxFilePos);
     std::cout << dbuf->getMemoryStr() << std::endl;
     
-
+    delete b;
     const std::string filename = fbc->getFileName();
     fbc->closeFile();
     if (Poco::File(filename).exists()) Poco::File(filename).remove();
diff --git a/Code/Mantid/Framework/DataObjects/test/MDBoxTest.h b/Code/Mantid/Framework/DataObjects/test/MDBoxTest.h
index be79dd888761334727d80d592de6416f4a1045d0..65cf4d1f6ed93acbdd1735d14cf7d367a23897d5 100644
--- a/Code/Mantid/Framework/DataObjects/test/MDBoxTest.h
+++ b/Code/Mantid/Framework/DataObjects/test/MDBoxTest.h
@@ -390,10 +390,10 @@ static void destroySuite(MDBoxTest * suite) { delete suite; }
     b.addEvent(ev);
     b.addEvent(ev);
     b.addEvent(ev);
-    std::vector<MDLeanEvent<2> > * events;
-    events = b.getEventsCopy();
+    std::vector<MDLeanEvent<2> > * events = b.getEventsCopy();
     TS_ASSERT_EQUALS( events->size(), 3);
     TS_ASSERT_EQUALS( (*events)[2].getSignal(), 4.0);
+    delete events;
   }
 
   void test_sptr()
diff --git a/Code/Mantid/Framework/DataObjects/test/MDEventWorkspaceTest.h b/Code/Mantid/Framework/DataObjects/test/MDEventWorkspaceTest.h
index 98fed03ff3a89748733ec17843fc678840b0fce9..02a1faa6b52b48140325fa4aab142dac3938d80e 100644
--- a/Code/Mantid/Framework/DataObjects/test/MDEventWorkspaceTest.h
+++ b/Code/Mantid/Framework/DataObjects/test/MDEventWorkspaceTest.h
@@ -52,8 +52,8 @@ private:
       }
       it->next(1); //Doesn't perform skipping on masked, bins, but next() does.
     }
-    return numberMasked;
     delete it;
+    return numberMasked;
   }
 
 public:
@@ -62,13 +62,6 @@ public:
   static MDEventWorkspaceTest *createSuite() { return new MDEventWorkspaceTest(); }
   static void destroySuite( MDEventWorkspaceTest *suite ) { delete suite; }
 
-  bool DODEBUG;
-  MDEventWorkspaceTest()
-  {
-    DODEBUG = false;
-  }
-
-
   void test_constructor()
   {
     MDEventWorkspace<MDLeanEvent<3>, 3> ew3;
@@ -98,13 +91,15 @@ public:
   {
     MDEventWorkspace<MDLeanEvent<3>, 3> ew3;
     
-    for (size_t i=0; i<3; i++)
+    for (size_t i=0; i<3; i++) {
       ew3.addDimension( MDHistoDimension_sptr(new MDHistoDimension("x","x","m",-1,1,0)) );
+    }
     ew3.initialize();
     ew3.getBoxController()->setSplitThreshold(1);
-    ew3.addEvent( MDLeanEvent<3>(1.0, 1.0) );
-    ew3.addEvent( MDLeanEvent<3>(2.0, 2.0) );
-    ew3.addEvent( MDLeanEvent<3>(3.0, 3.0) );
+    const coord_t centers[3] = {1.0f, 2.0f, 3.0f};
+    ew3.addEvent( MDLeanEvent<3>(1.0, 1.0, centers) );
+    ew3.addEvent( MDLeanEvent<3>(2.0, 2.0, centers) );
+    ew3.addEvent( MDLeanEvent<3>(3.0, 3.0, centers) );
     ew3.splitBox();
 
     ExperimentInfo_sptr ei(new ExperimentInfo);
@@ -119,7 +114,7 @@ public:
     TSM_ASSERT_DIFFERS( "Dimensions were not deep-copied", copy.getDimension(0), ew3.getDimension(0));
 
     /*Test that the boxes were deep copied and that their BoxController pointers have been updated too.*/
-    std::vector<API::IMDNode *> originalBoxes;
+    std::vector<API::IMDNode *> originalBoxes(0, NULL);
     ew3.getBox()->getBoxes(originalBoxes, 10000, false);
 
     std::vector<API::IMDNode *> copiedBoxes;
@@ -221,10 +216,13 @@ public:
     TS_ASSERT_EQUALS(it->getDataSize(), 4*4*4);
     TS_ASSERT(it->next());
     delete it;
-    it = ew->createIterator(new MDImplicitFunction());
+    auto *mdfunction = new MDImplicitFunction();
+    it = ew->createIterator(mdfunction);
     TS_ASSERT(it);
     TS_ASSERT_EQUALS(it->getDataSize(), 4*4*4);
     TS_ASSERT(it->next());
+    delete mdfunction;
+    delete it;
     delete ew;
   }
 
@@ -242,6 +240,9 @@ public:
     TS_ASSERT_EQUALS(iterators[0]->getDataSize(), 21);
     TS_ASSERT_EQUALS(iterators[1]->getDataSize(), 21);
     TS_ASSERT_EQUALS(iterators[2]->getDataSize(), 22);
+
+    for(size_t i = 0; i < 3; ++i) delete iterators[i];
+    delete ew;
   }
 
   //-------------------------------------------------------------------------------------
@@ -293,63 +294,6 @@ public:
   }
 
   ////-------------------------------------------------------------------------------------
-  ///** Fill a 10x10 gridbox with events
-  // *
-  // * Tests that bad events are thrown out when using addEvents.
-  // * */
-  //void xest_addManyEvents()
-  //{
-  //  ProgressText * prog = NULL;
-  //  if (DODEBUG) prog = new ProgressText(0.0, 1.0, 10, false);
-
-  //  typedef MDGridBox<MDLeanEvent<2>,2> box_t;
-  //  MDEventWorkspace2Lean::sptr b = MDEventsTestHelper::makeMDEW<2>(10, 0.0, 10.0);
-  //  box_t * subbox;
-
-  //  // Manually set some of the tasking parameters
-  //  b->getBoxController()->setAddingEvents_eventsPerTask(1000);
-  //  b->getBoxController()->setAddingEvents_numTasksPerBlock(20);
-  //  b->getBoxController()->setSplitThreshold(100);
-  //  b->getBoxController()->setMaxDepth(4);
-
-  //  std::vector< MDLeanEvent<2> > events;
-  //  size_t num_repeat = 1000;
-  //  // Make an event in the middle of each box
-  //  for (double x=0.0005; x < 10; x += 1.0)
-  //    for (double y=0.0005; y < 10; y += 1.0)
-  //    {
-  //      for (size_t i=0; i < num_repeat; i++)
-  //      {
-  //        coord_t centers[2] = {static_cast<coord_t>(x), static_cast<coord_t>(y)};
-  //        events.push_back( MDLeanEvent<2>(2.0, 2.0, centers) );
-  //      }
-  //    }
-  //  TS_ASSERT_EQUALS( events.size(), 100*num_repeat);
-
-  //  TS_ASSERT_THROWS_NOTHING( b->addManyEvents( events, prog ); );
-  //  TS_ASSERT_EQUALS( b->getNPoints(), 100*num_repeat);
-  //  TS_ASSERT_EQUALS( b->getBox()->getSignal(), 100*double(num_repeat)*2.0);
-  //  TS_ASSERT_EQUALS( b->getBox()->getErrorSquared(), 100*double(num_repeat)*2.0);
-
-  //  box_t * gridBox = dynamic_cast<box_t *>(b->getBox());
-  //  std::vector<MDBoxBase<MDLeanEvent<2>,2>*> boxes = gridBox->getBoxes();
-  //  TS_ASSERT_EQUALS( boxes[0]->getNPoints(), num_repeat);
-  //  // The box should have been split itself into a gridbox, because 1000 events > the split threshold.
-  //  subbox = dynamic_cast<box_t *>(boxes[0]);
-  //  TS_ASSERT( subbox ); if (!subbox) return;
-  //  // The sub box is at a depth of 1.
-  //  TS_ASSERT_EQUALS( subbox->getDepth(), 1);
-
-  //  // And you can keep recursing into the box.
-  //  boxes = subbox->getBoxes();
-  //  subbox = dynamic_cast<box_t *>(boxes[0]);
-  //  TS_ASSERT( subbox ); if (!subbox) return;
-  //  TS_ASSERT_EQUALS( subbox->getDepth(), 2);
-
-  //  // And so on (this type of recursion was checked in test_splitAllIfNeeded()
-  //  if (prog) delete prog;
-  //}
-
 
   void checkExtents( std::vector<Mantid::Geometry::MDDimensionExtents<coord_t> > & ext, coord_t xmin, coord_t xmax, coord_t ymin, coord_t ymax)
   {
@@ -412,67 +356,6 @@ public:
 
   }
 
-//
-//  //-------------------------------------------------------------------------------------
-//  /** Tests that bad events are thrown out when using addEvents. 
-//   * */
-//  void test_addManyEvents_Performance()
-//  {
-//    // This test is too slow for unit tests, so it is disabled except in debug mode.
-//    if (!DODEBUG) return;
-//
-//    ProgressText * prog = new ProgressText(0.0, 1.0, 10, true);
-//    prog->setNotifyStep(0.5); //Notify more often
-//
-//    typedef MDGridBox<MDLeanEvent<2>,2> box_t;
-//    box_t * b = makeMDEW<2>(10, 0.0, 10.0);
-//
-//    // Manually set some of the tasking parameters
-//    b->getBoxController()->m_addingEvents_eventsPerTask = 50000;
-//    b->getBoxController()->m_addingEvents_numTasksPerBlock = 50;
-//    b->getBoxController()->m_SplitThreshold = 1000;
-//    b->getBoxController()->m_maxDepth = 6;
-//
-//    Timer tim;
-//    std::vector< MDLeanEvent<2> > events;
-//    double step_size = 1e-3;
-//    size_t numPoints = (10.0/step_size)*(10.0/step_size);
-//    std::cout << "Starting to write out " << numPoints << " events\n";
-//    if (true)
-//    {
-//      // ------ Make an event in the middle of each box ------
-//      for (double x=step_size; x < 10; x += step_size)
-//        for (double y=step_size; y < 10; y += step_size)
-//        {
-//          double centers[2] = {x, y};
-//          events.push_back( MDLeanEvent<2>(2.0, 3.0, centers) );
-//        }
-//    }
-//    else
-//    {
-//      // ------- Randomize event distribution ----------
-//      boost::mt19937 rng;
-//      boost::uniform_real<float> u(0.0, 10.0); // Range
-//      boost::variate_generator<boost::mt19937&, boost::uniform_real<float> > gen(rng, u);
-//
-//      for (size_t i=0; i < numPoints; i++)
-//      {
-//        double centers[2] = {gen(), gen()};
-//        events.push_back( MDLeanEvent<2>(2.0, 3.0, centers) );
-//      }
-//    }
-//    TS_ASSERT_EQUALS( events.size(), numPoints);
-//    std::cout << "..." << numPoints << " events were filled in " << tim.elapsed() << " secs.\n";
-//
-//    size_t numbad = 0;
-//    TS_ASSERT_THROWS_NOTHING( numbad = b->addManyEvents( events, prog); );
-//    TS_ASSERT_EQUALS( numbad, 0);
-//    TS_ASSERT_EQUALS( b->getNPoints(), numPoints);
-//    TS_ASSERT_EQUALS( b->getSignal(), numPoints*2.0);
-//    TS_ASSERT_EQUALS( b->getErrorSquared(), numPoints*3.0);
-//
-//    std::cout << "addManyEvents() ran in " << tim.elapsed() << " secs.\n";
-//  }
 
 
   void test_integrateSphere()
@@ -493,8 +376,6 @@ public:
     //TODO:
 //    TS_ASSERT_DELTA( signal, 1.0, 1e-5);
 //    TS_ASSERT_DELTA( errorSquared, 1.0, 1e-5);
-
-
   }
 
   /*
diff --git a/Code/Mantid/Framework/DataObjects/test/MDGridBoxTest.h b/Code/Mantid/Framework/DataObjects/test/MDGridBoxTest.h
index 6c5c184ab99d8030420289141aa3b82b703bd6e6..f8d0907d5e89694bd1f1e040b1e42b3fbd15823f 100644
--- a/Code/Mantid/Framework/DataObjects/test/MDGridBoxTest.h
+++ b/Code/Mantid/Framework/DataObjects/test/MDGridBoxTest.h
@@ -44,7 +44,7 @@ using namespace testing;
 class MDGridBoxTest :    public CxxTest::TestSuite
 {
 private:
-  
+
   ///Mock type to help determine if masking is being determined correctly
     class MockMDBox : public MDBox<MDLeanEvent<1>, 1>
   {
@@ -80,7 +80,7 @@ public:
   //-------------------------------------------------------------------------------------
   void test_MDBoxConstructor()
   {
-    
+
     MDBox<MDLeanEvent<1>,1> * b = MDEventsTestHelper::makeMDBox1(10);
     TS_ASSERT_EQUALS( b->getNumDims(), 1);
     TS_ASSERT_EQUALS( b->getNPoints(), 0);
@@ -205,7 +205,7 @@ public:
       MDBox<MDLeanEvent<1>,1> * box = dynamic_cast<MDBox<MDLeanEvent<1>,1> *>(boxes[i]);
       TS_ASSERT_EQUALS(box->getNPoints(), 2);
     }
-    
+
     std::vector<signal_t> sigErr(20);
     std::vector<coord_t> coord(10);
     std::vector<uint16_t> runIndex;
@@ -231,7 +231,7 @@ public:
     BoxController *const bcc = b->getBoxController();
     delete b;
     delete bcc;
-
+    delete g;
   }
 
 
@@ -254,6 +254,9 @@ public:
 
     BoxController *const bcc = b->getBoxController();
     delete bcc;
+    delete g2;
+    delete g1;
+    delete b;
   }
 
   void test_setBoxController()
@@ -268,8 +271,8 @@ public:
 
     auto boxes = box1->getBoxes();
     for(size_t i = 0; i < boxes.size(); ++i)
-    {       
-      TSM_ASSERT_EQUALS("All child boxes should have the same box controller as the parent.", newBoxController, boxes[i]->getBoxController()); 
+    {
+      TSM_ASSERT_EQUALS("All child boxes should have the same box controller as the parent.", newBoxController, boxes[i]->getBoxController());
     }
     delete newBoxController;
     delete box1;
@@ -285,8 +288,10 @@ public:
   {
     // Build the grid box
     MDGridBox<MDLeanEvent<1>,1> * g = MDEventsTestHelper::makeMDGridBox<1>(10,10,0.0, 10.0);
-    BoxController *const bcc = g->getBoxController();
+    // Clear the initial children
+    for (size_t i = 0; i < g->getNumChildren(); i++) delete g->getChild(i);
 
+    BoxController *const bcc = g->getBoxController();
     std::vector<API::IMDNode *> boxes;
     for (size_t i=0; i<15; i++)
       boxes.push_back( MDEventsTestHelper::makeMDBox1(10,bcc) );
@@ -299,9 +304,12 @@ public:
       // Parent was set correctly in child
       TS_ASSERT_EQUALS( g->getChild(i-2)->getParent(), g);
     }
+    // MDGridBox will delete the children that it pulled in but the rest need to be
+    // taken care of manually
+    size_t indices[5] = {0, 1, 12, 13, 14};
+    for(size_t i = 0; i < 5; ++i) delete boxes[indices[i]];
     delete g;
     delete bcc;
-
   }
 
   void test_getChildIndexFromID()
@@ -354,7 +362,7 @@ public:
     BoxController *const bcc =b->getBoxController();
     delete b;
     delete bcc;
-
+    delete g;
   }
 
 
@@ -528,6 +536,7 @@ public:
     BoxController *const bcc = b->getBoxController();
     delete b;
     delete bcc;
+    delete g;
   }
 
 
@@ -639,6 +648,7 @@ public:
     }
 
     // ----- Infinitely thin plane for an implicit function ------------
+    delete function;
     function = new MDImplicitFunction;
     coord_t normal3[1] = {-1};
     coord_t origin3[1] = {1.51f};
@@ -649,11 +659,11 @@ public:
     parent->getBoxes(boxes, 3, true, function);
     TSM_ASSERT_EQUALS( "Only one box is found by an infinitely thin plane", boxes.size(), 1);
 
-    // clean up  behind 
+    // clean up  behind
     BoxController *const bcc = parent->getBoxController();
     delete parent;
     delete bcc;
-
+    delete function;
   }
 
 
@@ -678,7 +688,6 @@ public:
     // The boxes extents make sense
     for (size_t i=0; i<boxes.size(); i++)
     {
-      //std::cout << boxes[i]->getExtentsStr() << std::endl;
       TS_ASSERT( boxes[i]->getExtents(0).getMax() >= 2.00);
       TS_ASSERT( boxes[i]->getExtents(0).getMin() <= 3.00);
       TS_ASSERT( boxes[i]->getExtents(1).getMax() >= 2.00);
@@ -692,18 +701,17 @@ public:
     // The boxes extents make sense
     for (size_t i=0; i<boxes.size(); i++)
     {
-      //std::cout << boxes[i]->getExtentsStr() << std::endl;
       TS_ASSERT( boxes[i]->getExtents(0).getMax() >= 2.00);
       TS_ASSERT( boxes[i]->getExtents(0).getMin() <= 3.00);
       TS_ASSERT( boxes[i]->getExtents(1).getMax() >= 2.00);
       TS_ASSERT( boxes[i]->getExtents(1).getMin() <= 3.00);
     }
 
-    // clean up  behind 
+    // clean up  behind
     BoxController *const bcc = parent->getBoxController();
     delete parent;
     delete bcc;
-
+    delete function;
   }
 
 
@@ -734,11 +742,11 @@ public:
     TS_ASSERT_DELTA( boxes[0]->getExtents(0).getMin(), 1.75, 1e-4);
     TS_ASSERT_DELTA( boxes[0]->getExtents(0).getMax(), 2.00, 1e-4);
 
-    // clean up  behind 
+    // clean up  behind
     BoxController *const bcc = parent->getBoxController();
     delete parent;
     delete bcc;
-
+    delete function;
   }
 
   //-------------------------------------------------------------------------------------
@@ -767,11 +775,11 @@ public:
     TS_ASSERT_DELTA( boxes[0]->getExtents(0).getMin(), 1.75, 1e-4);
     TS_ASSERT_DELTA( boxes[0]->getExtents(0).getMax(), 2.00, 1e-4);
 
-    // clean up  behind 
+    // clean up  behind
     BoxController *const bcc = parent->getBoxController();
     delete parent;
     delete bcc;
-
+    delete function;
   }
 
 
@@ -786,15 +794,12 @@ public:
     size_t numSplit = 4;
     for (size_t recurseLevels = 1; recurseLevels < 5; recurseLevels++)
     {
-      std::cout << " --- Recursion Level " << recurseLevels << " --- " << std::endl;
-      Timer tim1;
       double boxes_per_side = pow(double(numSplit), double(recurseLevels));
       double spacing = double(numSplit)/boxes_per_side;
       // How many times to add the same event
       size_t num_to_repeat = size_t(1e7 / (boxes_per_side*boxes_per_side));
 
       MDGridBox<MDLeanEvent<2>,2> * box = MDEventsTestHelper::makeRecursiveMDGridBox<2>(numSplit, recurseLevels);
-      std::cout << tim1.elapsed() << " seconds to generate the " << boxes_per_side << "^2 boxes." << std::endl;
 
       for (double x=0; x < numSplit; x += spacing)
         for (double y=0; y < numSplit; y += spacing)
@@ -807,10 +812,6 @@ public:
         }
       // You must refresh the cache after adding individual events.
       box->refreshCache(NULL);
-
-      double sec = tim1.elapsed();
-      std::cout << sec << " seconds to add " << box->getNPoints() << " events. Each box had " << num_to_repeat << " events." << std::endl;
-      std::cout << "equals " << 1e6*sec/double(box->getNPoints()) << " seconds per million events." << std::endl;
     }
 
   }
@@ -876,7 +877,7 @@ public:
     TS_ASSERT_EQUALS( b->getSignal(), 100*2.0);
     TS_ASSERT_EQUALS( b->getErrorSquared(), 100*2.0);
 
-    // clean up  behind 
+    // clean up  behind
     BoxController *const bcc = b->getBoxController();
     delete b;
     delete bcc;
@@ -932,13 +933,14 @@ public:
         }
       TS_ASSERT_THROWS_NOTHING( b->addEvents( events ); );
     }
+
     // Get the right totals again by refreshing
     b->refreshCache(ts);
     TS_ASSERT_EQUALS( b->getNPoints(), 100*num_repeat);
     TS_ASSERT_EQUALS( b->getSignal(), 100*num_repeat*2.0);
     TS_ASSERT_EQUALS( b->getErrorSquared(), 100*num_repeat*2.0);
 
-    // clean up  behind 
+    // clean up  behind
     BoxController *const bcc = b->getBoxController();
     delete b;
     delete bcc;
@@ -969,6 +971,8 @@ public:
     coord_t coords[2] = {1.5,1.5};
     const MDBoxBase<MDLeanEvent<2>,2> * c = dynamic_cast<const MDBoxBase<MDLeanEvent<2>,2> *>(b->getBoxAtCoord(coords));
     TS_ASSERT_EQUALS(c, b->getChild(11));
+    delete b->getBoxController();
+    delete b;
   }
 
 
@@ -1033,9 +1037,9 @@ public:
     // We went this many levels (and no further) because recursion depth is limited
     TS_ASSERT_EQUALS(boxes[0]->getDepth(), 4);
 
-    // clean up  behind 
+    // clean up  behind
     BoxController *const bcc = b0->getBoxController();
-    delete b;
+    delete b0;
     delete bcc;
 
   }
@@ -1093,7 +1097,7 @@ public:
 
     }
 
-    // clean up  behind 
+    // clean up  behind
     BoxController *const bcc = b->getBoxController();
     delete b;
     delete bcc;
@@ -1186,6 +1190,8 @@ public:
     doTestMDBin2(b, "Bin that fits partially in one MDBox'es, and goes of the edge",
         -3.2, 0.8, 0.1, 0.9,     2.0);
 
+    delete b->getBoxController();
+    delete b;
   }
 
 
@@ -1201,7 +1207,6 @@ public:
    */
   void do_check_integrateSphere(MDGridBox<MDLeanEvent<2>,2> & box, double x, double y, const double radius, double numExpected, std::string message)
   {
-    std::cout << "Sphere of radius " << radius << " at " << x << "," << y << "------" << message << "--\n";
     // The sphere transformation
     bool dimensionsUsed[2] = {true,true};
     coord_t center[2] = {static_cast<coord_t>(x),static_cast<coord_t>(y)};
@@ -1251,7 +1256,7 @@ public:
     MDEventsTestHelper::feedMDBox<2>(box_ptr, 1);
     do_test_integrateSphere(box_ptr);
 
-    // clean up  behind 
+    // clean up  behind
     BoxController *const bcc = box_ptr->getBoxController();
     delete box_ptr;
     delete bcc;
@@ -1264,7 +1269,7 @@ public:
     MDGridBox<MDLeanEvent<2>,2> * box_ptr = MDEventsTestHelper::makeMDGridBox<2>(10,5);
     MDEventsTestHelper::feedMDBox<2>(box_ptr, 1);
     do_test_integrateSphere(box_ptr);
-    // clean up  behind 
+    // clean up  behind
     BoxController *const bcc = box_ptr->getBoxController();
     delete box_ptr;
     delete bcc;
@@ -1278,7 +1283,7 @@ public:
     MDEventsTestHelper::feedMDBox<2>(box_ptr, 1);
     do_test_integrateSphere(box_ptr);
 
-    // clean up  behind 
+    // clean up  behind
     BoxController *const bcc = box_ptr->getBoxController();
     delete box_ptr;
     delete bcc;
@@ -1301,7 +1306,7 @@ public:
     do_check_integrateSphere(box, 1.0,1.0,  1.45,  1.0, "Contains one box completely");
     do_check_integrateSphere(box, 9.0,9.0,  1.45,  1.0, "Contains one box completely, at the edges");
 
-    // clean up  behind 
+    // clean up  behind
     BoxController *const bcc = box_ptr->getBoxController();
     delete box_ptr;
     delete bcc;
@@ -1319,7 +1324,6 @@ public:
   void do_check_integrateSphere3d(MDGridBox<MDLeanEvent<3>,3> & box, double x, double y, double z,
       const double radius, double numExpected, std::string message)
   {
-    std::cout << "Sphere of radius " << radius << " at " << x << "," << y << "," << z << "--- " << message << " ---------\n";
     // The sphere transformation
     bool dimensionsUsed[3] = {true,true, true};
     coord_t center[3] = {static_cast<coord_t>(x),static_cast<coord_t>(y),static_cast<coord_t>(z)};
@@ -1351,6 +1355,8 @@ public:
     box.addEvent(MDLeanEvent<3>(2.0, 2.0, center));
 //    do_check_integrateSphere(box, -1.0,0.5, 1.01,  1.0, "Off an edge but just barely enough to get an event");
 //    do_check_integrateSphere(box, 0.0,0.5, 0.01,  1.0, "Tiny, but just barely enough to get an event");
+    delete box_ptr->getBoxController();
+    delete box_ptr;
   }
 
 
@@ -1370,7 +1376,6 @@ public:
       double numExpected, double xExpected, double yExpected,
       std::string message)
   {
-    std::cout << "Centroid of sphere of radius " << radius << " at " << x << "," << y << "------" << message << "--\n";
     // The sphere transformation
     bool dimensionsUsed[2] = {true,true};
     coord_t center[2] = {static_cast<coord_t>(x),static_cast<coord_t>(y)};
@@ -1421,6 +1426,9 @@ public:
     box.addEvent(MDLeanEvent<2>(1.0, 1.0, center));
     do_check_integrateSphere(box, -1.0,0.5, 1.01,  1.0, "Off an edge but just barely enough to get an event");
     do_check_integrateSphere(box, 0.0,0.5, 0.01,  1.0, "Tiny, but just barely enough to get an event");
+
+    delete box_ptr->getBoxController();
+    delete box_ptr;
   }
 
   void test_getIsMasked_WhenNoMasking()
@@ -1500,8 +1508,8 @@ public:
     MockMDBox* a = new MockMDBox;
     MockMDBox* b = new MockMDBox;
 
-    EXPECT_CALL(*a, mask()).Times(1); 
-    EXPECT_CALL(*b, mask()).Times(1); 
+    EXPECT_CALL(*a, mask()).Times(1);
+    EXPECT_CALL(*b, mask()).Times(1);
 
     boxes.push_back(a);
     boxes.push_back(b);
@@ -1525,8 +1533,8 @@ public:
     MockMDBox* a = new MockMDBox;
     MockMDBox* b = new MockMDBox;
 
-    EXPECT_CALL(*a, unmask()).Times(1); 
-    EXPECT_CALL(*b, unmask()).Times(1); 
+    EXPECT_CALL(*a, unmask()).Times(1);
+    EXPECT_CALL(*b, unmask()).Times(1);
 
     boxes.push_back(a);
     boxes.push_back(b);
@@ -1756,7 +1764,6 @@ public:
    * Gets about 11 million boxes */
   void test_getBoxes()
   {
-    CPUTimer tim;
     std::vector<API::IMDNode *> boxes;
     for (size_t i=0; i<10; i++)
     {
@@ -1766,11 +1773,9 @@ public:
       TS_ASSERT_EQUALS( boxes.size(), 1111111);
       TS_ASSERT_EQUALS( boxes[0], recursiveParent);
     }
-    std::cout << tim << " to getBoxes() 10 x 1.1 million boxes." << std::endl;
   }
 
 
 };
 
 #endif
-
diff --git a/Code/Mantid/Framework/DataObjects/test/MDHistoWorkspaceIteratorTest.h b/Code/Mantid/Framework/DataObjects/test/MDHistoWorkspaceIteratorTest.h
index e39b618a81543c6159385c992ad147b8fcfead09..0d06b5ad5fcb24fa95fad1ac2383d5c1b6cb34c4 100644
--- a/Code/Mantid/Framework/DataObjects/test/MDHistoWorkspaceIteratorTest.h
+++ b/Code/Mantid/Framework/DataObjects/test/MDHistoWorkspaceIteratorTest.h
@@ -8,14 +8,14 @@
 #include "MantidDataObjects/MDHistoWorkspaceIterator.h"
 #include "MantidTestHelpers/MDEventsTestHelper.h"
 #include <cxxtest/TestSuite.h>
-#include <iomanip>
-#include <iostream>
 #include "MantidKernel/VMD.h"
 #include "MantidGeometry/MDGeometry/MDImplicitFunction.h"
 #include "MantidGeometry/MDGeometry/MDPlane.h"
 #include <boost/assign/list_of.hpp>
 #include <boost/function.hpp>
 #include <boost/bind.hpp>
+#include <boost/scoped_ptr.hpp>
+
 
 using namespace Mantid;
 using namespace Mantid::DataObjects;
@@ -67,9 +67,10 @@ public:
   void do_test_iterator(size_t nd, size_t numPoints)
   {
     MDHistoWorkspace_sptr ws = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, nd, 10);
-    for (size_t i = 0; i < numPoints; i++)
+    for (size_t i = 0; i < numPoints; i++) {
       ws->setSignalAt(i, double(i));
-    MDHistoWorkspaceIterator * it = new MDHistoWorkspaceIterator(ws);
+    }
+    boost::scoped_ptr<MDHistoWorkspaceIterator> it(new MDHistoWorkspaceIterator(ws));
     TSM_ASSERT( "This iterator is valid at the start.", it->valid());
     size_t i = 0;
 
@@ -90,10 +91,10 @@ public:
     {
       TS_ASSERT_DELTA( it->getNormalizedSignal(), double(i) / 1.0, 1e-5);
       TS_ASSERT_DELTA( it->getNormalizedError(), 1.0, 1e-5);
-      coord_t * vertexes;
       size_t numVertices;
-      vertexes = it->getVertexesArray(numVertices);
-      TS_ASSERT( vertexes);
+      coord_t *vertexes = it->getVertexesArray(numVertices);
+      TS_ASSERT(vertexes);
+      delete [] vertexes;
       TS_ASSERT_EQUALS( it->getNumEvents(), 1);
       TS_ASSERT_EQUALS( it->getInnerDetectorID(0), 0);
       TS_ASSERT_EQUALS( it->getInnerRunIndex(0), 0);
@@ -163,6 +164,8 @@ public:
     it->next();
     TS_ASSERT_EQUALS(it->getNormalizedSignal(), 30.);
     TS_ASSERT( !it->next());
+
+    delete it;
   }
 
   void test_iterator_2D_implicitFunction_thatExcludesTheStart()
@@ -192,6 +195,8 @@ public:
     TS_ASSERT_EQUALS(it->getNormalizedSignal(), 13.);
     it->next();
     // And so forth....
+
+    delete it;
   }
 
   void test_iterator_2D_implicitFunction_thatExcludesEverything()
@@ -206,6 +211,8 @@ public:
     MDHistoWorkspaceIterator * it = new MDHistoWorkspaceIterator(ws, function);
 
     TSM_ASSERT( "This iterator is not valid at the start.", !it->valid());
+
+    delete it;
   }
 
   /** Create several parallel iterators */
@@ -227,7 +234,7 @@ public:
     TS_ASSERT_EQUALS( it->getDataSize(), 33);
     TS_ASSERT_DELTA( it->getInnerPosition(0,0), 0.5, 1e-5);
     TS_ASSERT_DELTA( it->getInnerPosition(0,1), 0.5, 1e-5);
-
+    
     it = iterators[1];
     TS_ASSERT_DELTA( it->getSignal(), 33.0, 1e-5);
     TS_ASSERT_EQUALS( it->getDataSize(), 33);
@@ -239,7 +246,8 @@ public:
     TS_ASSERT_EQUALS( it->getDataSize(), 34);
     TS_ASSERT_DELTA( it->getInnerPosition(0,0), 6.5, 1e-5);
     TS_ASSERT_DELTA( it->getInnerPosition(0,1), 6.5, 1e-5);
-
+    
+    for(size_t i = 0; i < 3; ++i) delete iterators[i];
   }
 
   void test_predictable_steps()
@@ -254,6 +262,7 @@ public:
       expected = current + 1;
       histoIt->next();
     }
+    delete histoIt;
   }
 
   void test_skip_masked_detectors()
@@ -278,6 +287,8 @@ public:
     histoIt->next();
     TSM_ASSERT_EQUALS("The first index hit should be 2 since that is the first unmasked one", 5,
         histoIt->getLinearIndex());
+
+    delete histoIt;
   }
 
   //template<typename ContainerType, typename ElementType>
@@ -350,6 +361,7 @@ public:
     neighbourIndexes = findNeighbourMemberFunction(it);
     TSM_ASSERT( "Neighbour at index 9 is 8", doesContainIndex(neighbourIndexes, 8));
 
+    delete it;
   }
 
   void test_neighbours_1d_face_touching()
@@ -436,6 +448,8 @@ public:
     // Is on an edge
     TSM_ASSERT( "Neighbour at index 15 is 11", doesContainIndex(neighbourIndexes, 11));
     TSM_ASSERT( "Neighbour at index 15 is 14", doesContainIndex(neighbourIndexes, 14));
+
+    delete it;
   }
 
   void test_neighbours_2d_vertex_touching()
@@ -516,6 +530,8 @@ public:
     TSM_ASSERT( "Neighbour at index 15 is 10", doesContainIndex(neighbourIndexes, 10));
     TSM_ASSERT( "Neighbour at index 15 is 11", doesContainIndex(neighbourIndexes, 11));
     TSM_ASSERT( "Neighbour at index 15 is 14", doesContainIndex(neighbourIndexes, 14));
+
+    delete it;
   }
 
   void test_neighbours_3d_face_touching()
@@ -592,6 +608,7 @@ public:
       TS_ASSERT(doesContainIndex(neighbourIndexes, *i));
     }
 
+    delete it;
   }
 
   void test_neighbours_3d_vertex_touching()
@@ -673,6 +690,7 @@ public:
       TS_ASSERT(doesContainIndex(neighbourIndexes, *i));
     }
 
+    delete it;
   }
 
   void test_neighbours_1d_with_width()
@@ -730,6 +748,8 @@ public:
       TS_ASSERT_EQUALS(2, neighbourIndexes.size());
       TSM_ASSERT( "Neighbours at index 9 includes 8", doesContainIndex(neighbourIndexes, 8));
       TSM_ASSERT( "Neighbours at index 9 includes 7", doesContainIndex(neighbourIndexes, 7));
+      
+      delete it;
   }
 
   void test_neighbours_2d_vertex_touching_by_width()
@@ -808,6 +828,8 @@ public:
     TSM_ASSERT( "Neighbour at index is 11", doesContainIndex(neighbourIndexes, 11));
     TSM_ASSERT( "Neighbour at index is 13", doesContainIndex(neighbourIndexes, 13));
     TSM_ASSERT( "Neighbour at index is 14", doesContainIndex(neighbourIndexes, 14));
+
+    delete it;
   }
 
   void test_neighbours_2d_vertex_touching_by_width_vector()
@@ -884,6 +906,8 @@ public:
     TSM_ASSERT( "Neighbour at index is 11", doesContainIndex(neighbourIndexes, 11));
     TSM_ASSERT( "Neighbour at index is 13", doesContainIndex(neighbourIndexes, 13));
     TSM_ASSERT( "Neighbour at index is 14", doesContainIndex(neighbourIndexes, 14));
+
+    delete it;
   }
 
 
@@ -939,6 +963,8 @@ public:
     TS_ASSERT(doesContainIndex(neighbourIndexes, 24));
     TS_ASSERT(doesContainIndex(neighbourIndexes, 25));
     TS_ASSERT(doesContainIndex(neighbourIndexes, 26));
+
+    delete it;
   }
 
   void test_cache()
@@ -960,8 +986,120 @@ public:
       TSM_ASSERT_EQUALS("One cache item expected", 1, it->permutationCacheSize()); // Same item, no change to cache
       it->findNeighbourIndexesByWidth(5);
       TSM_ASSERT_EQUALS("Two cache entries expected", 2, it->permutationCacheSize());
+
+      delete it;
   }
 
+  void test_getBoxExtents_1d() {
+      const size_t nd = 1;
+      MDHistoWorkspace_sptr ws = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0 /*signal*/, nd, 3 /*3 bins*/); // Dimension length defaults to 10
+      MDHistoWorkspaceIterator * it = new MDHistoWorkspaceIterator(ws);
+
+      // At zeroth position
+      VecMDExtents extents = it->getBoxExtents();
+      TSM_ASSERT_EQUALS("Wrong number of extents pairs. This is 1D.", 1, extents.size());
+      TS_ASSERT_DELTA(extents[0].get<0>(), 0, 1e-4);
+      TS_ASSERT_DELTA(extents[0].get<1>(), 10.0 * 1.0/3.0, 1e-4);
+
+      // At middle position
+      it->next();
+      extents = it->getBoxExtents();
+      TS_ASSERT_DELTA(extents[0].get<0>(), 10.0 * 1.0/3.0, 1e-4);
+      TS_ASSERT_DELTA(extents[0].get<1>(), 10.0 * 2.0/3.0, 1e-4);
+
+      // At end position
+      it->next();
+      extents = it->getBoxExtents();
+      TS_ASSERT_DELTA(extents[0].get<0>(), 10.0 * 2.0/3.0, 1e-4);
+      TS_ASSERT_DELTA(extents[0].get<1>(), 10.0 * 3.0/3.0, 1e-4);
+
+      delete it;
+  }
+
+  void test_getBoxExtents_3d() {
+      MDHistoWorkspace_sptr ws = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0 /*signal*/, 3 /*nd*/, 4 /*nbins per dim*/, 6 /*max*/, 1.0 /*error sq*/);
+      MDHistoWorkspaceIterator * it = new MDHistoWorkspaceIterator(ws);
+
+      // At zeroth position
+      VecMDExtents extents = it->getBoxExtents();
+      TSM_ASSERT_EQUALS("Wrong number of extents pairs. This is 3D.", 3, extents.size());
+      TS_ASSERT_DELTA(extents[0].get<0>(), 0, 1e-4);
+      TS_ASSERT_DELTA(extents[0].get<1>(), 6.0/4.0, 1e-4);
+      TS_ASSERT_DELTA(extents[1].get<0>(), 0, 1e-4);
+      TS_ASSERT_DELTA(extents[1].get<1>(), 6.0/4.0, 1e-4);
+      TS_ASSERT_DELTA(extents[2].get<0>(), 0, 1e-4);
+      TS_ASSERT_DELTA(extents[2].get<1>(), 6.0/4.0, 1e-4);
+
+      // At last position
+      it->jumpTo((4*4*4) - 1);
+      extents = it->getBoxExtents();
+      TSM_ASSERT_EQUALS("Wrong number of extents pairs. This is 3D.", 3, extents.size());
+      TS_ASSERT_DELTA(extents[0].get<0>(), 3.0/4 * 6.0, 1e-4);
+      TS_ASSERT_DELTA(extents[0].get<1>(), 4.0/4 * 6.0, 1e-4);
+      TS_ASSERT_DELTA(extents[1].get<0>(), 3.0/4 * 6.0, 1e-4);
+      TS_ASSERT_DELTA(extents[1].get<1>(), 4.0/4 * 6.0, 1e-4);
+      TS_ASSERT_DELTA(extents[2].get<0>(), 3.0/4 * 6.0, 1e-4);
+      TS_ASSERT_DELTA(extents[2].get<1>(), 4.0/4 * 6.0, 1e-4);
+
+      delete it;
+  }
+
+  void test_jump_to_nearest_1d() {
+
+      MDHistoWorkspace_sptr wsIn = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0 /*signal*/, 1 /*nd*/, 4 /*nbins per dim*/, 12 /*max*/);
+      MDHistoWorkspace_sptr wsOut = MDEventsTestHelper::makeFakeMDHistoWorkspace(0.0 /*signal*/, 1 /*nd*/, 3 /*nbins per dim*/, 12 /*max*/);
+
+      /*
+
+                           input
+      (x = 0) *|--------|--------|--------|--------|* (x = 12)
+               0        3        6        9        12 (x values)
+               0        1        2        3        4 (iterator indexes)
+                    x        x        x        x     (centres x)
+                    |        |        |        |
+                   1.5      4.5      7.5      10.5
+
+                            output
+      (x = 0) *|----------|------------|-----------|* (x = 12)
+               0          4            8           12 (x values)
+               0          1            2           3 (iterator indexes)
+
+
+      */
+
+      MDHistoWorkspaceIterator * itIn = new MDHistoWorkspaceIterator(wsIn);
+      MDHistoWorkspaceIterator * itOut = new MDHistoWorkspaceIterator(wsOut);
+
+      // First position
+      TS_ASSERT_EQUALS(itIn->getLinearIndex(), 0);
+      auto diff = itOut->jumpToNearest(itIn->getCenter());
+      TS_ASSERT_EQUALS(itOut->getLinearIndex(), 0); // 1.5 closer to 0 than 4.
+      TS_ASSERT_DELTA(1.5, diff, 1e-4);
+
+      // Second position
+      itIn->next();
+      TS_ASSERT_EQUALS(itIn->getLinearIndex(), 1);
+      diff = itOut->jumpToNearest(itIn->getCenter());
+      TS_ASSERT_EQUALS(itOut->getLinearIndex(), 1); // 4.5 closer to 4 than 5
+      TS_ASSERT_DELTA(0.5, diff, 1e-4);
+
+      // Third position
+      itIn->next();
+      TS_ASSERT_EQUALS(itIn->getLinearIndex(), 2);
+      diff = itOut->jumpToNearest(itIn->getCenter());
+      TS_ASSERT_EQUALS(itOut->getLinearIndex(), 2); // 7.5 is closer to 8 than 4
+      TS_ASSERT_DELTA(0.5, diff, 1e-4);
+
+      // Fourth position
+      itIn->next();
+      TS_ASSERT_EQUALS(itIn->getLinearIndex(), 3);
+      diff = itOut->jumpToNearest(itIn->getCenter());
+      TS_ASSERT_EQUALS(itOut->getLinearIndex(), 3); // 10.5 closer to 12 than 8
+      TS_ASSERT_DELTA(1.5, diff, 1e-4);
+
+      delete itIn;
+      delete itOut;
+  }
 
 };
 
@@ -1001,6 +1139,7 @@ public:
       UNUSED_ARG(sig);
       UNUSED_ARG(err);
     } while (it->next());
+    delete it;
   }
 
   /** ~Two million iterations */
@@ -1017,6 +1156,7 @@ public:
       UNUSED_ARG(sig);
       UNUSED_ARG(err);
     } while (it->next());
+    delete it;
   }
 
   /** ~Two million iterations */
@@ -1031,6 +1171,7 @@ public:
       UNUSED_ARG(sig);
       UNUSED_ARG(err);
     } while (it->next());
+    delete it;
   }
 
   /** Use jumpTo() */
@@ -1047,6 +1188,7 @@ public:
       UNUSED_ARG(sig);
       UNUSED_ARG(err);
     }
+    delete it;
   }
 
   void test_masked_get_vertexes_call_throws()
diff --git a/Code/Mantid/Framework/DataObjects/test/MDHistoWorkspaceTest.h b/Code/Mantid/Framework/DataObjects/test/MDHistoWorkspaceTest.h
index cdc1be0e3c94cceebcf8bc19a4812fec4b244448..d15c48a8ec45056739476d54d289b813060ab08e 100644
--- a/Code/Mantid/Framework/DataObjects/test/MDHistoWorkspaceTest.h
+++ b/Code/Mantid/Framework/DataObjects/test/MDHistoWorkspaceTest.h
@@ -13,6 +13,8 @@
 #include "MantidDataObjects/MDHistoWorkspaceIterator.h"
 #include "MantidTestHelpers/MDEventsTestHelper.h"
 #include <boost/math/special_functions/fpclassify.hpp>
+#include <boost/scoped_array.hpp>
+#include <boost/scoped_ptr.hpp>
 #include <cxxtest/TestSuite.h>
 #include <iomanip>
 #include <iostream>
@@ -43,6 +45,7 @@ private:
       }
       it->next(1);
     }
+    delete it;
     return numberMasked;
   }
   /// Helper method returns the size of an element in the MDHistoWorkspace
@@ -233,16 +236,17 @@ public:
   {
     MDHistoDimension_sptr dimX(new MDHistoDimension("X", "x", "m", -10, 10, 5));
     MDHistoWorkspace ws(dimX);
-    coord_t * v;
     size_t numVertices;
-    v = ws.getVertexesArray(0,numVertices);
+    coord_t *v1 = ws.getVertexesArray(0,numVertices);
     TS_ASSERT_EQUALS( numVertices, 2 );
-    TS_ASSERT_DELTA( v[0], -10.0, 1e-5);
-    TS_ASSERT_DELTA( v[1], -6.0, 1e-5);
-
-    v = ws.getVertexesArray(4,numVertices);
-    TS_ASSERT_DELTA( v[0], 6.0, 1e-5);
-    TS_ASSERT_DELTA( v[1], 10.0, 1e-5);
+    TS_ASSERT_DELTA( v1[0], -10.0, 1e-5);
+    TS_ASSERT_DELTA( v1[1], -6.0, 1e-5);
+    delete [] v1;
+    
+    coord_t *v2 = ws.getVertexesArray(4,numVertices);
+    TS_ASSERT_DELTA( v2[0], 6.0, 1e-5);
+    TS_ASSERT_DELTA( v2[1], 10.0, 1e-5);
+    delete [] v2;
   }
 
   //---------------------------------------------------------------------------------------------------
@@ -251,25 +255,24 @@ public:
     MDHistoDimension_sptr dimX(new MDHistoDimension("X", "x", "m", -10, 10, 5));
     MDHistoDimension_sptr dimY(new MDHistoDimension("Y", "y", "m", -10, 10, 5));
     MDHistoWorkspace ws(dimX, dimY);
-    coord_t * v;
     size_t numVertices, i;
 
-    v = ws.getVertexesArray(0,numVertices);
+    boost::scoped_array<coord_t> v1(ws.getVertexesArray(0,numVertices));
     TS_ASSERT_EQUALS( numVertices, 4 );
     i = 0*2;
-    TS_ASSERT_DELTA( v[i+0], -10.0, 1e-5);
-    TS_ASSERT_DELTA( v[i+1], -10.0, 1e-5);
+    TS_ASSERT_DELTA( v1[i+0], -10.0, 1e-5);
+    TS_ASSERT_DELTA( v1[i+1], -10.0, 1e-5);
     i = 3*2;
-    TS_ASSERT_DELTA( v[i+0], -6.0, 1e-5);
-    TS_ASSERT_DELTA( v[i+1], -6.0, 1e-5);
+    TS_ASSERT_DELTA( v1[i+0], -6.0, 1e-5);
+    TS_ASSERT_DELTA( v1[i+1], -6.0, 1e-5);
     // The opposite corner
-    v = ws.getVertexesArray(24,numVertices);
+    boost::scoped_array<coord_t> v2(ws.getVertexesArray(24,numVertices));
     i = 0*2;
-    TS_ASSERT_DELTA( v[i+0], 6.0, 1e-5);
-    TS_ASSERT_DELTA( v[i+1], 6.0, 1e-5);
+    TS_ASSERT_DELTA( v2[i+0], 6.0, 1e-5);
+    TS_ASSERT_DELTA( v2[i+1], 6.0, 1e-5);
     i = 3*2;
-    TS_ASSERT_DELTA( v[i+0], 10.0, 1e-5);
-    TS_ASSERT_DELTA( v[i+1], 10.0, 1e-5);
+    TS_ASSERT_DELTA( v2[i+0], 10.0, 1e-5);
+    TS_ASSERT_DELTA( v2[i+1], 10.0, 1e-5);
   }
 
   //---------------------------------------------------------------------------------------------------
@@ -279,10 +282,9 @@ public:
     MDHistoDimension_sptr dimY(new MDHistoDimension("Y", "y", "m", -9, 10, 5));
     MDHistoDimension_sptr dimZ(new MDHistoDimension("Z", "z", "m", -8, 10, 5));
     MDHistoWorkspace ws(dimX, dimY, dimZ);
-    coord_t * v;
     size_t numVertices, i;
 
-    v = ws.getVertexesArray(0,numVertices);
+    boost::scoped_array<coord_t> v(ws.getVertexesArray(0,numVertices));
     TS_ASSERT_EQUALS( numVertices, 8 );
     i = 0;
     TS_ASSERT_DELTA( v[i+0], -10.0, 1e-5);
@@ -353,8 +355,11 @@ public:
     MDHistoWorkspaceIterator * hwit = dynamic_cast<MDHistoWorkspaceIterator *>(it);
     TS_ASSERT( hwit );
     TS_ASSERT( it->next() );
-    it = ws.createIterator(new MDImplicitFunction() );
+    delete it;
+    boost::scoped_ptr<MDImplicitFunction> mdfunction(new MDImplicitFunction);
+    it = ws.createIterator(mdfunction.get());
     TS_ASSERT( it );
+    delete it;
   }
 
   //---------------------------------------------------------------------------------------------------
diff --git a/Code/Mantid/Framework/DataObjects/test/MDLeanEventTest.h b/Code/Mantid/Framework/DataObjects/test/MDLeanEventTest.h
index e485b4e6f30a9fae858fbabbf0e668026bd1369a..4a01af6ec5e8472e5a01938af080f5ac8541ab91 100644
--- a/Code/Mantid/Framework/DataObjects/test/MDLeanEventTest.h
+++ b/Code/Mantid/Framework/DataObjects/test/MDLeanEventTest.h
@@ -8,6 +8,8 @@
 #include <iomanip>
 #include <iostream>
 
+#include <boost/scoped_array.hpp>
+
 using namespace Mantid;
 using namespace Mantid::DataObjects;
 
@@ -43,12 +45,12 @@ public:
     TS_ASSERT_EQUALS( a.getCenter(2), 2.5);
 
     // Dynamic array
-    coord_t * coords2 = new coord_t[5];
+    boost::scoped_array<coord_t> coords2(new coord_t[5]);
     coords2[0] = 1.0;
     coords2[1] = 2.0;
     coords2[2] = 3.0;
 
-    MDLeanEvent<3> b(2.5, 1.5, coords2 );
+    MDLeanEvent<3> b(2.5, 1.5, coords2.get() );
     TS_ASSERT_EQUALS( b.getSignal(), 2.5);
     TS_ASSERT_EQUALS( b.getErrorSquared(), 1.5);
     TS_ASSERT_EQUALS( b.getCenter(0), 1);
diff --git a/Code/Mantid/Framework/Doxygen/Mantid_template.doxyfile b/Code/Mantid/Framework/Doxygen/Mantid_template.doxyfile
index d2986f0614fb6483248143f876efdf117708da80..c6d470f865e1f22ed8fe1bccda8c0c020fb90cc3 100644
--- a/Code/Mantid/Framework/Doxygen/Mantid_template.doxyfile
+++ b/Code/Mantid/Framework/Doxygen/Mantid_template.doxyfile
@@ -98,8 +98,6 @@ INPUT = @CMAKE_CURRENT_SOURCE_DIR@/../Algorithms/inc \
         @CMAKE_CURRENT_SOURCE_DIR@/../MatlabAPI/src \
         @CMAKE_CURRENT_SOURCE_DIR@/../MDAlgorithms/inc \
         @CMAKE_CURRENT_SOURCE_DIR@/../MDAlgorithms/src \
-        @CMAKE_CURRENT_SOURCE_DIR@/../MDEvents/inc \
-        @CMAKE_CURRENT_SOURCE_DIR@/../MDEvents/src \
         @CMAKE_CURRENT_SOURCE_DIR@/../Nexus/inc \
         @CMAKE_CURRENT_SOURCE_DIR@/../Nexus/src \
         @CMAKE_CURRENT_SOURCE_DIR@/../PythonInterface/inc/MantidPythonInterface/kernel \
diff --git a/Code/Mantid/Framework/Geometry/inc/MantidGeometry/Crystal/PointGroup.h b/Code/Mantid/Framework/Geometry/inc/MantidGeometry/Crystal/PointGroup.h
index f6ed56e7ba39116aa174b5943d0a0a60d60331cb..37c7e43c07457839b291522f9479c66d1ff22c39 100644
--- a/Code/Mantid/Framework/Geometry/inc/MantidGeometry/Crystal/PointGroup.h
+++ b/Code/Mantid/Framework/Geometry/inc/MantidGeometry/Crystal/PointGroup.h
@@ -75,6 +75,14 @@ typedef std::multimap<PointGroup::CrystalSystem, PointGroup_sptr>
 PointGroupCrystalSystemMap;
 MANTID_GEOMETRY_DLL PointGroupCrystalSystemMap getPointGroupsByCrystalSystem();
 
+MANTID_GEOMETRY_DLL
+std::string
+getCrystalSystemAsString(const PointGroup::CrystalSystem &crystalSystem);
+
+MANTID_GEOMETRY_DLL
+PointGroup::CrystalSystem
+getCrystalSystemFromString(const std::string &crystalSystem);
+
 } // namespace Mantid
 } // namespace Geometry
 
diff --git a/Code/Mantid/Framework/Geometry/inc/MantidGeometry/MDGeometry/MDBoxImplicitFunction.h b/Code/Mantid/Framework/Geometry/inc/MantidGeometry/MDGeometry/MDBoxImplicitFunction.h
index b03d1f986bf4969869d2060b817a8760783ea252..57bf6394089fb1ffce015a6d49d7955b35f30951 100644
--- a/Code/Mantid/Framework/Geometry/inc/MantidGeometry/MDGeometry/MDBoxImplicitFunction.h
+++ b/Code/Mantid/Framework/Geometry/inc/MantidGeometry/MDGeometry/MDBoxImplicitFunction.h
@@ -5,6 +5,8 @@
 #include "MantidGeometry/MDGeometry/MDImplicitFunction.h"
 #include "MantidGeometry/MDGeometry/MDTypes.h"
 #include "MantidKernel/VMD.h"
+#include <vector>
+#include <boost/tuple/tuple.hpp>
 
 namespace Mantid {
 namespace Geometry {
@@ -39,7 +41,6 @@ namespace Geometry {
 */
 class DLLExport MDBoxImplicitFunction : public MDImplicitFunction {
 public:
-  MDBoxImplicitFunction();
 
   MDBoxImplicitFunction(const Mantid::Kernel::VMD &min,
                         const Mantid::Kernel::VMD &max);
@@ -47,10 +48,24 @@ public:
   MDBoxImplicitFunction(const std::vector<coord_t> &min,
                         const std::vector<coord_t> &max);
 
-  void construct(const Mantid::Kernel::VMD &min,
-                 const Mantid::Kernel::VMD &max);
+  double volume() const;
+
+  double fraction(const std::vector<boost::tuple<Mantid::coord_t, Mantid::coord_t> >& extents) const;
 
   virtual ~MDBoxImplicitFunction();
+
+private:
+
+  void construct(const Mantid::Kernel::VMD &min,
+                         const Mantid::Kernel::VMD &max);
+
+  /// Maximum extents of MDBox
+  const Mantid::Kernel::VMD m_max;
+  /// Minimum extents of MDBox
+  const Mantid::Kernel::VMD m_min;
+  /// Box volume
+  double m_volume;
+
 };
 
 } // namespace Geometry
diff --git a/Code/Mantid/Framework/Geometry/inc/MantidGeometry/MDGeometry/MDImplicitFunction.h b/Code/Mantid/Framework/Geometry/inc/MantidGeometry/MDGeometry/MDImplicitFunction.h
index 1d710812293f765a3392a844d6e51109d9df7155..d24d009dcaf74128cf25889bea3d7e6817a9f9d5 100644
--- a/Code/Mantid/Framework/Geometry/inc/MantidGeometry/MDGeometry/MDImplicitFunction.h
+++ b/Code/Mantid/Framework/Geometry/inc/MantidGeometry/MDGeometry/MDImplicitFunction.h
@@ -245,7 +245,7 @@ public:
    * @param numPoints :: number of vertexes in the array.
    * @return eContact enum value
    */
-  eContact boxContact(const coord_t *vertexes, const size_t numPoints) {
+  eContact boxContact(const coord_t *vertexes, const size_t numPoints) const {
     // For speed, we can stop looking when we know the box CANNOT be fully
     // contained.
     bool lookForFullyContained = true;
diff --git a/Code/Mantid/Framework/Geometry/src/ComponentParser.cpp b/Code/Mantid/Framework/Geometry/src/ComponentParser.cpp
index 7bbf4d727069c85757bade200ec9fd4bd6d9cf3f..c856fc370d6eff5461aaefba697e1a43e4ac5962 100644
--- a/Code/Mantid/Framework/Geometry/src/ComponentParser.cpp
+++ b/Code/Mantid/Framework/Geometry/src/ComponentParser.cpp
@@ -1,6 +1,4 @@
 #include "MantidGeometry/ComponentParser.h"
-#include "MantidKernel/System.h"
-#include "MantidGeometry/Instrument/Component.h"
 
 using namespace Mantid::Kernel;
 
diff --git a/Code/Mantid/Framework/Geometry/src/Crystal/CrystalStructure.cpp b/Code/Mantid/Framework/Geometry/src/Crystal/CrystalStructure.cpp
index b96af9560f93ad6924231343df56054504477351..e69831f6763fbf744aa94393d672b500c57b23ac 100644
--- a/Code/Mantid/Framework/Geometry/src/Crystal/CrystalStructure.cpp
+++ b/Code/Mantid/Framework/Geometry/src/Crystal/CrystalStructure.cpp
@@ -220,7 +220,7 @@ CrystalStructure::getDValues(const std::vector<V3D> &hkls) const {
 
   std::vector<double> dValues(hkls.size());
   std::transform(hkls.begin(), hkls.end(), dValues.begin(),
-                 boost::bind<double>(&CrystalStructure::getDValue, this, _1));
+                 boost::bind(&CrystalStructure::getDValue, this, _1));
 
   return dValues;
 }
diff --git a/Code/Mantid/Framework/Geometry/src/Crystal/Group.cpp b/Code/Mantid/Framework/Geometry/src/Crystal/Group.cpp
index 79a42fa39fbf31aada7bb6fa7974a6b34c583667..8eb35261ee09a635977655938b05afd04c5e8595 100644
--- a/Code/Mantid/Framework/Geometry/src/Crystal/Group.cpp
+++ b/Code/Mantid/Framework/Geometry/src/Crystal/Group.cpp
@@ -1,6 +1,5 @@
 #include "MantidGeometry/Crystal/Group.h"
 #include "MantidGeometry/Crystal/SymmetryOperationFactory.h"
-#include <boost/make_shared.hpp>
 
 namespace Mantid {
 namespace Geometry {
diff --git a/Code/Mantid/Framework/Geometry/src/Crystal/PointGroup.cpp b/Code/Mantid/Framework/Geometry/src/Crystal/PointGroup.cpp
index 3a521aea6cbea6b5fb300e23465455cc610d0360..138b973085d963e4396f9960d655da9fa0a3f11c 100644
--- a/Code/Mantid/Framework/Geometry/src/Crystal/PointGroup.cpp
+++ b/Code/Mantid/Framework/Geometry/src/Crystal/PointGroup.cpp
@@ -3,6 +3,7 @@
 
 #include <set>
 #include <boost/make_shared.hpp>
+#include <boost/algorithm/string.hpp>
 #include <iostream>
 
 #include "MantidGeometry/Crystal/PointGroupFactory.h"
@@ -182,5 +183,50 @@ PointGroupCrystalSystemMap getPointGroupsByCrystalSystem() {
   return map;
 }
 
+/// Return a human-readable string for the given crystal system
+std::string
+getCrystalSystemAsString(const PointGroup::CrystalSystem &crystalSystem) {
+  switch (crystalSystem) {
+  case PointGroup::Cubic:
+    return "Cubic";
+  case PointGroup::Tetragonal:
+    return "Tetragonal";
+  case PointGroup::Hexagonal:
+    return "Hexagonal";
+  case PointGroup::Trigonal:
+    return "Trigonal";
+  case PointGroup::Orthorhombic:
+    return "Orthorhombic";
+  case PointGroup::Monoclinic:
+    return "Monoclinic";
+  default:
+    return "Triclinic";
+  }
+}
+
+PointGroup::CrystalSystem
+getCrystalSystemFromString(const std::string &crystalSystem) {
+  std::string crystalSystemLC = boost::algorithm::to_lower_copy(crystalSystem);
+
+  if (crystalSystemLC == "cubic") {
+    return PointGroup::Cubic;
+  } else if (crystalSystemLC == "tetragonal") {
+    return PointGroup::Tetragonal;
+  } else if (crystalSystemLC == "hexagonal") {
+    return PointGroup::Hexagonal;
+  } else if (crystalSystemLC == "trigonal") {
+    return PointGroup::Trigonal;
+  } else if (crystalSystemLC == "orthorhombic") {
+    return PointGroup::Orthorhombic;
+  } else if (crystalSystemLC == "monoclinic") {
+    return PointGroup::Monoclinic;
+  } else if (crystalSystemLC == "triclinic") {
+    return PointGroup::Triclinic;
+  } else {
+    throw std::invalid_argument("Not a valid crystal system: '" +
+                                crystalSystem + "'.");
+  }
+}
+
 } // namespace Mantid
 } // namespace Geometry
diff --git a/Code/Mantid/Framework/Geometry/src/IObjComponent.cpp b/Code/Mantid/Framework/Geometry/src/IObjComponent.cpp
index 53528c857c8805f0993cab55440e906bf0e3c50b..ff0837baf7746ca740ce821388f3946832d81797 100644
--- a/Code/Mantid/Framework/Geometry/src/IObjComponent.cpp
+++ b/Code/Mantid/Framework/Geometry/src/IObjComponent.cpp
@@ -2,11 +2,8 @@
 // Includes
 //----------------------------------------------------------------------
 #include "MantidGeometry/IObjComponent.h"
-#include "MantidGeometry/Objects/Object.h"
-#include "MantidKernel/Exception.h"
 #include "MantidGeometry/Rendering/GeometryHandler.h"
 #include "MantidGeometry/Rendering/CacheGeometryHandler.h"
-#include <cfloat>
 
 namespace Mantid {
 namespace Geometry {
diff --git a/Code/Mantid/Framework/Geometry/src/Instrument.cpp b/Code/Mantid/Framework/Geometry/src/Instrument.cpp
index c2acdee929cd15ab66761ea12589fe3d17df32b2..3ddae81ad4ccb58bd6d0dda01c7fa25a4475dd98 100644
--- a/Code/Mantid/Framework/Geometry/src/Instrument.cpp
+++ b/Code/Mantid/Framework/Geometry/src/Instrument.cpp
@@ -1,18 +1,10 @@
 #include "MantidGeometry/Instrument.h"
-#include "MantidKernel/V3D.h"
-#include "MantidKernel/Exception.h"
-#include "MantidKernel/Logger.h"
-#include "MantidGeometry/Instrument/ParameterMap.h"
 #include "MantidGeometry/Instrument/ParComponentFactory.h"
-#include "MantidGeometry/Objects/BoundingBox.h"
-#include "MantidGeometry/Instrument/CompAssembly.h"
 #include "MantidGeometry/Instrument/DetectorGroup.h"
 #include "MantidGeometry/Instrument/ReferenceFrame.h"
 #include "MantidGeometry/Instrument/RectangularDetector.h"
 
 #include <Poco/Path.h>
-#include <algorithm>
-#include <sstream>
 #include <queue>
 
 using namespace Mantid::Kernel;
diff --git a/Code/Mantid/Framework/Geometry/src/MDGeometry/MDBoxImplicitFunction.cpp b/Code/Mantid/Framework/Geometry/src/MDGeometry/MDBoxImplicitFunction.cpp
index 49ee9bcbc7e94de2ea75e0ad273d00dc7c5346c1..923cac6194b0d262f9aff64a883d063c5efa359a 100644
--- a/Code/Mantid/Framework/Geometry/src/MDGeometry/MDBoxImplicitFunction.cpp
+++ b/Code/Mantid/Framework/Geometry/src/MDGeometry/MDBoxImplicitFunction.cpp
@@ -8,11 +8,6 @@ using Mantid::Kernel::VMD;
 namespace Mantid {
 namespace Geometry {
 
-//----------------------------------------------------------------------------------------------
-/** Default ctor
- */
-MDBoxImplicitFunction::MDBoxImplicitFunction() : MDImplicitFunction() {}
-
 //----------------------------------------------------------------------------------------------
 /** Constructor with min/max dimensions.
  *
@@ -24,7 +19,8 @@ MDBoxImplicitFunction::MDBoxImplicitFunction() : MDImplicitFunction() {}
  * @param max :: nd-sized vector of the maximum edge of the box
  */
 MDBoxImplicitFunction::MDBoxImplicitFunction(const std::vector<coord_t> &min,
-                                             const std::vector<coord_t> &max) {
+                                             const std::vector<coord_t> &max)
+    : m_max(max), m_min(min) {
   construct(VMD(min), VMD(max));
 }
 
@@ -39,7 +35,8 @@ MDBoxImplicitFunction::MDBoxImplicitFunction(const std::vector<coord_t> &min,
  * @param max :: nd-sized vector of the maximum edge of the box
  */
 MDBoxImplicitFunction::MDBoxImplicitFunction(const Mantid::Kernel::VMD &min,
-                                             const Mantid::Kernel::VMD &max) {
+                                             const Mantid::Kernel::VMD &max)
+    : m_max(max), m_min(min) {
   construct(min, max);
 }
 
@@ -59,7 +56,10 @@ void MDBoxImplicitFunction::construct(const Mantid::Kernel::VMD &min,
     throw std::invalid_argument(
         "MDBoxImplicitFunction::ctor(): Invalid number of dimensions!");
 
+  double volume = 1;
   for (size_t d = 0; d < nd; d++) {
+    volume *= (max[d] - min[d]);
+
     // Make two parallel planes per dimension
 
     // Normal on the min side, so it faces towards +X
@@ -84,6 +84,7 @@ void MDBoxImplicitFunction::construct(const Mantid::Kernel::VMD &min,
     MDPlane p_max(normal_max, origin_max);
     this->addPlane(p_max);
   }
+  m_volume = volume;
 }
 
 //----------------------------------------------------------------------------------------------
@@ -91,5 +92,43 @@ void MDBoxImplicitFunction::construct(const Mantid::Kernel::VMD &min,
  */
 MDBoxImplicitFunction::~MDBoxImplicitFunction() {}
 
+/**
+ * Calculate volume
+ * @return box volume
+ */
+double MDBoxImplicitFunction::volume() const { return m_volume; }
+
+/**
+ * Calculate the fraction of a box residing inside this implicit function
+ * @param boxExtents to get fraction for
+ * @return fraction 0 to 1
+ */
+double MDBoxImplicitFunction::fraction(const std::vector<boost::tuple<Mantid::coord_t, Mantid::coord_t> >& boxExtents) const {
+
+    size_t nd = m_min.size();
+    coord_t frac = 1;
+
+    for (size_t d = 0; d < nd; ++d) {
+
+      const coord_t min = boxExtents[d].get<0>();
+      const coord_t max = boxExtents[d].get<1>();
+
+      // Check that there is overlap at all. There must be overlap in ALL dimensions for the fraction to be > 0, so abort early if not.
+      if( max < m_min[d] || min > m_max[d]) {
+          frac = 0;
+          break;
+      }
+
+      const coord_t dBoxRange = (max - min); // max-min
+      const coord_t dInnerMin = std::max(m_min[d], min);
+      const coord_t dInnerMax = std::min(m_max[d], max);
+      const coord_t dOverlap = dInnerMax - dInnerMin;
+
+      frac *= dOverlap / dBoxRange;
+    }
+
+  return frac;
+}
+
 } // namespace Mantid
 } // namespace Geometry
diff --git a/Code/Mantid/Framework/Geometry/src/Math/Acomp.cpp b/Code/Mantid/Framework/Geometry/src/Math/Acomp.cpp
index 3ddb84653142f109c36d88f39af633ab589c55b3..0788103182bd08ed8d4202180f43ed171f722ee3 100644
--- a/Code/Mantid/Framework/Geometry/src/Math/Acomp.cpp
+++ b/Code/Mantid/Framework/Geometry/src/Math/Acomp.cpp
@@ -6,7 +6,6 @@
 #include "MantidGeometry/Math/RotCounter.h"
 #include <algorithm>
 #include <iostream>
-#include <iterator>
 #include <functional>
 
 namespace Mantid {
diff --git a/Code/Mantid/Framework/Geometry/src/Math/Algebra.cpp b/Code/Mantid/Framework/Geometry/src/Math/Algebra.cpp
index 073b829c503c4bc25f4fcfadb06a7e861a7d4018..d87ab1a5ae91930e7923355d64b8a39245cdc92c 100644
--- a/Code/Mantid/Framework/Geometry/src/Math/Algebra.cpp
+++ b/Code/Mantid/Framework/Geometry/src/Math/Algebra.cpp
@@ -6,14 +6,11 @@
 #include <set>
 #include <map>
 #include <stack>
-#include <string>
 #include <sstream>
 #include <algorithm>
-#include <functional>
 #include <iterator>
 
 #include "MantidKernel/Exception.h"
-#include "MantidKernel/Logger.h"
 #include "MantidKernel/Strings.h"
 #include "MantidGeometry/Math/Algebra.h"
 #include "MantidGeometry/Math/MapSupport.h"
diff --git a/Code/Mantid/Framework/Geometry/src/Math/BnId.cpp b/Code/Mantid/Framework/Geometry/src/Math/BnId.cpp
index d7f8f678b188b16abcbf7a590ba3c96268122979..25a999388cb556f39dac36496cb77df09b1f7b84 100644
--- a/Code/Mantid/Framework/Geometry/src/Math/BnId.cpp
+++ b/Code/Mantid/Framework/Geometry/src/Math/BnId.cpp
@@ -6,7 +6,6 @@
 #include <set>
 #include <map>
 #include <stack>
-#include <string>
 #include <sstream>
 #include <algorithm>
 #include <iterator>
diff --git a/Code/Mantid/Framework/Geometry/src/Math/PolyBase.cpp b/Code/Mantid/Framework/Geometry/src/Math/PolyBase.cpp
index 304894f4170689a34d19d9214574f51c881c1001..eac6ba5b99a7b0fb476bc5bed2e86b2f2860906f 100644
--- a/Code/Mantid/Framework/Geometry/src/Math/PolyBase.cpp
+++ b/Code/Mantid/Framework/Geometry/src/Math/PolyBase.cpp
@@ -4,7 +4,6 @@
 #include <vector>
 #include <algorithm>
 #include <iterator>
-#include <iterator>
 #include <functional>
 #include <gsl/gsl_poly.h>
 
diff --git a/Code/Mantid/Framework/Geometry/src/Math/mathSupport.cpp b/Code/Mantid/Framework/Geometry/src/Math/mathSupport.cpp
index 95fc600868dacd6c1e71f884c48d9ddfaba06226..acaea1386ca754f59598c893ef00184b3ee03778 100644
--- a/Code/Mantid/Framework/Geometry/src/Math/mathSupport.cpp
+++ b/Code/Mantid/Framework/Geometry/src/Math/mathSupport.cpp
@@ -4,7 +4,6 @@
 #include <vector>
 #include <iterator>
 #include <algorithm>
-#include <numeric>
 
 #include "MantidGeometry/Math/mathSupport.h"
 
diff --git a/Code/Mantid/Framework/Geometry/src/Rendering/OCGeometryGenerator.cpp b/Code/Mantid/Framework/Geometry/src/Rendering/OCGeometryGenerator.cpp
index d7b2f36805bc36e7dca6bc672e11a361cdd76400..f9bf1df320cdb5e74449782f6284a90627a66fa4 100644
--- a/Code/Mantid/Framework/Geometry/src/Rendering/OCGeometryGenerator.cpp
+++ b/Code/Mantid/Framework/Geometry/src/Rendering/OCGeometryGenerator.cpp
@@ -32,7 +32,9 @@
 #endif
 
 GCC_DIAG_OFF(conversion)
+// clang-format off
 GCC_DIAG_OFF(cast-qual)
+// clang-format on
 #include <gp_Trsf.hxx>
 #include <gp_Vec.hxx>
 #include <gp_Dir.hxx>
@@ -58,7 +60,9 @@ GCC_DIAG_OFF(cast-qual)
 #include <BRep_Tool.hxx>
 #include <Poly_Triangulation.hxx>
 GCC_DIAG_ON(conversion)
+// clang-format off
 GCC_DIAG_ON(cast-qual)
+// clang-format on
 
 #ifdef __INTEL_COMPILER
 #pragma warning enable 191
diff --git a/Code/Mantid/Framework/Geometry/src/Rendering/OCGeometryRenderer.cpp b/Code/Mantid/Framework/Geometry/src/Rendering/OCGeometryRenderer.cpp
index d67a87c881ba78e510dca603718f7b10e412ec02..e713533cada620f366ed1a6a7501815051a550ea 100644
--- a/Code/Mantid/Framework/Geometry/src/Rendering/OCGeometryRenderer.cpp
+++ b/Code/Mantid/Framework/Geometry/src/Rendering/OCGeometryRenderer.cpp
@@ -21,7 +21,9 @@
 #endif
 
 GCC_DIAG_OFF(conversion)
+// clang-format off
 GCC_DIAG_OFF(cast-qual)
+// clang-format on
 #include <gp_Pnt.hxx>
 #include <TopoDS.hxx>
 #include <TopoDS_Shape.hxx>
@@ -32,7 +34,9 @@ GCC_DIAG_OFF(cast-qual)
 #include <TColgp_Array1OfPnt.hxx>
 #include <Poly_Triangulation.hxx>
 GCC_DIAG_ON(conversion)
+// clang-format off
 GCC_DIAG_ON(cast-qual)
+// clang-format on
 
 #ifdef __INTEL_COMPILER
 #pragma warning enable 191
diff --git a/Code/Mantid/Framework/Geometry/test/MDBoxImplicitFunctionTest.h b/Code/Mantid/Framework/Geometry/test/MDBoxImplicitFunctionTest.h
index d39923045c3f61e9194ec0c564bbbfe5885be32a..af0d0c7d7060ac16dfc698814689cccdb5c1086b 100644
--- a/Code/Mantid/Framework/Geometry/test/MDBoxImplicitFunctionTest.h
+++ b/Code/Mantid/Framework/Geometry/test/MDBoxImplicitFunctionTest.h
@@ -12,6 +12,10 @@
 using namespace Mantid;
 using namespace Mantid::Geometry;
 
+namespace {
+typedef boost::tuple<Mantid::coord_t, Mantid::coord_t> Extent;
+}
+
 class MDBoxImplicitFunctionTest : public CxxTest::TestSuite
 {
 public:
@@ -51,6 +55,228 @@ public:
     TS_ASSERT( !try2Dpoint(f, 1.5,2.1) );
   }
 
+
+  void test_volume()
+  {
+    std::vector<coord_t> min, max;
+    min.push_back(0);
+    min.push_back(0);
+    min.push_back(0);
+    max.push_back(1);
+    max.push_back(2);
+    max.push_back(3);
+    MDBoxImplicitFunction box(min, max);
+    TS_ASSERT_EQUALS(1*2*3, box.volume());
+  }
+
+  void test_fraction_when_not_contained()
+  {
+      // The implicit function box
+      const coord_t areaMin = 1.0f;
+      const coord_t areaMax = 2.0f;
+      std::vector<coord_t> min;
+      min.push_back(areaMin);
+      min.push_back(areaMin);
+      std::vector<coord_t> max;
+      max.push_back(areaMax);
+      max.push_back(areaMax);
+      MDBoxImplicitFunction f(min,max);
+
+      // The box to test.
+      const coord_t boxMin = 0.0f;
+      const coord_t boxMax = 0.1f;
+      std::vector<Extent> extents;
+      // extent
+      extents.push_back(Extent(boxMin, boxMax));
+      // extent
+      extents.push_back(Extent(boxMin, boxMax));
+
+      TS_ASSERT_EQUALS(0.0, f.fraction(extents));
+  }
+
+  void test_fraction_when_fully_contained()
+  {
+      // The implicit function box
+      const coord_t areaMin = 1.0f;
+      const coord_t areaMax = 2.0f;
+      std::vector<coord_t> min;
+      min.push_back(areaMin);
+      min.push_back(areaMin);
+      std::vector<coord_t> max;
+      max.push_back(areaMax);
+      max.push_back(areaMax);
+      MDBoxImplicitFunction f(min,max);
+
+      // The box to test.
+      const coord_t boxMin = 1.1f;
+      const coord_t boxMax = 1.9f;
+      std::vector<coord_t> boxVertexes;
+      std::vector<Extent> extents;
+      // extent
+      extents.push_back(Extent(boxMin, boxMax));
+      // extent
+      extents.push_back(Extent(boxMin, boxMax));
+      // extent
+      extents.push_back(Extent(boxMin, boxMax));
+      // extent
+      extents.push_back(Extent(boxMin, boxMax));
+
+      TS_ASSERT_EQUALS(1.0, f.fraction(extents));
+  }
+
+  void test_fraction_when_partially_contained_1D_simple()
+  {
+      // The implicit function box
+      const coord_t areaMin = 0.9f;
+      const coord_t areaMax = 2.0f;
+      std::vector<coord_t> min;
+      min.push_back(areaMin);
+      std::vector<coord_t> max;
+      max.push_back(areaMax);
+      MDBoxImplicitFunction f(min,max);
+
+      // The box to test.
+      const coord_t boxMin = 0;
+      const coord_t boxMax = 1;
+      std::vector<Extent> extents;
+      // extent
+      extents.push_back(Extent(boxMin, boxMax));
+
+      /*
+
+                box to test
+      (x = 0) *------------------* (x = 1)
+
+                            implicit function 1D
+                    (x = 0.9) *--------------------------* (x = 2)
+
+      */
+
+      TSM_ASSERT_DELTA("Overlap fraction is incorrectly calculated", 0.1, f.fraction(extents), 1e-4);
+  }
+
+  void test_fraction_when_partially_contained_1D_complex()
+  {
+      // The implicit function box
+      const coord_t areaMin = 0.25;
+      const coord_t areaMax = 0.75;
+      std::vector<coord_t> min;
+      min.push_back(areaMin);
+      std::vector<coord_t> max;
+      max.push_back(areaMax);
+      MDBoxImplicitFunction f(min,max);
+
+      // The box to test.
+      const coord_t boxMin = 0;
+      const coord_t boxMax = 1.0;
+      std::vector<Extent> extents;
+      // extent
+      extents.push_back(Extent(boxMin, boxMax));
+
+      /*
+
+                                    box to test
+      (x = 0) *------------------------------------------------------* (x = 1)
+
+                                 implicit function 1D
+                  (x = 0.25) *--------------------------* (x = 0.75)
+
+      */
+
+      TSM_ASSERT_DELTA("Overlap fraction is incorrectly calculated", 0.5, f.fraction(extents), 1e-4);
+  }
+
+
+  void test_fraction_when_partially_contained_2d_simple()
+  {
+
+      /*
+
+        1/4 overlap
+
+                ---------------
+                |             |
+                |             |
+        ---------------       |
+        |       |     |       |
+        |       |     |       |
+        |       ------|--------
+        |             |
+        |             |
+        ---------------
+
+
+
+      */
+
+      // The implicit function box
+      const coord_t areaMin = 0.5;
+      const coord_t areaMax = 1.5;
+      std::vector<coord_t> min;
+      min.push_back(areaMin);
+      min.push_back(areaMin);
+      std::vector<coord_t> max;
+      max.push_back(areaMax);
+      max.push_back(areaMax);
+      MDBoxImplicitFunction f(min,max);
+
+      // The box to test.
+      const coord_t boxMin = 0;
+      const coord_t boxMax = 1;
+      std::vector<Extent> extents;
+      // extent
+      extents.push_back(Extent(boxMin, boxMax));
+      // extent
+      extents.push_back(Extent(boxMin, boxMax));
+
+      TSM_ASSERT_DELTA("2d overlap incorrectly calculated", 1.0/4, f.fraction(extents), 1e-3);
+  }
+
+  void test_fraction_when_partially_contained_2d_complex()
+  {
+
+      /*
+
+        1/8 overlap
+
+                ---------------
+                |  function   |
+                |             |
+        ---------------       |
+        |       |     |       |
+        |       ------|--------
+        |             |
+        |   box       |
+        |             |
+        ---------------
+
+
+
+      */
+
+      // The implicit function box
+      const coord_t areaMin = 0.5;
+      const coord_t areaMax = 1.5;
+      std::vector<coord_t> min;
+      min.push_back(areaMin); // xmin at 0.5
+      min.push_back(areaMin + (areaMin/2)); // ymin at 0.75
+      std::vector<coord_t> max;
+      max.push_back(areaMax);
+      max.push_back(areaMax + (areaMin/2)); // ymax at 0.75
+      MDBoxImplicitFunction f(min,max);
+
+      // The box to test.
+      const coord_t boxMin = 0;
+      const coord_t boxMax = 1;
+      std::vector<Extent> extents;
+      // extent
+      extents.push_back(Extent(boxMin, boxMax));
+      // extent
+      extents.push_back(Extent(boxMin, boxMax));
+
+      TSM_ASSERT_DELTA("2d overlap incorrectly calculated", 1.0/8, f.fraction(extents), 1e-3);
+  }
+
 };
 
 
diff --git a/Code/Mantid/Framework/Geometry/test/PointGroupTest.h b/Code/Mantid/Framework/Geometry/test/PointGroupTest.h
index 31a1f945dd5551cbd98370ac9c603b8133943004..0fd1f3159f44621aeb5150314179e077882d5799 100644
--- a/Code/Mantid/Framework/Geometry/test/PointGroupTest.h
+++ b/Code/Mantid/Framework/Geometry/test/PointGroupTest.h
@@ -193,6 +193,38 @@ public:
       checkPointGroupPerformance(pg);
   }
 
+  void testCrystalSystemNames()
+  {
+      TS_ASSERT_EQUALS(getCrystalSystemFromString("Cubic"), PointGroup::Cubic);
+      TS_ASSERT_EQUALS(getCrystalSystemFromString("cubic"), PointGroup::Cubic);
+      TS_ASSERT_EQUALS(getCrystalSystemFromString("CUBIC"), PointGroup::Cubic);
+      TS_ASSERT_EQUALS(getCrystalSystemFromString("CuBiC"), PointGroup::Cubic);
+
+      TS_ASSERT_EQUALS(getCrystalSystemFromString("Tetragonal"), PointGroup::Tetragonal);
+      TS_ASSERT_EQUALS(getCrystalSystemFromString("Hexagonal"), PointGroup::Hexagonal);
+      TS_ASSERT_EQUALS(getCrystalSystemFromString("Trigonal"), PointGroup::Trigonal);
+      TS_ASSERT_EQUALS(getCrystalSystemFromString("Orthorhombic"), PointGroup::Orthorhombic);
+      TS_ASSERT_EQUALS(getCrystalSystemFromString("Monoclinic"), PointGroup::Monoclinic);
+      TS_ASSERT_EQUALS(getCrystalSystemFromString("Triclinic"), PointGroup::Triclinic);
+
+      TS_ASSERT_THROWS(getCrystalSystemFromString("DoesNotExist"), std::invalid_argument);
+
+      TS_ASSERT_EQUALS(getCrystalSystemFromString(getCrystalSystemAsString(PointGroup::Cubic)),
+                       PointGroup::Cubic);
+      TS_ASSERT_EQUALS(getCrystalSystemFromString(getCrystalSystemAsString(PointGroup::Tetragonal)),
+                       PointGroup::Tetragonal);
+      TS_ASSERT_EQUALS(getCrystalSystemFromString(getCrystalSystemAsString(PointGroup::Hexagonal)),
+                       PointGroup::Hexagonal);
+      TS_ASSERT_EQUALS(getCrystalSystemFromString(getCrystalSystemAsString(PointGroup::Trigonal)),
+                       PointGroup::Trigonal);
+      TS_ASSERT_EQUALS(getCrystalSystemFromString(getCrystalSystemAsString(PointGroup::Orthorhombic)),
+                       PointGroup::Orthorhombic);
+      TS_ASSERT_EQUALS(getCrystalSystemFromString(getCrystalSystemAsString(PointGroup::Monoclinic)),
+                       PointGroup::Monoclinic);
+      TS_ASSERT_EQUALS(getCrystalSystemFromString(getCrystalSystemAsString(PointGroup::Triclinic)),
+                       PointGroup::Triclinic);
+  }
+
 private:
   void checkPointGroupPerformance(const PointGroup_sptr &pointGroup)
   {
diff --git a/Code/Mantid/Framework/ICat/src/CatalogSearch.cpp b/Code/Mantid/Framework/ICat/src/CatalogSearch.cpp
index 678362ddadb884af778b97b5aed1902cc6927f64..75852a2a32f3b8ba7bcc08b4e58d583f6f3fcc31 100644
--- a/Code/Mantid/Framework/ICat/src/CatalogSearch.cpp
+++ b/Code/Mantid/Framework/ICat/src/CatalogSearch.cpp
@@ -1,9 +1,13 @@
 #if GCC_VERSION >= 40800 // 4.8.0
+// clang-format off
 GCC_DIAG_OFF(literal-suffix)
+// clang-format on
 #endif
 #include "MantidICat/CatalogSearch.h"
 #if GCC_VERSION >= 40800 // 4.8.0
+// clang-format off
 GCC_DIAG_ON(literal-suffix)
+// clang-format on
 #endif
 
 #include "MantidAPI/CatalogManager.h"
diff --git a/Code/Mantid/Framework/ICat/src/GSoap.cpp b/Code/Mantid/Framework/ICat/src/GSoap.cpp
index f68a779bd788621a1ec496003336e4b5f554dfd4..d0c2ea6339a65b395a4d8f939e85ffd0442a61ec 100644
--- a/Code/Mantid/Framework/ICat/src/GSoap.cpp
+++ b/Code/Mantid/Framework/ICat/src/GSoap.cpp
@@ -4,14 +4,18 @@
 // disable some warnings that we understand but do not want to touch as
 // it is automatically generated code
 //------------------------------------------------------------------------------
+// clang-format off
 GCC_DIAG_OFF(cast-qual)
 GCC_DIAG_OFF(conversion)
 GCC_DIAG_OFF(unused-parameter)
 GCC_DIAG_OFF(strict-aliasing)
+// clang-format on
 GCC_DIAG_OFF(format)
 GCC_DIAG_OFF(vla)
 #if GCC_VERSION >= 40800 // 4.8.0
+// clang-format off
 GCC_DIAG_OFF(literal-suffix)
+// clang-format on
 #endif
 #ifdef _WIN32
 #pragma warning(disable : 4100)
diff --git a/Code/Mantid/Framework/ICat/src/ICat3/ICat3GSoapGenerated.cpp b/Code/Mantid/Framework/ICat/src/ICat3/ICat3GSoapGenerated.cpp
index ed2b8e6ca0c38c3e25966957d89885626f2fd0cf..d1b54aeaaf706ddcc99d86080eb33de8a601eea4 100644
--- a/Code/Mantid/Framework/ICat/src/ICat3/ICat3GSoapGenerated.cpp
+++ b/Code/Mantid/Framework/ICat/src/ICat3/ICat3GSoapGenerated.cpp
@@ -4,14 +4,18 @@
 // disable some warnings that we understand but do not want to touch as
 // it is automatically generated code
 //------------------------------------------------------------------------------
+// clang-format off
 GCC_DIAG_OFF(cast-qual)
 GCC_DIAG_OFF(conversion)
 GCC_DIAG_OFF(unused-parameter)
 GCC_DIAG_OFF(strict-aliasing)
+// clang-format on
 GCC_DIAG_OFF(format)
 GCC_DIAG_OFF(vla)
 #if GCC_VERSION >= 40800 // 4.8.0
+// clang-format off
 GCC_DIAG_OFF(literal-suffix)
+// clang-format on
 #endif
 #ifdef _WIN32
 #pragma warning(disable : 4100)
diff --git a/Code/Mantid/Framework/ICat/src/ICat3/ICat3Helper.cpp b/Code/Mantid/Framework/ICat/src/ICat3/ICat3Helper.cpp
index 569e79501e068bc876390ffc1f552db4181a5055..fd06ff81d408fbfb64645c20f6e91b7064c6136c 100644
--- a/Code/Mantid/Framework/ICat/src/ICat3/ICat3Helper.cpp
+++ b/Code/Mantid/Framework/ICat/src/ICat3/ICat3Helper.cpp
@@ -2,7 +2,9 @@
 // Poco-related compilation error on Windows
 #include "MantidAPI/WorkspaceFactory.h"
 #if GCC_VERSION >= 40800 // 4.8.0
+// clang-format off
 GCC_DIAG_OFF(literal-suffix)
+// clang-format on
 #endif
 #include "MantidICat/ICat3/ICat3Helper.h"
 #include "MantidICat/ICat3/ICat3ErrorHandling.h"
diff --git a/Code/Mantid/Framework/ICat/src/ICat4/ICat4GSoapGenerated.cpp b/Code/Mantid/Framework/ICat/src/ICat4/ICat4GSoapGenerated.cpp
index 1fea2753743711ef229fbfab5d0dffd927ce793f..b58295fd0b34780f542568e18df5e727b746f17d 100644
--- a/Code/Mantid/Framework/ICat/src/ICat4/ICat4GSoapGenerated.cpp
+++ b/Code/Mantid/Framework/ICat/src/ICat4/ICat4GSoapGenerated.cpp
@@ -4,14 +4,18 @@
 // disable some warnings that we understand but do not want to touch as
 // it is automatically generated code
 //------------------------------------------------------------------------------
+// clang-format off
 GCC_DIAG_OFF(cast-qual)
 GCC_DIAG_OFF(conversion)
 GCC_DIAG_OFF(unused-parameter)
 GCC_DIAG_OFF(strict-aliasing)
+// clang-format on
 GCC_DIAG_OFF(format)
 GCC_DIAG_OFF(vla)
 #if GCC_VERSION >= 40800 // 4.8.0
+// clang-format off
 GCC_DIAG_OFF(literal-suffix)
+// clang-format on
 #endif
 #ifdef _WIN32
 #pragma warning(disable : 4100)
diff --git a/Code/Mantid/Framework/Kernel/CMakeLists.txt b/Code/Mantid/Framework/Kernel/CMakeLists.txt
index 07d6f10edbb7529ecaf9e15a95a7d554e653a20e..d2435a2742b3a5f15857bc12609c26d81d53f508 100644
--- a/Code/Mantid/Framework/Kernel/CMakeLists.txt
+++ b/Code/Mantid/Framework/Kernel/CMakeLists.txt
@@ -13,7 +13,7 @@ set ( SRC_FILES
 	src/ChecksumHelper.cpp
 	src/DataItem.cpp
 	src/DateAndTime.cpp
-	src/DateTimeValidator.cpp 
+	src/DateTimeValidator.cpp
 	src/DateValidator.cpp
 	src/DeltaEMode.cpp
 	src/DirectoryValidator.cpp
@@ -398,7 +398,11 @@ if ( GCC_COMPILER_VERSION AND GCC_COMPILER_VERSION VERSION_LESS "4.5" )
  target_link_libraries ( Kernel stdc++ )
 endif()
 target_link_libraries ( Kernel ${NEXUS_LIBRARIES} ${MANTIDLIBS} ${GSL_LIBRARIES} 
-                        ${NETWORK_LIBRARIES} ${JSONCPP_LIBRARIES} )
+                        ${NETWORK_LIBRARIES} ${JSONCPP_LIBRARIES})
+if (WITH_ASAN)
+  target_link_libraries ( Kernel -lasan )
+endif ()
+
 if ( WIN32 )
   target_link_libraries ( Kernel Psapi.lib ) # For memory usage queries
 endif()
@@ -447,7 +451,11 @@ if ( ${CMAKE_PROJECT_NAME} STREQUAL "MantidFramework" )
 endif ()
 
 set ( PLUGINS "." )
-set ( PV_PLUGINS "./pvplugins" )
+if ( MAKE_VATES )
+  set ( PV_PLUGINS "./${PVPLUGINS_DIR}" )
+else ()
+  set ( PV_PLUGINS "" )
+endif ()
 set ( IGNORE_PARAVIEW "0" )
 set ( QTPLUGINS "." )
 set ( UPDATE_INSTRUMENT_DEFINTITIONS "0" )
diff --git a/Code/Mantid/Framework/Kernel/inc/MantidKernel/ConfigService.h b/Code/Mantid/Framework/Kernel/inc/MantidKernel/ConfigService.h
index e1d33012d1567775eaf96156157e68e43de3b0e4..5f218e2a1dc0f05d15bc93628702cdcf0c663a6a 100644
--- a/Code/Mantid/Framework/Kernel/inc/MantidKernel/ConfigService.h
+++ b/Code/Mantid/Framework/Kernel/inc/MantidKernel/ConfigService.h
@@ -234,20 +234,15 @@ public:
   // Starts up the logging
   void configureLogging();
 
-  /// Set the path to the paraview libraries
-  void setParaviewLibraryPath(const std::string &path);
+  /// Return true if ParaView plugins are available
+  bool pvPluginsAvailable() const;
 
-  /// Quick check to determine if paraview is available.
-  bool quickParaViewCheck() const;
-
-  /// Quick check to determine if vates has been installed.
-  bool quickVatesCheck() const;
+  /// Return the path to the pv plugins
+  const std::string getPVPluginsPath() const;
 
   /// Gets the proxy for the system
   Kernel::ProxyInfo &getProxy(const std::string &url);
 
-  /// Get the ParaViewPath
-  const std::string getParaViewPath() const;
 
 private:
   friend struct Mantid::Kernel::CreateUsingNew<ConfigServiceImpl>;
@@ -286,8 +281,6 @@ private:
   /// Empty the list of facilities, deleting the FacilityInfo objects in the
   /// process
   void clearFacilities();
-  /// Set the PV_PLUGIN_PATH to point at this version of Mantid.
-  void setParaViewPluginPath() const;
   /// Verifies the directory exists and add it to the back of the directory list
   /// if valid
   bool addDirectoryifExists(const std::string &directoryName,
diff --git a/Code/Mantid/Framework/Kernel/inc/MantidKernel/EnabledWhenProperty.h b/Code/Mantid/Framework/Kernel/inc/MantidKernel/EnabledWhenProperty.h
index da0ab0d41a0887127735de8c17f8b8e2981dc3c9..191cdb19c258ca71f15aadbd0884055248bdeb53 100644
--- a/Code/Mantid/Framework/Kernel/inc/MantidKernel/EnabledWhenProperty.h
+++ b/Code/Mantid/Framework/Kernel/inc/MantidKernel/EnabledWhenProperty.h
@@ -77,12 +77,10 @@ public:
    * (as string) to check for
    */
   EnabledWhenProperty(std::string otherPropName, ePropertyCriterion when,
-                      std::string value = "")
-      : IPropertySettings(), m_otherPropName(otherPropName), m_when(when),
-        m_value(value) {}
+                      std::string value = "");
 
   /// Destructor
-  virtual ~EnabledWhenProperty() {}
+  virtual ~EnabledWhenProperty();
 
   //--------------------------------------------------------------------------------------------
   /** Does the validator fulfill the criterion based on the
@@ -90,62 +88,21 @@ public:
    * @return true if fulfilled or if any problem was found (missing property,
    * e.g.).
    */
-  virtual bool fulfillsCriterion(const IPropertyManager *algo) const {
-    // Find the property
-    if (algo == NULL)
-      return true;
-    Property *prop = NULL;
-    try {
-      prop = algo->getPointerToProperty(m_otherPropName);
-    } catch (Exception::NotFoundError &) {
-      return true; // Property not found. Ignore
-    }
-    if (!prop)
-      return true;
-
-    // Value of the other property
-    std::string propValue = prop->value();
-
-    // OK, we have the property. Check the condition
-    switch (m_when) {
-    case IS_DEFAULT:
-      return prop->isDefault();
-    case IS_NOT_DEFAULT:
-      return !prop->isDefault();
-    case IS_EQUAL_TO:
-      return (propValue == m_value);
-    case IS_NOT_EQUAL_TO:
-      return (propValue != m_value);
-    case IS_MORE_OR_EQ: {
-      int check = boost::lexical_cast<int>(m_value);
-      int iPropV = boost::lexical_cast<int>(propValue);
-      return (iPropV >= check);
-    }
-    default:
-      // Unknown criterion
-      return true;
-    }
-  }
+  virtual bool fulfillsCriterion(const IPropertyManager *algo) const;
 
   //--------------------------------------------------------------------------------------------
   /// Return true/false based on whether the other property satisfies the
   /// criterion
-  virtual bool isEnabled(const IPropertyManager *algo) const {
-    return fulfillsCriterion(algo);
-  }
+  virtual bool isEnabled(const IPropertyManager *algo) const;
 
   //--------------------------------------------------------------------------------------------
   /// Return true always
-  virtual bool isVisible(const IPropertyManager *) const { return true; }
+  virtual bool isVisible(const IPropertyManager *) const;
   /// does nothing in this case and put here to satisfy the interface.
-  void modify_allowed_values(Property *const) {}
+  void modify_allowed_values(Property *const);
   //--------------------------------------------------------------------------------------------
   /// Make a copy of the present type of validator
-  virtual IPropertySettings *clone() {
-    EnabledWhenProperty *out =
-        new EnabledWhenProperty(m_otherPropName, m_when, m_value);
-    return out;
-  }
+  virtual IPropertySettings *clone();
 
 protected:
   /// Name of the OTHER property that we will check.
diff --git a/Code/Mantid/Framework/Kernel/inc/MantidKernel/Utils.h b/Code/Mantid/Framework/Kernel/inc/MantidKernel/Utils.h
index e53ef353320531563f25afcfef32b993c83153e8..d83377b96dcd4bfe9c4fb90c84915c5ee2b992db 100644
--- a/Code/Mantid/Framework/Kernel/inc/MantidKernel/Utils.h
+++ b/Code/Mantid/Framework/Kernel/inc/MantidKernel/Utils.h
@@ -289,23 +289,18 @@ inline void getIndicesFromLinearIndex(const size_t linear_index,
  * @param widths : width in pixels per dimension
  * @return True if the are neighbours, otherwise false.
  */
-inline bool isNeighbourOfSubject(const size_t ndims,
-                                 const size_t neighbour_linear_index,
-                                 const size_t *subject_indices,
-                                 const size_t *num_bins,
-                                 const size_t *index_max, const std::vector<int>& widths) {
-  std::vector<size_t> neighbour_indices(ndims);
-  Utils::NestedForLoop::GetIndicesFromLinearIndex(ndims, neighbour_linear_index,
-                                                  num_bins, index_max,
-                                                  &neighbour_indices.front());
-
+inline bool
+isNeighbourOfSubject(const size_t ndims, const size_t neighbour_linear_index,
+                     const size_t *subject_indices, const size_t *num_bins,
+                     const size_t *index_max, const std::vector<int> &widths) {
   for (size_t ind = 0; ind < ndims; ++ind) {
-    long double diff =
-        std::abs(static_cast<long double>(subject_indices[ind]) -
-                 static_cast<long double>(neighbour_indices[ind]));
-    if (diff > widths[ind]/2) {
+    size_t neigh_index =
+        (neighbour_linear_index / num_bins[ind]) % index_max[ind];
+    const long double subj = static_cast<long double>(subject_indices[ind]);
+    const long double neigh = static_cast<long double>(neigh_index);
+    const long double diff = std::abs(subj - neigh);
+    if (diff > widths[ind] / 2)
       return false;
-    }
   }
   return true;
 }
diff --git a/Code/Mantid/Framework/Kernel/inc/MantidKernel/VisibleWhenProperty.h b/Code/Mantid/Framework/Kernel/inc/MantidKernel/VisibleWhenProperty.h
index 2d36ae7f96b9d60c3c7a254040a9b48db3d4b5e4..24a7f889fce9d63a3841a3be80fb678905a5d146 100644
--- a/Code/Mantid/Framework/Kernel/inc/MantidKernel/VisibleWhenProperty.h
+++ b/Code/Mantid/Framework/Kernel/inc/MantidKernel/VisibleWhenProperty.h
@@ -44,30 +44,23 @@ public:
    * (as string) to check for
    */
   VisibleWhenProperty(std::string otherPropName, ePropertyCriterion when,
-                      std::string value = "")
-      : EnabledWhenProperty(otherPropName, when, value) {}
+                      std::string value = "");
 
   /// Destructor
-  virtual ~VisibleWhenProperty() {}
+  virtual ~VisibleWhenProperty();
 
   //--------------------------------------------------------------------------------------------
   /// Return true always
-  virtual bool isEnabled(const IPropertyManager *) const { return true; }
+  virtual bool isEnabled(const IPropertyManager *) const;
 
   //--------------------------------------------------------------------------------------------
   /// Return true/false based on whether the other property satisfies the
   /// criterion
-  virtual bool isVisible(const IPropertyManager *algo) const {
-    return this->fulfillsCriterion(algo);
-  }
+  virtual bool isVisible(const IPropertyManager *algo) const;
 
   //--------------------------------------------------------------------------------------------
   /// Make a copy of the present type of validator
-  virtual IPropertySettings *clone() {
-    VisibleWhenProperty *out = new VisibleWhenProperty(
-        this->m_otherPropName, this->m_when, this->m_value);
-    return out;
-  }
+  virtual IPropertySettings *clone();
 };
 
 } // namespace Kernel
diff --git a/Code/Mantid/Framework/Kernel/src/ArrayBoundedValidator.cpp b/Code/Mantid/Framework/Kernel/src/ArrayBoundedValidator.cpp
index e1031bb8d650873ddb9b4725c84889f0e63b691b..f4f0abce5886b338332b0398397f0ec0c3f555f3 100644
--- a/Code/Mantid/Framework/Kernel/src/ArrayBoundedValidator.cpp
+++ b/Code/Mantid/Framework/Kernel/src/ArrayBoundedValidator.cpp
@@ -1,9 +1,5 @@
 #include "MantidKernel/ArrayBoundedValidator.h"
 
-#include <iostream>
-#include <sstream>
-#include <string>
-
 namespace Mantid {
 namespace Kernel {
 
diff --git a/Code/Mantid/Framework/Kernel/src/ArrayLengthValidator.cpp b/Code/Mantid/Framework/Kernel/src/ArrayLengthValidator.cpp
index a731e60fb0f2a96275079148d47a7572697f17dd..aff8f4f52ad5c2816757a3cf56ecfc22905af6b3 100644
--- a/Code/Mantid/Framework/Kernel/src/ArrayLengthValidator.cpp
+++ b/Code/Mantid/Framework/Kernel/src/ArrayLengthValidator.cpp
@@ -1,5 +1,4 @@
 #include "MantidKernel/ArrayLengthValidator.h"
-#include "MantidKernel/System.h"
 
 using namespace Mantid::Kernel;
 
diff --git a/Code/Mantid/Framework/Kernel/src/Atom.cpp b/Code/Mantid/Framework/Kernel/src/Atom.cpp
index 2ac473b01aa8f9cd8880bd2b921be1e665da5085..7a9e2551517b3de90b58f93b514b58d07efdd2c2 100644
--- a/Code/Mantid/Framework/Kernel/src/Atom.cpp
+++ b/Code/Mantid/Framework/Kernel/src/Atom.cpp
@@ -1,6 +1,5 @@
 #include <algorithm>
 #include <iostream> // REMOVE
-#include <limits>
 #include <sstream>
 #include <stdexcept>
 #include "MantidKernel/Atom.h"
diff --git a/Code/Mantid/Framework/Kernel/src/CPUTimer.cpp b/Code/Mantid/Framework/Kernel/src/CPUTimer.cpp
index 3d4e41e96de2e56fbfd625c239245e65351515f5..608c2e9794586e2009aeb700bc021e952634ebe5 100644
--- a/Code/Mantid/Framework/Kernel/src/CPUTimer.cpp
+++ b/Code/Mantid/Framework/Kernel/src/CPUTimer.cpp
@@ -1,6 +1,4 @@
 #include "MantidKernel/CPUTimer.h"
-#include "MantidKernel/System.h"
-#include <ctime>
 #include <sstream>
 #include <iomanip>
 
diff --git a/Code/Mantid/Framework/Kernel/src/ChecksumHelper.cpp b/Code/Mantid/Framework/Kernel/src/ChecksumHelper.cpp
index 10247e421d76e39ba73bf65bd7b5b6587aca38a0..c4e50074f2e9564880935870ee22915715a0f48f 100644
--- a/Code/Mantid/Framework/Kernel/src/ChecksumHelper.cpp
+++ b/Code/Mantid/Framework/Kernel/src/ChecksumHelper.cpp
@@ -1,7 +1,6 @@
 #include "MantidKernel/ChecksumHelper.h"
 
 #include <boost/regex.hpp>
-#include <boost/scoped_ptr.hpp>
 #include <boost/shared_array.hpp>
 
 #include <Poco/MD5Engine.h>
@@ -10,7 +9,6 @@
 
 #include <fstream>
 #include <sstream>
-#include <string>
 
 namespace Mantid {
 namespace Kernel {
diff --git a/Code/Mantid/Framework/Kernel/src/ConfigService.cpp b/Code/Mantid/Framework/Kernel/src/ConfigService.cpp
index 700cb165f067533d540230934543a93bf354d236..4ff60619ab8f8ecd239f2466b9d06f6e745357f0 100644
--- a/Code/Mantid/Framework/Kernel/src/ConfigService.cpp
+++ b/Code/Mantid/Framework/Kernel/src/ConfigService.cpp
@@ -22,12 +22,9 @@
 #include <Poco/StringTokenizer.h>
 #include <Poco/DOM/DOMParser.h>
 #include <Poco/DOM/Document.h>
-#include <Poco/DOM/Element.h>
 #include <Poco/DOM/NodeList.h>
 #include <Poco/Environment.h>
-#include <Poco/File.h>
 #include <Poco/Process.h>
-#include <Poco/String.h>
 #include <Poco/URI.h>
 #ifdef _WIN32
 #pragma warning(disable : 4250)
@@ -40,10 +37,7 @@
 #include <boost/regex.hpp>
 
 #include <fstream>
-#include <sstream>
 #include <iostream>
-#include <string>
-#include <algorithm>
 
 #ifdef __APPLE__
 #include <mach-o/dyld.h>
@@ -316,7 +310,6 @@ void ConfigServiceImpl::loadConfig(const std::string &filename,
     // there was a problem loading the file - it probably is not there
     std::cerr << "Problem loading the configuration file " << filename << " "
               << e.what() << std::endl;
-
     if (!append) {
       // if we have no property values then take the default
       m_PropertyString = defaultConfig();
@@ -1566,42 +1559,6 @@ bool ConfigServiceImpl::isNetworkDrive(const std::string &path) {
 #endif
 }
 
-/**
- * Set the environment variable for the PV_PLUGIN_PATH based on where Mantid is.
- */
-void ConfigServiceImpl::setParaViewPluginPath() const {
-  std::string mantid_loc = this->getDirectoryOfExecutable();
-  Poco::Path pv_plugin_path(mantid_loc +
-                            "/pvplugins/pvplugins"); // Developer build paths
-  pv_plugin_path = pv_plugin_path.absolute();
-  g_log.debug() << "Trying " << pv_plugin_path.toString()
-                << " as PV_PLUGIN_PATH\n";
-  Poco::File pv_plugin(pv_plugin_path.toString());
-  if (!pv_plugin.exists() || !pv_plugin.isDirectory()) {
-    // Installation paths
-    g_log.debug("ParaView plugin directory \"" + pv_plugin.path() +
-                "\" does not exist. Trying properties file location.");
-    std::string user_loc = this->getString("pvplugins.directory");
-    if (user_loc.empty()) {
-      g_log.debug(
-          "No ParaView plugin directory specified in the properties file.");
-      return; // it didn't work
-    }
-    pv_plugin_path = Poco::Path(user_loc, "pvplugins");
-    pv_plugin_path = pv_plugin_path.absolute();
-    pv_plugin = Poco::File(pv_plugin_path.toString());
-    if (!pv_plugin.exists() || !pv_plugin.isDirectory()) {
-      g_log.debug("ParaView plugin directory \"" + pv_plugin.path() +
-                  "\" does not exist");
-      return; // it didn't work
-    }
-  }
-
-  // one of the two choices worked so set to that directory
-  g_log.debug("Setting PV_PLUGIN_PATH = \"" + pv_plugin.path() + "\"");
-  Poco::Environment::set("PV_PLUGIN_PATH", pv_plugin.path());
-}
-
 /**
  * Gets the directory that we consider to be the directory containing the
  * Mantid.properties file.
@@ -1962,151 +1919,21 @@ void ConfigServiceImpl::removeObserver(const Poco::AbstractObserver &observer)
 }
 
 /*
-Ammend paths to point to include the paraview core libraries.
-@param path : path to add
-*/
-void ConfigServiceImpl::setParaviewLibraryPath(const std::string &path) {
-#ifdef _WIN32
-  const std::string platformPathName = "PATH";
-  Poco::Path existingPath;
-  char separator = existingPath.pathSeparator();
-  std::string strSeparator;
-  strSeparator.push_back(separator);
-
-  if (Poco::Environment::has(platformPathName)) {
-    existingPath = Poco::Environment::get(platformPathName);
-    existingPath.append(strSeparator + path);
-  } else {
-    existingPath = path;
-  }
-  const std::string newPath = existingPath.toString();
-  Poco::Environment::set(platformPathName, newPath);
-#elif defined __linux__
-  UNUSED_ARG(path)
-  throw std::runtime_error("Cannot dynamically set the library path on Linux");
-#elif defined __APPLE__
-  UNUSED_ARG(path)
-  throw std::runtime_error("Cannot dynamically set the library path on Mac");
-#else
-  throw std::runtime_error("ConfigServiceImpl::setParaviewLibraryPath cannot "
-                           "determine the running platform and therefore "
-                           "cannot set the path to the Paraview libraries.");
-#endif
-}
-
-/*
-Extracts the string from a poco pipe and returns the numerical part.
-@param pipe : input pipe.
-@return the numerical part of the version string contained inside the pipe.
-*/
-const std::string extractVersionNumberFromPipe(const Poco::Pipe &pipe) {
-  std::string versionString = "undetermined";
-  Poco::PipeInputStream pipeStream(pipe);
-  std::stringstream stringStream;
-  Poco::StreamCopier::copyStream(pipeStream, stringStream);
-  const std::string givenVersion = stringStream.str();
-  boost::smatch match;
-  boost::regex expression(
-      "(\\d+)\\.(\\d+)\\.?(\\d*)$"); // Gets the version number part.
-  if (boost::regex_search(givenVersion, match, expression)) {
-    versionString = match[0];
-  }
-  return versionString;
-}
-
-/*
-Checks to see whether paraview usage is explicitly ignored in the property file
-then,
-quick check to determine if paraview is installed. We make the assumption
-that if the executable paraview binary is on the path that the paraview
-libraries
-will also be available on the library path, or equivalent.
+Checks to see whether the pvplugins.directory variable is set. If it is set, assume
+we have built Mantid with ParaView
 @return True if paraview is available or not disabled.
 */
-bool ConfigServiceImpl::quickParaViewCheck() const {
-  const std::string paraviewIgnoreProperty = "paraview.ignore";
-  const bool ignoreParaview = hasProperty(paraviewIgnoreProperty) &&
-                              atoi(getString(paraviewIgnoreProperty).c_str());
-  if (ignoreParaview) {
-    g_log.debug("Ignoring ParaView");
-    return false;
-  }
-
-  g_log.debug("Checking for ParaView");
-  bool isAvailable = false;
-
-  try {
-    // Try to run "paraview -V", which will succeed if ParaView is installed.
-    std::string paraviewDir = getString("paraview.path");
-    std::string cmd = "paraview";
-    if (!paraviewDir.empty()) {
-      Poco::Path paraviewExe = Poco::Path(paraviewDir, "paraview");
-      cmd = paraviewExe.toString();
-    }
-    std::vector<std::string> args;
-    args.push_back("-V");
-    Poco::Pipe outPipe, errorPipe;
-    Poco::ProcessHandle ph =
-        Poco::Process::launch(cmd, args, 0, &outPipe, &errorPipe);
-    const int rc = ph.wait();
-    // Only if the paraview query returned successfully.
-    if (rc == 1) {
-      // Check the actual version numbers against what we expect they should be.
-      const std::string givenVersionNumber =
-          extractVersionNumberFromPipe(errorPipe);
-      const std::string targetVersionNumber = ParaViewVersion::targetVersion();
-      if (givenVersionNumber == targetVersionNumber) {
-        isAvailable = true;
-        g_log.information("ParaView is available");
-        // Now set the plugin path.
-        this->setParaViewPluginPath();
-      } else {
-        std::stringstream messageStream;
-        messageStream << "The compatible version of ParaView is "
-                      << targetVersionNumber << " but the installed version is "
-                      << givenVersionNumber;
-        g_log.debug(messageStream.str());
-        g_log.information("ParaView is not available");
-      }
-    } else {
-      std::stringstream messageStream;
-      messageStream << "ParaView version query failed with code: " << rc;
-      g_log.debug(messageStream.str());
-      g_log.information("ParaView is not available");
-    }
-  }
-  catch (Poco::SystemException &e) {
-    g_log.debug(e.what());
-    g_log.information("ParaView is not available");
-  }
-  return isAvailable;
+bool ConfigServiceImpl::pvPluginsAvailable() const {
+  std::string pvpluginsDir = getString("pvplugins.directory");
+  return !pvpluginsDir.empty();
 }
 
-/*
-Quick check to determine if VATES is installed.
-@return TRUE if available.
-*/
-bool ConfigServiceImpl::quickVatesCheck() const {
-  std::string path = this->getDirectoryOfExecutable();
-
-  Poco::File dir(path);
-  typedef std::vector<std::string> VecFiles;
-
-  VecFiles files;
-  dir.list(files);
-  VecFiles::iterator it = files.begin();
-
-  bool found = false;
-  while (it != files.end()) {
-    std::string file = *it;
-    boost::regex expression("^(VatesSimpleGui)", boost::regex::icase);
-    if (boost::regex_search(file, expression)) {
-      found = true;
-      break;
-    }
-    ++it;
-  }
-  return found;
+/**
+ * Gets the path to the ParaView plugins
+ * @returns A string giving the directory of the ParaView plugins
+ */
+const std::string ConfigServiceImpl::getPVPluginsPath() const {
+  return getString("pvplugins.directory");
 }
 
 /*
@@ -2135,14 +1962,6 @@ Kernel::ProxyInfo &ConfigServiceImpl::getProxy(const std::string &url) {
   return m_proxyInfo;
 }
 
-/**
- * Gets the path to ParaView.
- * @returns The ParaView path.
- */
-const std::string ConfigServiceImpl::getParaViewPath() const {
-  return getString("paraview.path");
-}
-
 /// \cond TEMPLATE
 template DLLExport int ConfigServiceImpl::getValue(const std::string &,
                                                    double &);
diff --git a/Code/Mantid/Framework/Kernel/src/DateAndTime.cpp b/Code/Mantid/Framework/Kernel/src/DateAndTime.cpp
index 4d1be305d68919c7648dc06cc211916600631c5d..546dd9294e202eff489d1510e03e64342a821986 100644
--- a/Code/Mantid/Framework/Kernel/src/DateAndTime.cpp
+++ b/Code/Mantid/Framework/Kernel/src/DateAndTime.cpp
@@ -1,12 +1,8 @@
 #include "MantidKernel/DateAndTime.h"
 #include "MantidKernel/Logger.h"
-#include <time.h>
 #include <Poco/DateTime.h>
 #include <Poco/DateTimeFormat.h>
 #include <Poco/DateTimeParser.h>
-#include <boost/date_time/posix_time/posix_time_config.hpp>
-#include <ostream>
-#include <ctime>
 
 namespace Mantid {
 namespace Kernel {
diff --git a/Code/Mantid/Framework/Kernel/src/DateValidator.cpp b/Code/Mantid/Framework/Kernel/src/DateValidator.cpp
index 21c166f20b01ce7e831c95fff10d5b2b0247bb42..246f8988ae04a06e54225b91c3be610f9957f8b7 100644
--- a/Code/Mantid/Framework/Kernel/src/DateValidator.cpp
+++ b/Code/Mantid/Framework/Kernel/src/DateValidator.cpp
@@ -3,7 +3,6 @@
 //----------------------------------------------------------------------
 #include "MantidKernel/DateValidator.h"
 #include <boost/lexical_cast.hpp>
-#include <time.h>
 
 namespace Mantid {
 namespace Kernel {
diff --git a/Code/Mantid/Framework/Kernel/src/DirectoryValidator.cpp b/Code/Mantid/Framework/Kernel/src/DirectoryValidator.cpp
index 566b0ddcd1e84b931873dbc78edba2355a383746..af030ad128b8135fbbb307a808f10aa2ee82078c 100644
--- a/Code/Mantid/Framework/Kernel/src/DirectoryValidator.cpp
+++ b/Code/Mantid/Framework/Kernel/src/DirectoryValidator.cpp
@@ -1,9 +1,7 @@
 #include "MantidKernel/DirectoryValidator.h"
-#include <algorithm>
 #include <Poco/Exception.h>
 #include <Poco/File.h>
 #include <Poco/Path.h>
-#include <iostream>
 
 namespace Mantid {
 namespace Kernel {
diff --git a/Code/Mantid/Framework/Kernel/src/DiskBuffer.cpp b/Code/Mantid/Framework/Kernel/src/DiskBuffer.cpp
index d034504821a39878941d159ccf77b63669a377d9..0e2b61b091e48b9397c4c300c75de1a900d8cabb 100644
--- a/Code/Mantid/Framework/Kernel/src/DiskBuffer.cpp
+++ b/Code/Mantid/Framework/Kernel/src/DiskBuffer.cpp
@@ -1,7 +1,4 @@
 #include "MantidKernel/DiskBuffer.h"
-#include "MantidKernel/System.h"
-#include <Poco/ScopedLock.h>
-#include <iostream>
 #include <sstream>
 
 using namespace Mantid::Kernel;
diff --git a/Code/Mantid/Framework/Kernel/src/EnabledWhenProperty.cpp b/Code/Mantid/Framework/Kernel/src/EnabledWhenProperty.cpp
index 7629f94f3015502016cb439401b8549847956283..db875b8da785adbfccd7c874c85405807069e6bf 100644
--- a/Code/Mantid/Framework/Kernel/src/EnabledWhenProperty.cpp
+++ b/Code/Mantid/Framework/Kernel/src/EnabledWhenProperty.cpp
@@ -1,8 +1,71 @@
 #include "MantidKernel/EnabledWhenProperty.h"
-#include "MantidKernel/System.h"
 
 using namespace Mantid::Kernel;
 
 namespace Mantid {
-namespace Kernel {} // namespace Mantid
+namespace Kernel {
+EnabledWhenProperty::EnabledWhenProperty(std::string otherPropName,
+                                         ePropertyCriterion when,
+                                         std::string value)
+    : IPropertySettings(), m_otherPropName(otherPropName), m_when(when),
+      m_value(value) {}
+
+EnabledWhenProperty::~EnabledWhenProperty() {}
+
+bool
+EnabledWhenProperty::fulfillsCriterion(const IPropertyManager *algo) const {
+  // Find the property
+  if (algo == NULL)
+    return true;
+  Property *prop = NULL;
+  try {
+    prop = algo->getPointerToProperty(m_otherPropName);
+  } catch (Exception::NotFoundError &) {
+    return true; // Property not found. Ignore
+  }
+  if (!prop)
+    return true;
+
+  // Value of the other property
+  std::string propValue = prop->value();
+
+  // OK, we have the property. Check the condition
+  switch (m_when) {
+  case IS_DEFAULT:
+    return prop->isDefault();
+  case IS_NOT_DEFAULT:
+    return !prop->isDefault();
+  case IS_EQUAL_TO:
+    return (propValue == m_value);
+  case IS_NOT_EQUAL_TO:
+    return (propValue != m_value);
+  case IS_MORE_OR_EQ: {
+    int check = boost::lexical_cast<int>(m_value);
+    int iPropV = boost::lexical_cast<int>(propValue);
+    return (iPropV >= check);
+  }
+  default:
+    // Unknown criterion
+    return true;
+  }
+}
+
+bool EnabledWhenProperty::isEnabled(const IPropertyManager *algo) const {
+  return fulfillsCriterion(algo);
+}
+
+bool EnabledWhenProperty::isVisible(const IPropertyManager *) const {
+  return true;
+}
+/// does nothing in this case and put here to satisfy the interface.
+void EnabledWhenProperty::modify_allowed_values(Property *const) {}
+//--------------------------------------------------------------------------------------------
+/// Make a copy of the present type of validator
+IPropertySettings *EnabledWhenProperty::clone() {
+  EnabledWhenProperty *out =
+      new EnabledWhenProperty(m_otherPropName, m_when, m_value);
+  return out;
+}
+
+} // namespace Mantid
 } // namespace Kernel
diff --git a/Code/Mantid/Framework/Kernel/src/Exception.cpp b/Code/Mantid/Framework/Kernel/src/Exception.cpp
index 3eab33561a0df42f6d66e664e438fca6406707fa..6144671df7e148c03273f2db476dff8bb5bf58f5 100644
--- a/Code/Mantid/Framework/Kernel/src/Exception.cpp
+++ b/Code/Mantid/Framework/Kernel/src/Exception.cpp
@@ -1,6 +1,5 @@
 #include <iostream>
 #include <sstream>
-#include <string>
 #include "MantidKernel/Exception.h"
 
 namespace Mantid {
diff --git a/Code/Mantid/Framework/Kernel/src/FacilityInfo.cpp b/Code/Mantid/Framework/Kernel/src/FacilityInfo.cpp
index 9212e6ec540cf143f57c4c00f9e16e525deb642e..14712c0a5d3efe77341288f2c6cd71d5d09c2619 100644
--- a/Code/Mantid/Framework/Kernel/src/FacilityInfo.cpp
+++ b/Code/Mantid/Framework/Kernel/src/FacilityInfo.cpp
@@ -11,7 +11,6 @@
 #include "MantidKernel/Strings.h"
 
 #include <boost/algorithm/string.hpp>
-#include <boost/shared_ptr.hpp>
 
 #include <Poco/DOM/Element.h>
 #include <Poco/DOM/NodeList.h>
diff --git a/Code/Mantid/Framework/Kernel/src/FileValidator.cpp b/Code/Mantid/Framework/Kernel/src/FileValidator.cpp
index c968b019f098f444629b20d1fa2094b36b045039..ed0ed61793d02b723b96bf788d6ad13a2c7e917d 100644
--- a/Code/Mantid/Framework/Kernel/src/FileValidator.cpp
+++ b/Code/Mantid/Framework/Kernel/src/FileValidator.cpp
@@ -1,10 +1,7 @@
 #include "MantidKernel/FileValidator.h"
-#include "MantidKernel/Logger.h"
-#include <algorithm>
 #include <boost/algorithm/string/case_conv.hpp>
 #include <Poco/File.h>
 #include <Poco/Path.h>
-#include <iostream>
 
 namespace Mantid {
 namespace Kernel {
diff --git a/Code/Mantid/Framework/Kernel/src/FreeBlock.cpp b/Code/Mantid/Framework/Kernel/src/FreeBlock.cpp
index 7aecdb5a605cd7c1110f60ea4d33f82405a33b82..cb29c69bed2c5335f34573870a8bf12da084fd2e 100644
--- a/Code/Mantid/Framework/Kernel/src/FreeBlock.cpp
+++ b/Code/Mantid/Framework/Kernel/src/FreeBlock.cpp
@@ -1,6 +1,3 @@
-#include "MantidKernel/FreeBlock.h"
-#include "MantidKernel/System.h"
-
 namespace Mantid {
 namespace Kernel {} // namespace Mantid
 } // namespace Kernel
diff --git a/Code/Mantid/Framework/Kernel/src/IPropertyManager.cpp b/Code/Mantid/Framework/Kernel/src/IPropertyManager.cpp
index 36961d43915405e62d2d90412392bc68b81b579b..9aa813039a189e2ad36315ea216ced5436546b4a 100644
--- a/Code/Mantid/Framework/Kernel/src/IPropertyManager.cpp
+++ b/Code/Mantid/Framework/Kernel/src/IPropertyManager.cpp
@@ -2,9 +2,6 @@
 // Includes
 //----------------------------------------------------------------------
 #include "MantidKernel/IPropertyManager.h"
-#include "MantidKernel/Exception.h"
-#include "MantidKernel/System.h"
-#include <algorithm>
 
 ///@cond
 DEFINE_IPROPERTYMANAGER_GETVALUE(int16_t)
diff --git a/Code/Mantid/Framework/Kernel/src/ISaveable.cpp b/Code/Mantid/Framework/Kernel/src/ISaveable.cpp
index e031594d78473baa2a711f6cf65188b2fd37e7f7..c1c77c975dfa5fc409dbe6e9dd5464d912d3182f 100644
--- a/Code/Mantid/Framework/Kernel/src/ISaveable.cpp
+++ b/Code/Mantid/Framework/Kernel/src/ISaveable.cpp
@@ -1,8 +1,8 @@
 #include "MantidKernel/ISaveable.h"
-#include "MantidKernel/System.h"
-#include <limits>
 //#include "MantidKernel/INode.h"
 
+#include <limits>
+
 namespace Mantid {
 namespace Kernel {
 
diff --git a/Code/Mantid/Framework/Kernel/src/InstrumentInfo.cpp b/Code/Mantid/Framework/Kernel/src/InstrumentInfo.cpp
index 811e12887551ff58adde06ed77afd0e8a00ebc7f..9f17e25e395e4ca813a6c6fcc137171c09b78acf 100644
--- a/Code/Mantid/Framework/Kernel/src/InstrumentInfo.cpp
+++ b/Code/Mantid/Framework/Kernel/src/InstrumentInfo.cpp
@@ -5,7 +5,6 @@
 
 #include "MantidKernel/InstrumentInfo.h"
 #include "MantidKernel/FacilityInfo.h"
-#include "MantidKernel/Exception.h"
 #include "MantidKernel/Logger.h"
 #include "MantidKernel/Strings.h"
 
diff --git a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp
index 80366e03248ebe2ed7102c967ec24e440a7c8199..ed391b5bd717e1f9721bf12bff883d7c1f95362d 100644
--- a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp
+++ b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp
@@ -29,12 +29,11 @@
 #else
 #include <Poco/FileStream.h>
 #include <Poco/NullStream.h>
-#include <stdlib.h>
+
 #endif
 
 // std
 #include <fstream>
-#include <sstream>
 
 namespace Mantid {
 namespace Kernel {
diff --git a/Code/Mantid/Framework/Kernel/src/ListValidator.cpp b/Code/Mantid/Framework/Kernel/src/ListValidator.cpp
index e4cec745706f22658e7b4f191ccee90effcf551b..f57367781acfe92b4bd9bad1a4272522871c2915 100644
--- a/Code/Mantid/Framework/Kernel/src/ListValidator.cpp
+++ b/Code/Mantid/Framework/Kernel/src/ListValidator.cpp
@@ -1,7 +1,6 @@
 //----------------------------------------------------------------------
 // Includes
 //----------------------------------------------------------------------
-#include "MantidKernel/ListValidator.h"
 
 namespace Mantid {
 namespace Kernel {} // namespace Kernel
diff --git a/Code/Mantid/Framework/Kernel/src/LogFilter.cpp b/Code/Mantid/Framework/Kernel/src/LogFilter.cpp
index bc20870417e64f6a2e4cefdcfda375026d963ec8..6cd99a7daec8c518e3e4422c279334d52e21e543 100644
--- a/Code/Mantid/Framework/Kernel/src/LogFilter.cpp
+++ b/Code/Mantid/Framework/Kernel/src/LogFilter.cpp
@@ -1,6 +1,5 @@
 #include "MantidKernel/LogFilter.h"
 #include "MantidKernel/TimeSeriesProperty.h"
-#include <stdexcept>
 
 namespace Mantid {
 namespace Kernel {
diff --git a/Code/Mantid/Framework/Kernel/src/LogParser.cpp b/Code/Mantid/Framework/Kernel/src/LogParser.cpp
index e88d7f883f308beaf3c98e47d179f04d5cf0e866..533da10a5deeaafdf8ecbb2e1d94c61ade15445b 100644
--- a/Code/Mantid/Framework/Kernel/src/LogParser.cpp
+++ b/Code/Mantid/Framework/Kernel/src/LogParser.cpp
@@ -7,10 +7,7 @@
 #include "MantidKernel/PropertyWithValue.h"
 #include "MantidKernel/TimeSeriesProperty.h"
 
-#include <algorithm>
 #include <fstream>
-#include <limits>
-#include <sstream>
 
 // constants for the new style icp event commands
 const char *START_COLLECTION = "START_COLLECTION";
diff --git a/Code/Mantid/Framework/Kernel/src/Logger.cpp b/Code/Mantid/Framework/Kernel/src/Logger.cpp
index 5eef2861a3aaf2fe5368258edde6169deafe259d..9f576555e68e18be2e5e20226d23ea4132f637b8 100644
--- a/Code/Mantid/Framework/Kernel/src/Logger.cpp
+++ b/Code/Mantid/Framework/Kernel/src/Logger.cpp
@@ -1,8 +1,5 @@
 #include "MantidKernel/Logger.h"
 #include "MantidKernel/ThreadSafeLogStream.h"
-#include <Poco/Logger.h>
-#include <Poco/Message.h>
-#include <Poco/Mutex.h>
 
 #ifdef _MSC_VER
 // Disable a flood of warnings about inheriting from std streams
diff --git a/Code/Mantid/Framework/Kernel/src/MandatoryValidator.cpp b/Code/Mantid/Framework/Kernel/src/MandatoryValidator.cpp
index 3e137964db5053fd69568a70311d8440fb1d9f45..18a470461eff0e3ff104aeb0bd924286cbf80b66 100644
--- a/Code/Mantid/Framework/Kernel/src/MandatoryValidator.cpp
+++ b/Code/Mantid/Framework/Kernel/src/MandatoryValidator.cpp
@@ -4,7 +4,6 @@
 #include "MantidKernel/MandatoryValidator.h"
 #include "MantidKernel/EmptyValues.h"
 #include <cmath>
-#include <string>
 
 namespace Mantid {
 namespace Kernel {
diff --git a/Code/Mantid/Framework/Kernel/src/Material.cpp b/Code/Mantid/Framework/Kernel/src/Material.cpp
index a38008d3f089eff78c147eace8bbc51b5ce6b173..4cc28f0bd0391f1e5b09aa353a274349d2498bc2 100644
--- a/Code/Mantid/Framework/Kernel/src/Material.cpp
+++ b/Code/Mantid/Framework/Kernel/src/Material.cpp
@@ -7,9 +7,6 @@
 #include <boost/make_shared.hpp>
 #include <boost/regex.hpp>
 #include <boost/tokenizer.hpp>
-#include <sstream>
-#include <stdexcept>
-#include <utility>
 
 namespace Mantid {
 
diff --git a/Code/Mantid/Framework/Kernel/src/Math/Distributions/BoseEinsteinDistribution.cpp b/Code/Mantid/Framework/Kernel/src/Math/Distributions/BoseEinsteinDistribution.cpp
index 5a7121b9bdd7890f3d31a9ca8da2b927fdc1395c..d4b6dca905fc042c4282517140df155bcf0c97bc 100644
--- a/Code/Mantid/Framework/Kernel/src/Math/Distributions/BoseEinsteinDistribution.cpp
+++ b/Code/Mantid/Framework/Kernel/src/Math/Distributions/BoseEinsteinDistribution.cpp
@@ -3,7 +3,6 @@
 #include "MantidKernel/PhysicalConstants.h"
 
 #include <boost/lexical_cast.hpp>
-#include <iostream>
 
 namespace Mantid {
 namespace Kernel {
diff --git a/Code/Mantid/Framework/Kernel/src/Matrix.cpp b/Code/Mantid/Framework/Kernel/src/Matrix.cpp
index 425b07ab4f3d66e5371bf822f4ec65b6e729ff9c..e1bb4e3e777f63f58fbf74c2d8bbbce3480d52d7 100644
--- a/Code/Mantid/Framework/Kernel/src/Matrix.cpp
+++ b/Code/Mantid/Framework/Kernel/src/Matrix.cpp
@@ -3,8 +3,6 @@
 #include "MantidKernel/Exception.h"
 #include "MantidKernel/TimeSeriesProperty.h"
 #include "MantidKernel/MersenneTwister.h"
-#include <iomanip>
-#include <iostream>
 
 using Mantid::Kernel::TimeSeriesProperty;
 
diff --git a/Code/Mantid/Framework/Kernel/src/MultiFileNameParser.cpp b/Code/Mantid/Framework/Kernel/src/MultiFileNameParser.cpp
index a81476ec71363d27fc45b7bdfb58b13fdff0ea00..91665c120ff996823fdc350551668b2d5babc93c 100644
--- a/Code/Mantid/Framework/Kernel/src/MultiFileNameParser.cpp
+++ b/Code/Mantid/Framework/Kernel/src/MultiFileNameParser.cpp
@@ -5,27 +5,15 @@
 
 #include "MantidKernel/ConfigService.h"
 #include "MantidKernel/FacilityInfo.h"
-#include "MantidKernel/InstrumentInfo.h"
-#include "MantidKernel/Exception.h"
 
-#include <algorithm>
 #include <numeric>
-#include <iterator>
-#include <cassert>
-
-#include <ctype.h>
-#include <cctype>
 #include <sstream>
 
 #include <boost/regex.hpp>
-#include <boost/tokenizer.hpp>
 #include <boost/algorithm/string.hpp>
 #include <boost/lexical_cast.hpp>
-#include <boost/regex.hpp>
 #include <boost/bind.hpp>
 
-#include <Poco/Path.h>
-
 namespace Mantid {
 namespace Kernel {
 namespace MultiFileNameParsing {
diff --git a/Code/Mantid/Framework/Kernel/src/MultiFileValidator.cpp b/Code/Mantid/Framework/Kernel/src/MultiFileValidator.cpp
index b4900895e059d804cdc3aa8ae54cbc4c149f31d0..5c70ac32fc91815ef97eb5150bef9f3171dc2050 100644
--- a/Code/Mantid/Framework/Kernel/src/MultiFileValidator.cpp
+++ b/Code/Mantid/Framework/Kernel/src/MultiFileValidator.cpp
@@ -1,9 +1,4 @@
 #include "MantidKernel/MultiFileValidator.h"
-#include "MantidKernel/Logger.h"
-#include <Poco/File.h>
-#include <Poco/Path.h>
-#include <algorithm>
-#include <iostream>
 
 namespace Mantid {
 namespace Kernel {
diff --git a/Code/Mantid/Framework/Kernel/src/NeutronAtom.cpp b/Code/Mantid/Framework/Kernel/src/NeutronAtom.cpp
index 2a170d67308ab864c811b82c530d8fcc34cdb8a6..03874b20567f64528a9cde28317cfeeb01480b99 100644
--- a/Code/Mantid/Framework/Kernel/src/NeutronAtom.cpp
+++ b/Code/Mantid/Framework/Kernel/src/NeutronAtom.cpp
@@ -2,12 +2,11 @@
 // Includes
 //------------------------------------------------------------------------------
 #include "MantidKernel/NeutronAtom.h"
+#include "MantidKernel/PhysicalConstants.h"
 #include <algorithm>
 #include <iostream> // REMOVE
-#include <limits>
 #include <sstream>
 #include <stdexcept>
-#include "MantidKernel/PhysicalConstants.h"
 #include <boost/math/special_functions/fpclassify.hpp>
 
 namespace Mantid {
diff --git a/Code/Mantid/Framework/Kernel/src/NexusDescriptor.cpp b/Code/Mantid/Framework/Kernel/src/NexusDescriptor.cpp
index 7f020c9e1aa07e169a6656354ca26e9e5e13d5b1..39755715bc32b9ab8a774b25a8bd76494e12d44e 100644
--- a/Code/Mantid/Framework/Kernel/src/NexusDescriptor.cpp
+++ b/Code/Mantid/Framework/Kernel/src/NexusDescriptor.cpp
@@ -1,5 +1,4 @@
 #include "MantidKernel/NexusDescriptor.h"
-#include "MantidKernel/Exception.h"
 
 #include <nexus/NeXusFile.hpp>
 #include <nexus/NeXusException.hpp>
diff --git a/Code/Mantid/Framework/Kernel/src/ProgressText.cpp b/Code/Mantid/Framework/Kernel/src/ProgressText.cpp
index 950562e8792e4c6f2ecd791c328bc96a1eef419c..8e608e36f43f4df790b7c3a08514dcda51617d19 100644
--- a/Code/Mantid/Framework/Kernel/src/ProgressText.cpp
+++ b/Code/Mantid/Framework/Kernel/src/ProgressText.cpp
@@ -1,5 +1,4 @@
 #include "MantidKernel/ProgressText.h"
-#include "MantidKernel/System.h"
 #include <iostream>
 #include <fstream>
 #include <iomanip>
diff --git a/Code/Mantid/Framework/Kernel/src/Property.cpp b/Code/Mantid/Framework/Kernel/src/Property.cpp
index 2b39e233e21650e19ebd19e9fc29f9579bb6e726..38b7035fbc9af6f05fcb8cc071d9c1697ca6ac8d 100644
--- a/Code/Mantid/Framework/Kernel/src/Property.cpp
+++ b/Code/Mantid/Framework/Kernel/src/Property.cpp
@@ -6,9 +6,6 @@
 #include "MantidKernel/PropertyHistory.h"
 #include "MantidKernel/TimeSeriesProperty.h"
 
-#include <map>
-#include <sstream>
-
 namespace Mantid {
 namespace Kernel {
 
diff --git a/Code/Mantid/Framework/Kernel/src/PropertyHistory.cpp b/Code/Mantid/Framework/Kernel/src/PropertyHistory.cpp
index d566bcf490471d0db9466e33c7f0693e39feefa2..e96dd0efac744608bcc4105b5cc09482532e959d 100644
--- a/Code/Mantid/Framework/Kernel/src/PropertyHistory.cpp
+++ b/Code/Mantid/Framework/Kernel/src/PropertyHistory.cpp
@@ -4,7 +4,6 @@
 #include "MantidKernel/PropertyHistory.h"
 #include "MantidKernel/Property.h"
 
-#include <iostream>
 #include <sstream>
 
 namespace Mantid {
diff --git a/Code/Mantid/Framework/Kernel/src/PropertyManager.cpp b/Code/Mantid/Framework/Kernel/src/PropertyManager.cpp
index 747da588b905beddcf7287e1744cf46ae5586ed0..f09a67a3473b048fcdf6d2f1b1ac7757f37bcc79 100644
--- a/Code/Mantid/Framework/Kernel/src/PropertyManager.cpp
+++ b/Code/Mantid/Framework/Kernel/src/PropertyManager.cpp
@@ -2,13 +2,9 @@
 // Includes
 //----------------------------------------------------------------------
 #include "MantidKernel/PropertyManager.h"
-#include "MantidKernel/Exception.h"
 #include "MantidKernel/FilteredTimeSeriesProperty.h"
-#include "MantidKernel/TimeSeriesProperty.h"
 
-#include <boost/tokenizer.hpp>
 #include <boost/algorithm/string/trim.hpp>
-#include <algorithm>
 
 namespace Mantid {
 namespace Kernel {
diff --git a/Code/Mantid/Framework/Kernel/src/PropertyManagerOwner.cpp b/Code/Mantid/Framework/Kernel/src/PropertyManagerOwner.cpp
index 808014d694fe14172fc3dd856262de7ce8673e54..3bf120830249e62a3bc1a2e0ad10f78b6ab8fe92 100644
--- a/Code/Mantid/Framework/Kernel/src/PropertyManagerOwner.cpp
+++ b/Code/Mantid/Framework/Kernel/src/PropertyManagerOwner.cpp
@@ -3,8 +3,6 @@
 //----------------------------------------------------------------------
 #include "MantidKernel/PropertyManagerOwner.h"
 #include "MantidKernel/PropertyManager.h"
-#include "MantidKernel/Exception.h"
-#include <algorithm>
 
 namespace Mantid {
 namespace Kernel {
diff --git a/Code/Mantid/Framework/Kernel/src/PropertyWithValue.cpp b/Code/Mantid/Framework/Kernel/src/PropertyWithValue.cpp
index 038a26cc359abd12083be4e8546b336ab48bf427..52c93ddb02d604797157a446e20f8f673eadf87e 100644
--- a/Code/Mantid/Framework/Kernel/src/PropertyWithValue.cpp
+++ b/Code/Mantid/Framework/Kernel/src/PropertyWithValue.cpp
@@ -1,5 +1,4 @@
 #include "MantidKernel/PropertyWithValue.h"
-#include "MantidKernel/System.h"
 
 namespace Mantid {
 
diff --git a/Code/Mantid/Framework/Kernel/src/Quat.cpp b/Code/Mantid/Framework/Kernel/src/Quat.cpp
index 9d7ebc85a4f0425a9bc480775d1273ca390b906f..fe600ec5e6632e82dfd2818fcd1ac52503c14212 100644
--- a/Code/Mantid/Framework/Kernel/src/Quat.cpp
+++ b/Code/Mantid/Framework/Kernel/src/Quat.cpp
@@ -3,11 +3,6 @@
 #include "MantidKernel/Tolerance.h"
 #include "MantidKernel/V3D.h"
 
-#include <cmath>
-#include <stdexcept>
-#include <cstdlib>
-#include <float.h>
-
 #include <boost/algorithm/string.hpp>
 
 namespace Mantid {
diff --git a/Code/Mantid/Framework/Kernel/src/RegexStrings.cpp b/Code/Mantid/Framework/Kernel/src/RegexStrings.cpp
index 5329f0a3a53cd7d764160de3ba03a0adfaa6c639..a417ea4f1e4e57eb7bacbbd9d2d18b5f72e77be0 100644
--- a/Code/Mantid/Framework/Kernel/src/RegexStrings.cpp
+++ b/Code/Mantid/Framework/Kernel/src/RegexStrings.cpp
@@ -4,9 +4,7 @@
 #include <sstream>
 #include <vector>
 #include <list>
-#include <string>
 #include <algorithm>
-#include <functional>
 
 #include "MantidKernel/RegexStrings.h"
 #include "MantidKernel/Strings.h"
diff --git a/Code/Mantid/Framework/Kernel/src/RemoteJobManager.cpp b/Code/Mantid/Framework/Kernel/src/RemoteJobManager.cpp
index b819dddb788b667fc717fb2e574640ae6f5d3c82..6932db398a632855731e8b9c6d894886d351afa8 100644
--- a/Code/Mantid/Framework/Kernel/src/RemoteJobManager.cpp
+++ b/Code/Mantid/Framework/Kernel/src/RemoteJobManager.cpp
@@ -5,7 +5,6 @@
 #include "MantidKernel/Logger.h"
 #include "MantidKernel/RemoteJobManager.h"
 
-#include <Poco/AutoPtr.h>
 #include <Poco/DOM/Element.h>
 #include <Poco/DOM/NodeList.h>
 #include <Poco/DOM/Text.h>
@@ -13,9 +12,6 @@
 #include <Poco/Base64Encoder.h>
 #include <Poco/Net/HTTPSClientSession.h>
 #include <Poco/Net/HTTPRequest.h>
-#include <Poco/Net/HTTPResponse.h>
-#include <Poco/Net/HTTPCookie.h>
-#include <Poco/Net/NameValueCollection.h>
 #include <Poco/URI.h>
 
 namespace Mantid {
diff --git a/Code/Mantid/Framework/Kernel/src/Statistics.cpp b/Code/Mantid/Framework/Kernel/src/Statistics.cpp
index 6a021e757806d99a549b69131b44c37009466422..5cefc6fec5e06c3243e70f66c777face67f059da 100644
--- a/Code/Mantid/Framework/Kernel/src/Statistics.cpp
+++ b/Code/Mantid/Framework/Kernel/src/Statistics.cpp
@@ -2,15 +2,15 @@
 #include "MantidKernel/Statistics.h"
 
 #include <algorithm>
-#include <functional>
-#include <limits>
+#include <cfloat>
 #include <cmath>
-#include <numeric>
-#include <string>
-#include <stdexcept>
 #include <iostream>
+#include <limits>
+#include <numeric>
 #include <sstream>
-#include <cfloat>
+#include <stdexcept>
+#include <functional>
+
 
 namespace Mantid {
 namespace Kernel {
diff --git a/Code/Mantid/Framework/Kernel/src/Strings.cpp b/Code/Mantid/Framework/Kernel/src/Strings.cpp
index 9741f94a9e8a98f0e953ac0a4b2436f7d9cb23f1..c396f0e02c9b9179337274b07a24758d49aabed5 100644
--- a/Code/Mantid/Framework/Kernel/src/Strings.cpp
+++ b/Code/Mantid/Framework/Kernel/src/Strings.cpp
@@ -1,5 +1,4 @@
 #include "MantidKernel/Strings.h"
-#include "MantidKernel/Exception.h"
 #include "MantidKernel/UnitLabel.h"
 
 #include <Poco/StringTokenizer.h>
@@ -13,11 +12,6 @@
 #include <cmath>
 #include <fstream>
 #include <iomanip>
-#include <iostream>
-#include <list>
-#include <sstream>
-#include <cstring>
-#include <vector>
 
 using std::size_t;
 
diff --git a/Code/Mantid/Framework/Kernel/src/ThreadPool.cpp b/Code/Mantid/Framework/Kernel/src/ThreadPool.cpp
index 5232ef9af073212ba9f5e50dd4e90852cc447cfc..3e486fe8a5c11fcaa8983826a5e5d260b83bf541 100644
--- a/Code/Mantid/Framework/Kernel/src/ThreadPool.cpp
+++ b/Code/Mantid/Framework/Kernel/src/ThreadPool.cpp
@@ -2,16 +2,8 @@
 // Includes
 //----------------------------------------------------------------------
 #include "MantidKernel/ThreadPool.h"
-#include "MantidKernel/ThreadPoolRunnable.h"
-#include "MantidKernel/Task.h"
 #include "MantidKernel/ConfigService.h"
-#include <algorithm>
 #include <sstream>
-#include <cmath>
-#include <cfloat>
-#include <Poco/Mutex.h>
-#include <Poco/Runnable.h>
-#include <Poco/Thread.h>
 #include <Poco/Environment.h>
 
 namespace Mantid {
diff --git a/Code/Mantid/Framework/Kernel/src/ThreadPoolRunnable.cpp b/Code/Mantid/Framework/Kernel/src/ThreadPoolRunnable.cpp
index 23a2148228a402bdf9911392fe836d89a2549255..99550df3ad306e74146ec57af5ffd9be5a317e66 100644
--- a/Code/Mantid/Framework/Kernel/src/ThreadPoolRunnable.cpp
+++ b/Code/Mantid/Framework/Kernel/src/ThreadPoolRunnable.cpp
@@ -1,5 +1,4 @@
 #include "MantidKernel/ThreadPoolRunnable.h"
-#include "MantidKernel/System.h"
 
 namespace Mantid {
 namespace Kernel {
diff --git a/Code/Mantid/Framework/Kernel/src/ThreadSafeLogStream.cpp b/Code/Mantid/Framework/Kernel/src/ThreadSafeLogStream.cpp
index ce2e331946c9b53ef844a969eec7c48824eb33cf..e487fe13169a12b03237808fdea8a943162b9e4a 100644
--- a/Code/Mantid/Framework/Kernel/src/ThreadSafeLogStream.cpp
+++ b/Code/Mantid/Framework/Kernel/src/ThreadSafeLogStream.cpp
@@ -2,9 +2,7 @@
 // Includes
 //-----------------------------------------------
 #include "MantidKernel/ThreadSafeLogStream.h"
-#include "MantidKernel/MultiThreaded.h"
 #include <iostream>
-#include <Poco/Thread.h>
 
 using namespace Mantid::Kernel;
 
diff --git a/Code/Mantid/Framework/Kernel/src/TimeSeriesProperty.cpp b/Code/Mantid/Framework/Kernel/src/TimeSeriesProperty.cpp
index c6057895d5fdfca2f4ac6aaac52b913364003493..192a84f193bbec166f2811f90751685ae0583df0 100644
--- a/Code/Mantid/Framework/Kernel/src/TimeSeriesProperty.cpp
+++ b/Code/Mantid/Framework/Kernel/src/TimeSeriesProperty.cpp
@@ -1,13 +1,10 @@
 #include "MantidKernel/TimeSeriesProperty.h"
-#include "MantidKernel/DateAndTime.h"
 #include "MantidKernel/EmptyValues.h"
 #include "MantidKernel/Exception.h"
 #include "MantidKernel/Logger.h"
 #include "MantidKernel/TimeSplitter.h"
 
-#include <sstream>
 #if !(defined __APPLE__ && defined __INTEL_COMPILER)
-#include <algorithm>
 #else
 #include <boost/range/algorithm_ext/is_sorted.hpp>
 #endif
diff --git a/Code/Mantid/Framework/Kernel/src/TimeSplitter.cpp b/Code/Mantid/Framework/Kernel/src/TimeSplitter.cpp
index 20410bd89d7c840ea5bb03ccfe15a88057d63b8f..c4beaf928def18188517f3d7cffb21daa278eae4 100644
--- a/Code/Mantid/Framework/Kernel/src/TimeSplitter.cpp
+++ b/Code/Mantid/Framework/Kernel/src/TimeSplitter.cpp
@@ -1,7 +1,5 @@
 #include "MantidKernel/DateAndTime.h"
 #include "MantidKernel/TimeSplitter.h"
-#include <ctime>
-#include <ostream>
 
 namespace Mantid {
 namespace Kernel {
diff --git a/Code/Mantid/Framework/Kernel/src/Unit.cpp b/Code/Mantid/Framework/Kernel/src/Unit.cpp
index bdb02815fc78cc158d4a3b60277733f5b03aa79c..31275c764ad5e58756040ae6423877e08a3a441e 100644
--- a/Code/Mantid/Framework/Kernel/src/Unit.cpp
+++ b/Code/Mantid/Framework/Kernel/src/Unit.cpp
@@ -6,7 +6,6 @@
 #include "MantidKernel/PhysicalConstants.h"
 #include "MantidKernel/UnitFactory.h"
 #include "MantidKernel/UnitLabelTypes.h"
-#include <cmath>
 #include <cfloat>
 #include <limits>
 
diff --git a/Code/Mantid/Framework/Kernel/src/Utils.cpp b/Code/Mantid/Framework/Kernel/src/Utils.cpp
index 517f06e54ca4cf4aa7b32714ceaabc5169c02a6a..0f09dace07b65cddb00eff4e8fee57c1c69c5e45 100644
--- a/Code/Mantid/Framework/Kernel/src/Utils.cpp
+++ b/Code/Mantid/Framework/Kernel/src/Utils.cpp
@@ -1,6 +1,3 @@
-#include "MantidKernel/Utils.h"
-#include "MantidKernel/System.h"
-
 namespace Mantid {
 namespace Kernel {
 
diff --git a/Code/Mantid/Framework/Kernel/src/V2D.cpp b/Code/Mantid/Framework/Kernel/src/V2D.cpp
index 2dd7646fca89bbdb8132dafd25c4d74b97be1d4a..350daad046c5d46c910ff449e32dad24b961ff61 100644
--- a/Code/Mantid/Framework/Kernel/src/V2D.cpp
+++ b/Code/Mantid/Framework/Kernel/src/V2D.cpp
@@ -5,7 +5,6 @@
 #include "MantidKernel/V3D.h"
 #include "MantidKernel/Tolerance.h"
 #include "MantidKernel/Exception.h"
-#include <cmath>
 
 namespace Mantid {
 namespace Kernel {
diff --git a/Code/Mantid/Framework/Kernel/src/V3D.cpp b/Code/Mantid/Framework/Kernel/src/V3D.cpp
index 89d25b59fe3798045dcc528ec40873a218fb4be3..ea012553abcc24c57324a4a77b6ea78cb4999234 100644
--- a/Code/Mantid/Framework/Kernel/src/V3D.cpp
+++ b/Code/Mantid/Framework/Kernel/src/V3D.cpp
@@ -1,14 +1,11 @@
 #include <iostream>
 #include <cmath>
-#include <math.h>
 #include <float.h>
 #include <vector>
-#include <cstdlib>
 
 #include "MantidKernel/V3D.h"
 #include "MantidKernel/Tolerance.h"
 #include "MantidKernel/Exception.h"
-#include <sstream>
 #include "MantidKernel/Quat.h"
 #include <boost/math/common_factor.hpp>
 
diff --git a/Code/Mantid/Framework/Kernel/src/VMD.cpp b/Code/Mantid/Framework/Kernel/src/VMD.cpp
index 8b81996a72b4ed6d780821a14da084691b80ad71..432a4161c987ddfc0f8bef2ef7abe0de97441de6 100644
--- a/Code/Mantid/Framework/Kernel/src/VMD.cpp
+++ b/Code/Mantid/Framework/Kernel/src/VMD.cpp
@@ -1,6 +1,4 @@
 #include "MantidKernel/VMD.h"
-#include "MantidKernel/System.h"
-#include "MantidKernel/DllConfig.h"
 
 using namespace Mantid::Kernel;
 
diff --git a/Code/Mantid/Framework/Kernel/src/VectorHelper.cpp b/Code/Mantid/Framework/Kernel/src/VectorHelper.cpp
index cdc8f881d62d222fef1b055b689b0ef4f4ac7f04..cb08b58efed92266595a719e9424ac1109e6b17f 100644
--- a/Code/Mantid/Framework/Kernel/src/VectorHelper.cpp
+++ b/Code/Mantid/Framework/Kernel/src/VectorHelper.cpp
@@ -3,10 +3,8 @@
 
 #include "MantidKernel/VectorHelper.h"
 #include <algorithm>
-#include <vector>
-#include <numeric>
-#include <limits>
 #include <iostream>
+#include <numeric>
 #include <sstream>
 #include <boost/algorithm/string.hpp>
 
diff --git a/Code/Mantid/Framework/Kernel/src/VisibleWhenProperty.cpp b/Code/Mantid/Framework/Kernel/src/VisibleWhenProperty.cpp
index d5876696fb277f97dcebc09fb1c3360e1241e866..0853ff1c3c9567fc63c96c4b9d6002b22c6d8f14 100644
--- a/Code/Mantid/Framework/Kernel/src/VisibleWhenProperty.cpp
+++ b/Code/Mantid/Framework/Kernel/src/VisibleWhenProperty.cpp
@@ -1,6 +1,27 @@
 #include "MantidKernel/VisibleWhenProperty.h"
-#include "MantidKernel/System.h"
 
 namespace Mantid {
-namespace Kernel {} // namespace Mantid
+namespace Kernel {
+VisibleWhenProperty::VisibleWhenProperty(std::string otherPropName,
+                                         ePropertyCriterion when,
+                                         std::string value)
+    : EnabledWhenProperty(otherPropName, when, value) {}
+
+VisibleWhenProperty::~VisibleWhenProperty() {}
+
+bool VisibleWhenProperty::isEnabled(const IPropertyManager *) const {
+  return true;
+}
+
+bool VisibleWhenProperty::isVisible(const IPropertyManager *algo) const {
+  return this->fulfillsCriterion(algo);
+}
+
+IPropertySettings *VisibleWhenProperty::clone() {
+  VisibleWhenProperty *out = new VisibleWhenProperty(
+      this->m_otherPropName, this->m_when, this->m_value);
+  return out;
+}
+
+} // namespace Mantid
 } // namespace Kernel
diff --git a/Code/Mantid/Framework/Kernel/test/HermitePolynomialsTest.h b/Code/Mantid/Framework/Kernel/test/HermitePolynomialsTest.h
index d9cd19c1c526ef81c15859a60494f1280f20b244..ed10a2491af52cc72d63c6a6807bbacb994688f5 100644
--- a/Code/Mantid/Framework/Kernel/test/HermitePolynomialsTest.h
+++ b/Code/Mantid/Framework/Kernel/test/HermitePolynomialsTest.h
@@ -13,7 +13,9 @@ public:
   static HermitePolynomialsTest *createSuite() { return new HermitePolynomialsTest(); }
   static void destroySuite( HermitePolynomialsTest *suite ) { delete suite; }
 
+  // clang-format off
   void test_hermitePoly_With_SingleValue_Returns_Expected_Values_For_First_Few_Terms()
+  // clang-format on
   {
     using namespace Mantid::Kernel;
     static const unsigned int npoly(6);
@@ -28,7 +30,9 @@ public:
     }
   }
 
+  // clang-format off
   void test_hermitePoly_With_Array_Values_Returns_Expected_Values_For_First_Few_Terms()
+  // clang-format on
   {
     using namespace Mantid::Kernel;
 
diff --git a/Code/Mantid/Framework/LiveData/src/ISISHistoDataListener.cpp b/Code/Mantid/Framework/LiveData/src/ISISHistoDataListener.cpp
index 842e6ecf731e0b89facb352e5138ca3cc62ead28..6912032a4f9a5199b0a975ae8097eb3d50ae8cc5 100644
--- a/Code/Mantid/Framework/LiveData/src/ISISHistoDataListener.cpp
+++ b/Code/Mantid/Framework/LiveData/src/ISISHistoDataListener.cpp
@@ -17,7 +17,9 @@
 #ifdef GCC_VERSION
 // Avoid compiler warnings on gcc from unused static constants in
 // isisds_command.h
+// clang-format off
 GCC_DIAG_OFF(unused-variable)
+// clang-format on
 #endif
 #include "LoadDAE/idc.h"
 
diff --git a/Code/Mantid/Framework/LiveData/src/ISISLiveEventDataListener.cpp b/Code/Mantid/Framework/LiveData/src/ISISLiveEventDataListener.cpp
index 61c306734bb1841ed81ba282f1a382645450c27e..f47c708c69d2dfb9aaabc02a1799f0bb57e5694a 100644
--- a/Code/Mantid/Framework/LiveData/src/ISISLiveEventDataListener.cpp
+++ b/Code/Mantid/Framework/LiveData/src/ISISLiveEventDataListener.cpp
@@ -15,7 +15,9 @@
 #ifdef GCC_VERSION
 // Avoid compiler warnings on gcc from unused static constants in
 // isisds_command.h
+// clang-format off
 GCC_DIAG_OFF(unused-variable)
+// clang-format on
 #endif
 #include "LoadDAE/idc.h"
 
diff --git a/Code/Mantid/Framework/MDAlgorithms/CMakeLists.txt b/Code/Mantid/Framework/MDAlgorithms/CMakeLists.txt
index 7cb309bcc7dc1631064c12f8f60cd5fc2ef00f0f..9c78aae411c1c4e34f0e09a7b449fc208f485157 100644
--- a/Code/Mantid/Framework/MDAlgorithms/CMakeLists.txt
+++ b/Code/Mantid/Framework/MDAlgorithms/CMakeLists.txt
@@ -48,6 +48,7 @@ set ( SRC_FILES
 	src/Integrate3DEvents.cpp
 	src/IntegrateEllipsoids.cpp
 	src/IntegrateFlux.cpp
+	src/IntegrateMDHistoWorkspace.cpp
 	src/IntegratePeaksMD.cpp
 	src/IntegratePeaksMD2.cpp
 	src/InvalidParameter.cpp
@@ -101,6 +102,7 @@ set ( SRC_FILES
 	src/ReflectometryTransformQxQz.cpp
 	src/SaveIsawQvector.cpp
 	src/SaveMD.cpp
+	src/SaveMD2.cpp
 	src/SaveZODS.cpp
 	src/SetMDUsingMask.cpp
 	src/SliceMD.cpp
@@ -165,6 +167,7 @@ set ( INC_FILES
 	inc/MantidMDAlgorithms/Integrate3DEvents.h
 	inc/MantidMDAlgorithms/IntegrateEllipsoids.h
 	inc/MantidMDAlgorithms/IntegrateFlux.h
+	inc/MantidMDAlgorithms/IntegrateMDHistoWorkspace.h
 	inc/MantidMDAlgorithms/IntegratePeaksMD.h
 	inc/MantidMDAlgorithms/IntegratePeaksMD2.h
 	inc/MantidMDAlgorithms/InvalidParameter.h
@@ -218,6 +221,7 @@ set ( INC_FILES
 	inc/MantidMDAlgorithms/ReflectometryTransformQxQz.h
 	inc/MantidMDAlgorithms/SaveIsawQvector.h
 	inc/MantidMDAlgorithms/SaveMD.h
+	inc/MantidMDAlgorithms/SaveMD2.h
 	inc/MantidMDAlgorithms/SaveZODS.h
 	inc/MantidMDAlgorithms/SetMDUsingMask.h
 	inc/MantidMDAlgorithms/SliceMD.h
@@ -279,6 +283,7 @@ set ( TEST_FILES
 	Integrate3DEventsTest.h
 	IntegrateEllipsoidsTest.h
 	IntegrateFluxTest.h
+	IntegrateMDHistoWorkspaceTest.h
 	IntegratePeaksMD2Test.h
 	IntegratePeaksMDTest.h
 	InvalidParameterParserTest.h
@@ -317,6 +322,7 @@ set ( TEST_FILES
 	ResolutionConvolvedCrossSectionTest.h
 	SaveIsawQvectorTest.h
 	SaveMDTest.h
+	SaveMD2Test.h
 	SaveZODSTest.h
 	SetMDUsingMaskTest.h
 	SimulateResolutionConvolvedModelTest.h
diff --git a/Code/Mantid/Framework/MDAlgorithms/inc/MantidMDAlgorithms/ConvertToMD.h b/Code/Mantid/Framework/MDAlgorithms/inc/MantidMDAlgorithms/ConvertToMD.h
index 9fe01fa089e7abcec0fc910483c8b374ce9e812c..3112f5406d7182fd0bfa8dad374636663a950f0b 100644
--- a/Code/Mantid/Framework/MDAlgorithms/inc/MantidMDAlgorithms/ConvertToMD.h
+++ b/Code/Mantid/Framework/MDAlgorithms/inc/MantidMDAlgorithms/ConvertToMD.h
@@ -87,7 +87,7 @@ protected: // for testing, otherwise private:
   bool doWeNeedNewTargetWorkspace(API::IMDEventWorkspace_sptr spws);
   /**Create new MD workspace using existing parameters for algorithm */
   API::IMDEventWorkspace_sptr
-  createNewMDWorkspace(const MDAlgorithms::MDWSDescription &NewMDWSDescription);
+  createNewMDWorkspace(const MDAlgorithms::MDWSDescription &targWSDescr);
 
   bool buildTargetWSDescription(API::IMDEventWorkspace_sptr spws,
                                 const std::string &Q_mod_req,
diff --git a/Code/Mantid/Framework/MDAlgorithms/inc/MantidMDAlgorithms/IntegrateEllipsoids.h b/Code/Mantid/Framework/MDAlgorithms/inc/MantidMDAlgorithms/IntegrateEllipsoids.h
index d3fadb25388193dc3de26fdfc58136a6561b0cb6..07fede619029299275132b776484ee14e07f2050 100644
--- a/Code/Mantid/Framework/MDAlgorithms/inc/MantidMDAlgorithms/IntegrateEllipsoids.h
+++ b/Code/Mantid/Framework/MDAlgorithms/inc/MantidMDAlgorithms/IntegrateEllipsoids.h
@@ -4,6 +4,11 @@
 #include "MantidAPI/Algorithm.h"
 #include "MantidAPI/MatrixWorkspace.h"
 #include "MantidMDAlgorithms/MDWSDescription.h"
+#include "MantidMDAlgorithms/Integrate3DEvents.h"
+#include "MantidMDAlgorithms/UnitsConversionHelper.h"
+#include "MantidMDAlgorithms/MDTransfInterface.h"
+#include "MantidDataObjects/Workspace2D.h"
+#include "MantidDataObjects/EventWorkspace.h"
 
 namespace Mantid {
 namespace MDAlgorithms {
@@ -12,7 +17,6 @@ class DLLExport IntegrateEllipsoids : public API::Algorithm {
 public:
   IntegrateEllipsoids();
   virtual ~IntegrateEllipsoids();
-
   virtual const std::string name() const;
   /// Summary of algorithms purpose
   virtual const std::string summary() const {
@@ -26,6 +30,12 @@ public:
 private:
   void init();
   void exec();
+  void qListFromEventWS(Integrate3DEvents &integrator, API::Progress &prog,
+                        DataObjects::EventWorkspace_sptr &wksp,
+                        Kernel::DblMatrix const &UBinv, bool hkl_integ);
+  void qListFromHistoWS(Integrate3DEvents &integrator, API::Progress &prog,
+                        DataObjects::Workspace2D_sptr &wksp,
+                        Kernel::DblMatrix const &UBinv, bool hkl_integ);
 
   MDWSDescription m_targWSDescr;
 
diff --git a/Code/Mantid/Framework/MDAlgorithms/inc/MantidMDAlgorithms/IntegrateMDHistoWorkspace.h b/Code/Mantid/Framework/MDAlgorithms/inc/MantidMDAlgorithms/IntegrateMDHistoWorkspace.h
new file mode 100644
index 0000000000000000000000000000000000000000..b967666e189548e90b21f2f5cc621335c807b2e1
--- /dev/null
+++ b/Code/Mantid/Framework/MDAlgorithms/inc/MantidMDAlgorithms/IntegrateMDHistoWorkspace.h
@@ -0,0 +1,60 @@
+#ifndef MANTID_MDALGORITHMS_INTEGRATEMDHISTOWORKSPACE_H_
+#define MANTID_MDALGORITHMS_INTEGRATEMDHISTOWORKSPACE_H_
+
+#include "MantidKernel/System.h"
+#include "MantidAPI/Algorithm.h"
+
+#include <vector>
+
+namespace Mantid
+{
+namespace MDAlgorithms
+{
+
+  /** IntegrateMDHistoWorkspace : Algorithm to perform axis aligned integration of an MDHistoWorkspace.
+
+    Copyright &copy; 2015 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+
+    This file is part of Mantid.
+
+    Mantid is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 3 of the License, or
+    (at your option) any later version.
+
+    Mantid 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 General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+    File change history is stored at: <https://github.com/mantidproject/mantid>
+    Code Documentation is available at: <http://doxygen.mantidproject.org>
+  */
+  class DLLExport IntegrateMDHistoWorkspace  : public API::Algorithm
+  {
+  public:
+    IntegrateMDHistoWorkspace();
+    virtual ~IntegrateMDHistoWorkspace();
+    
+    virtual const std::string name() const;
+    virtual int version() const;
+    virtual const std::string category() const;
+    virtual const std::string summary() const;
+    virtual std::map<std::string, std::string> validateInputs();
+
+  private:
+
+    void init();
+    void exec();
+
+
+  };
+
+
+} // namespace MDAlgorithms
+} // namespace Mantid
+
+#endif  /* MANTID_MDALGORITHMS_INTEGRATEMDHISTOWORKSPACE_H_ */
diff --git a/Code/Mantid/Framework/MDAlgorithms/inc/MantidMDAlgorithms/LoadMD.h b/Code/Mantid/Framework/MDAlgorithms/inc/MantidMDAlgorithms/LoadMD.h
index 8eb3131709cdcc06b99190025a7616ee1250b044..7287b626028448cb94d99c811cb2059fbf98e98f 100644
--- a/Code/Mantid/Framework/MDAlgorithms/inc/MantidMDAlgorithms/LoadMD.h
+++ b/Code/Mantid/Framework/MDAlgorithms/inc/MantidMDAlgorithms/LoadMD.h
@@ -75,6 +75,8 @@ private:
 
   void loadDimensions();
 
+  void loadDimensions2();
+
   void loadCoordinateSystem();
 
   /// Load all the affine matricies
@@ -83,7 +85,9 @@ private:
   API::CoordTransform *loadAffineMatrix(std::string entry_name);
 
   /// Open file handle
+  // clang-format off
   boost::scoped_ptr< ::NeXus::File> m_file;
+  // clang-format on
 
   /// Name of that file
   std::string m_filename;
@@ -97,6 +101,9 @@ private:
   Kernel::SpecialCoordinateSystem m_coordSystem;
   /// load only the box structure with empty boxes but do not tload boxes events
   bool m_BoxStructureAndMethadata;
+
+  /// Version of SaveMD used to save the file
+  int SaveMDVersion ;
 };
 
 } // namespace DataObjects
diff --git a/Code/Mantid/Framework/MDAlgorithms/inc/MantidMDAlgorithms/SaveMD2.h b/Code/Mantid/Framework/MDAlgorithms/inc/MantidMDAlgorithms/SaveMD2.h
new file mode 100644
index 0000000000000000000000000000000000000000..6aa31d50bb24c1378f0d20e43a4dc7dc152db67e
--- /dev/null
+++ b/Code/Mantid/Framework/MDAlgorithms/inc/MantidMDAlgorithms/SaveMD2.h
@@ -0,0 +1,70 @@
+#ifndef MANTID_MDALGORITHMS_SAVEMD2_H_
+#define MANTID_MDALGORITHMS_SAVEMD2_H_
+
+#include "MantidKernel/System.h"
+#include "MantidAPI/Algorithm.h"
+#include "MantidDataObjects/MDEventWorkspace.h"
+
+namespace Mantid {
+
+namespace MDAlgorithms {
+
+/** Save a MDEventWorkspace to a .nxs file.
+
+  Copyright &copy; 2015 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid 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 General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport SaveMD2 : public API::Algorithm {
+public:
+  SaveMD2();
+  ~SaveMD2();
+
+  /// Algorithm's name for identification
+  virtual const std::string name() const { return "SaveMD"; };
+  /// Summary of algorithms purpose
+  virtual const std::string summary() const {
+    return "Save a MDEventWorkspace or MDHistoWorkspace to a .nxs file.";
+  }
+
+  /// Algorithm's version for identification
+  virtual int version() const { return 2; };
+  /// Algorithm's category for identification
+  virtual const std::string category() const { return "MDAlgorithms"; }
+
+private:
+  /// Initialise the properties
+  void init();
+  /// Run the algorithm
+  void exec();
+
+  /// Save the MDHistoWorkspace.
+  void doSaveHisto(Mantid::DataObjects::MDHistoWorkspace_sptr ws);
+
+  /// Save a generic matrix
+  template <typename T>
+  void saveMatrix(::NeXus::File *const file, std::string name,
+                  Kernel::Matrix<T> &m, ::NeXus::NXnumtype type,
+                  std::string tag = "");
+};
+
+} // namespace DataObjects
+} // namespace Mantid
+
+#endif /* MANTID_MDALGORITHMS_SAVEMD2_H_ */
diff --git a/Code/Mantid/Framework/MDAlgorithms/inc/MantidMDAlgorithms/SmoothMD.h b/Code/Mantid/Framework/MDAlgorithms/inc/MantidMDAlgorithms/SmoothMD.h
index 61c447729a39e417ab6799c08af66a17f952a1cf..d404c890fe1a687392e274e4270cb652c5b42808 100644
--- a/Code/Mantid/Framework/MDAlgorithms/inc/MantidMDAlgorithms/SmoothMD.h
+++ b/Code/Mantid/Framework/MDAlgorithms/inc/MantidMDAlgorithms/SmoothMD.h
@@ -50,7 +50,7 @@ namespace MDAlgorithms
     std::map<std::string, std::string> validateInputs();
 
     boost::shared_ptr<Mantid::API::IMDHistoWorkspace> hatSmooth(boost::shared_ptr<const Mantid::API::IMDHistoWorkspace> toSmooth,
-                                     const std::vector<int> &widthVector, boost::optional<boost::shared_ptr<const Mantid::API::IMDHistoWorkspace> > weighting);
+                                     const std::vector<int> &widthVector, boost::optional<boost::shared_ptr<const Mantid::API::IMDHistoWorkspace> > weightingWS);
 
   private:
 
diff --git a/Code/Mantid/Framework/MDAlgorithms/src/CreateMDHistoWorkspace.cpp b/Code/Mantid/Framework/MDAlgorithms/src/CreateMDHistoWorkspace.cpp
index a312ee39c8481fe6dc9ac72f824f9c0d99b0eab5..0dfe0a426e7f783f17ab64184f9b034e1806a78c 100644
--- a/Code/Mantid/Framework/MDAlgorithms/src/CreateMDHistoWorkspace.cpp
+++ b/Code/Mantid/Framework/MDAlgorithms/src/CreateMDHistoWorkspace.cpp
@@ -49,12 +49,13 @@ const std::string CreateMDHistoWorkspace::category() const {
  */
 void CreateMDHistoWorkspace::init() {
   declareProperty(new ArrayProperty<double>("SignalInput"),
-                  "A comma separated list of all the signal values required "
-                  "for the workspace");
+                  "Signal array for n-dimensional workspace");
 
   declareProperty(new ArrayProperty<double>("ErrorInput"),
-                  "A comma separated list of all the error values required for "
-                  "the workspace");
+                  "Error array for n-dimensional workspace");
+
+  declareProperty(new ArrayProperty<double>("NumberOfEvents", std::vector<double>(0)),
+                  "Number of pixels array for n-dimensional workspace. Optional, defaults to 1 per bin.");
 
   // Declare all the generic properties required.
   this->initGenericImportProps();
@@ -65,11 +66,13 @@ void CreateMDHistoWorkspace::init() {
  */
 void CreateMDHistoWorkspace::exec() {
   MDHistoWorkspace_sptr ws = this->createEmptyOutputWorkspace();
-  double *signals = ws->getSignalArray();
-  double *errors = ws->getErrorSquaredArray();
+  Mantid::signal_t *signals = ws->getSignalArray();
+  Mantid::signal_t *errors = ws->getErrorSquaredArray();
+  Mantid::signal_t *nEvents = ws->getNumEventsArray();
 
   std::vector<double> signalValues = getProperty("SignalInput");
   std::vector<double> errorValues = getProperty("ErrorInput");
+  std::vector<double> numberOfEvents = getProperty("NumberOfEvents");
 
   size_t binProduct = this->getBinProduct();
   std::stringstream stream;
@@ -82,6 +85,15 @@ void CreateMDHistoWorkspace::exec() {
     throw std::invalid_argument("Expected size of the ErrorInput is: " +
                                 stream.str());
   }
+  if (!numberOfEvents.empty() && binProduct != numberOfEvents.size()) {
+    throw std::invalid_argument("Expected size of the NumberOfEvents is: " +
+                                stream.str() + ". Leave empty to auto fill with 1.0");
+  }
+
+  // Auto fill number of events.
+  if(numberOfEvents.empty()) {
+    numberOfEvents = std::vector<double>(binProduct, 1.0);
+  }
 
   // Copy from property
   std::copy(signalValues.begin(), signalValues.end(), signals);
@@ -93,6 +105,10 @@ void CreateMDHistoWorkspace::exec() {
   std::copy(errorValues.begin(), errorValues.end(), errors);
   // Clean up
   errorValues.swap(empty);
+  // Copy from property
+  std::copy(numberOfEvents.begin(), numberOfEvents.end(), nEvents);
+  // Clean up
+  numberOfEvents.swap(empty);
 
   setProperty("OutputWorkspace", ws);
 }
diff --git a/Code/Mantid/Framework/MDAlgorithms/src/CutMD.cpp b/Code/Mantid/Framework/MDAlgorithms/src/CutMD.cpp
index 3deac2121dfc386f33aea1c3bac8969deeb9d612..85cbdcd35b5dfc35efcb00e49987fd9cefa22d55 100644
--- a/Code/Mantid/Framework/MDAlgorithms/src/CutMD.cpp
+++ b/Code/Mantid/Framework/MDAlgorithms/src/CutMD.cpp
@@ -1,5 +1,6 @@
 #include "MantidMDAlgorithms/CutMD.h"
 #include "MantidAPI/IMDEventWorkspace.h"
+#include "MantidAPI/IMDHistoWorkspace.h"
 #include "MantidAPI/Projection.h"
 #include "MantidGeometry/Crystal/OrientedLattice.h"
 #include "MantidKernel/ArrayProperty.h"
@@ -198,8 +199,8 @@ CutMD::~CutMD() {}
 //----------------------------------------------------------------------------------------------
 
 void CutMD::init() {
-  declareProperty(new WorkspaceProperty<IMDEventWorkspace>("InputWorkspace", "",
-                                                           Direction::Input),
+  declareProperty(new WorkspaceProperty<IMDWorkspace>("InputWorkspace", "",
+                                                      Direction::Input),
                   "MDWorkspace to slice");
 
   declareProperty(
@@ -220,8 +221,6 @@ void CutMD::init() {
                                   "as output. True to create an "
                                   "MDHistoWorkspace as output. This is DND "
                                   "only in Horace terminology.");
-  declareProperty("CheckAxes", true,
-                  "Check that the axis look to be correct, and abort if not.");
 }
 
 void CutMD::exec() {
@@ -229,7 +228,7 @@ void CutMD::exec() {
                 "behaviour may change without warning.");
 
   // Collect input properties
-  const IMDEventWorkspace_sptr inWS = getProperty("InputWorkspace");
+  const IMDWorkspace_sptr inWS = getProperty("InputWorkspace");
   const size_t numDims = inWS->getNumDims();
   const ITableWorkspace_sptr projectionWS = getProperty("Projection");
   std::vector<std::vector<double>> pbins(5);
@@ -238,150 +237,174 @@ void CutMD::exec() {
   pbins[2] = getProperty("P3Bin");
   pbins[3] = getProperty("P4Bin");
   pbins[4] = getProperty("P5Bin");
-  const bool noPix = getProperty("NoPix");
 
-  // Check Projection format
-  Projection projection;
-  if (projectionWS)
-    projection = Projection(*projectionWS);
-
-  // Check PBin properties
-  for (size_t i = 0; i < 5; ++i) {
-    if (i < numDims && pbins[i].empty())
-      throw std::runtime_error(
-          "P" + boost::lexical_cast<std::string>(i + 1) +
-          "Bin must be set when processing a workspace with " +
-          boost::lexical_cast<std::string>(numDims) + " dimensions.");
-    if (i >= numDims && !pbins[i].empty())
-      throw std::runtime_error(
-          "P" + boost::lexical_cast<std::string>(i + 1) +
-          "Bin must NOT be set when processing a workspace with " +
-          boost::lexical_cast<std::string>(numDims) + " dimensions.");
-  }
-
-  // Get extents in projection
-  std::vector<MinMax> extentLimits;
-  extentLimits.push_back(getDimensionExtents(inWS, 0));
-  extentLimits.push_back(getDimensionExtents(inWS, 1));
-  extentLimits.push_back(getDimensionExtents(inWS, 2));
-
-  // Scale projection
-  DblMatrix projectionMatrix(3, 3);
-  projectionMatrix.setRow(0, projection.U());
-  projectionMatrix.setRow(1, projection.V());
-  projectionMatrix.setRow(2, projection.W());
-
-  std::vector<std::string> targetUnits(3);
-  for (size_t i = 0; i < 3; ++i)
-    targetUnits[i] = projection.getUnit(i) == RLU ? "r" : "a";
-  std::vector<std::string> originUnits(3, "r"); // TODO. This is a hack!
-
-  DblMatrix scaledProjectionMatrix =
-      scaleProjection(projectionMatrix, originUnits, targetUnits, inWS);
-
-  // Calculate extents for the first 3 dimensions
-  std::vector<MinMax> scaledExtents =
-      calculateExtents(scaledProjectionMatrix, extentLimits);
-  auto stepPair = calculateSteps(scaledExtents, pbins);
-  std::vector<MinMax> steppedExtents = stepPair.first;
-  std::vector<int> steppedBins = stepPair.second;
-
-  // Calculate extents for additional dimensions
-  for (size_t i = 3; i < numDims; ++i) {
-    const size_t nArgs = pbins[i].size();
-    const MinMax extentLimit = getDimensionExtents(inWS, i);
-    const double dimRange = extentLimit.second - extentLimit.first;
-
-    if (nArgs == 1) {
-      steppedExtents.push_back(extentLimit);
-      steppedBins.push_back(static_cast<int>(dimRange / pbins[i][0]));
-    } else if (nArgs == 2) {
-      steppedExtents.push_back(std::make_pair(pbins[i][0], pbins[i][1]));
-      steppedBins.push_back(1);
-    } else if (nArgs == 3) {
-      const double dimRange = pbins[i][2] - pbins[i][0];
-      const double stepSize = pbins[i][1] < dimRange ? pbins[i][1] : dimRange;
-      steppedExtents.push_back(std::make_pair(pbins[i][0], pbins[i][2]));
-      steppedBins.push_back(static_cast<int>(dimRange / stepSize));
+  Workspace_sptr sliceWS; // output worskpace
+
+  // Histogram workspaces can be sliced axis-aligned only.
+  if (auto histInWS = boost::dynamic_pointer_cast<IMDHistoWorkspace>(inWS)) {
+
+    g_log.information("Integrating using binning parameters only.");
+    auto integrateAlg =
+        this->createChildAlgorithm("IntegrateMDHistoWorkspace", 0, 1);
+    integrateAlg->setProperty("InputWorkspace", histInWS);
+    integrateAlg->setProperty("P1Bin", pbins[0]);
+    integrateAlg->setProperty("P2Bin", pbins[1]);
+    integrateAlg->setProperty("P3Bin", pbins[2]);
+    integrateAlg->setProperty("P4Bin", pbins[3]);
+    integrateAlg->setProperty("P5Bin", pbins[4]);
+    integrateAlg->execute();
+    IMDHistoWorkspace_sptr temp = integrateAlg->getProperty("OutputWorkspace");
+    sliceWS = temp;
+  } else { // We are processing an MDEventWorkspace
+
+    auto eventInWS = boost::dynamic_pointer_cast<IMDEventWorkspace>(inWS);
+    const bool noPix = getProperty("NoPix");
+
+    // Check Projection format
+    Projection projection;
+    if (projectionWS)
+      projection = Projection(*projectionWS);
+
+    // Check PBin properties
+    for (size_t i = 0; i < 5; ++i) {
+      if (i < numDims && pbins[i].empty())
+        throw std::runtime_error(
+            "P" + boost::lexical_cast<std::string>(i + 1) +
+            "Bin must be set when processing a workspace with " +
+            boost::lexical_cast<std::string>(numDims) + " dimensions.");
+      if (i >= numDims && !pbins[i].empty())
+        throw std::runtime_error(
+            "P" + boost::lexical_cast<std::string>(i + 1) +
+            "Bin must NOT be set when processing a workspace with " +
+            boost::lexical_cast<std::string>(numDims) + " dimensions.");
     }
 
-    // and double targetUnits' length by appending itself to itself
-    size_t preSize = targetUnits.size();
-    targetUnits.resize(preSize * 2);
-    for (size_t i = 0; i < preSize; ++i)
-      targetUnits[preSize + i] = targetUnits[i];
-  }
+    // Get extents in projection
+    std::vector<MinMax> extentLimits;
+    extentLimits.push_back(getDimensionExtents(eventInWS, 0));
+    extentLimits.push_back(getDimensionExtents(eventInWS, 1));
+    extentLimits.push_back(getDimensionExtents(eventInWS, 2));
+
+    // Scale projection
+    DblMatrix projectionMatrix(3, 3);
+    projectionMatrix.setRow(0, projection.U());
+    projectionMatrix.setRow(1, projection.V());
+    projectionMatrix.setRow(2, projection.W());
+
+    std::vector<std::string> targetUnits(3);
+    for (size_t i = 0; i < 3; ++i)
+      targetUnits[i] = projection.getUnit(i) == RLU ? "r" : "a";
+    std::vector<std::string> originUnits(3, "r"); // TODO. This is a hack!
+
+    DblMatrix scaledProjectionMatrix =
+        scaleProjection(projectionMatrix, originUnits, targetUnits, eventInWS);
+
+    // Calculate extents for the first 3 dimensions
+    std::vector<MinMax> scaledExtents =
+        calculateExtents(scaledProjectionMatrix, extentLimits);
+    auto stepPair = calculateSteps(scaledExtents, pbins);
+    std::vector<MinMax> steppedExtents = stepPair.first;
+    std::vector<int> steppedBins = stepPair.second;
+
+    // Calculate extents for additional dimensions
+    for (size_t i = 3; i < numDims; ++i) {
+      const size_t nArgs = pbins[i].size();
+      const MinMax extentLimit = getDimensionExtents(eventInWS, i);
+      const double dimRange = extentLimit.second - extentLimit.first;
+
+      if (nArgs == 1) {
+        steppedExtents.push_back(extentLimit);
+        steppedBins.push_back(static_cast<int>(dimRange / pbins[i][0]));
+      } else if (nArgs == 2) {
+        steppedExtents.push_back(std::make_pair(pbins[i][0], pbins[i][1]));
+        steppedBins.push_back(1);
+      } else if (nArgs == 3) {
+        const double dimRange = pbins[i][2] - pbins[i][0];
+        const double stepSize = pbins[i][1] < dimRange ? pbins[i][1] : dimRange;
+        steppedExtents.push_back(std::make_pair(pbins[i][0], pbins[i][2]));
+        steppedBins.push_back(static_cast<int>(dimRange / stepSize));
+      }
 
-  // Make labels
-  std::vector<std::string> labels = labelProjection(projectionMatrix);
+      // and double targetUnits' length by appending itself to itself
+      size_t preSize = targetUnits.size();
+      targetUnits.resize(preSize * 2);
+      for (size_t i = 0; i < preSize; ++i)
+        targetUnits[preSize + i] = targetUnits[i];
+    }
 
-  // Either run RebinMD or SliceMD
-  const std::string cutAlgName = noPix ? "BinMD" : "SliceMD";
-  IAlgorithm_sptr cutAlg = createChildAlgorithm(cutAlgName, 0.0, 1.0);
-  cutAlg->initialize();
-  cutAlg->setProperty("InputWorkspace", inWS);
-  cutAlg->setProperty("OutputWorkspace", "sliced");
-  cutAlg->setProperty("NormalizeBasisVectors", false);
-  cutAlg->setProperty("AxisAligned", false);
+    // Make labels
+    std::vector<std::string> labels = labelProjection(projectionMatrix);
+
+    // Either run RebinMD or SliceMD
+    const std::string cutAlgName = noPix ? "BinMD" : "SliceMD";
+    IAlgorithm_sptr cutAlg = createChildAlgorithm(cutAlgName, 0.0, 1.0);
+    cutAlg->initialize();
+    cutAlg->setProperty("InputWorkspace", inWS);
+    cutAlg->setProperty("OutputWorkspace", "sliced");
+    cutAlg->setProperty("NormalizeBasisVectors", false);
+    cutAlg->setProperty("AxisAligned", false);
+
+    for (size_t i = 0; i < numDims; ++i) {
+      std::string label;
+      std::string unit;
+      std::string vecStr;
+
+      if (i < 3) {
+        // Slicing algorithms accept name as [x, y, z]
+        label = labels[i];
+        unit = targetUnits[i];
+
+        std::vector<std::string> vec(numDims, "0");
+        for (size_t j = 0; j < 3; ++j)
+          vec[j] = boost::lexical_cast<std::string>(projectionMatrix[i][j]);
+        vecStr = boost::algorithm::join(vec, ", ");
+      } else {
+        // Always orthogonal
+        auto dim = inWS->getDimension(i);
+        label = dim->getName();
+        unit = dim->getUnits();
+        std::vector<std::string> vec(numDims, "0");
+        vec[i] = "1";
+        vecStr = boost::algorithm::join(vec, ", ");
+      }
 
-  for (size_t i = 0; i < numDims; ++i) {
-    std::string label;
-    std::string unit;
-    std::string vecStr;
-
-    if (i < 3) {
-      // Slicing algorithms accept name as [x, y, z]
-      label = labels[i];
-      unit = targetUnits[i];
-
-      std::vector<std::string> vec(numDims, "0");
-      for (size_t j = 0; j < 3; ++j)
-        vec[j] = boost::lexical_cast<std::string>(projectionMatrix[i][j]);
-      vecStr = boost::algorithm::join(vec, ", ");
-    } else {
-      // Always orthogonal
-      auto dim = inWS->getDimension(i);
-      label = dim->getName();
-      unit = dim->getUnits();
-      std::vector<std::string> vec(numDims, "0");
-      vec[i] = "1";
-      vecStr = boost::algorithm::join(vec, ", ");
+      const std::string value = label + ", " + unit + ", " + vecStr;
+      cutAlg->setProperty("BasisVector" + boost::lexical_cast<std::string>(i),
+                          value);
     }
 
-    const std::string value = label + ", " + unit + ", " + vecStr;
-    cutAlg->setProperty("BasisVector" + boost::lexical_cast<std::string>(i),
-                        value);
-  }
+    // Translate extents into a single vector
+    std::vector<double> outExtents(steppedExtents.size() * 2);
+    for (size_t i = 0; i < steppedExtents.size(); ++i) {
+      outExtents[2 * i] = steppedExtents[i].first;
+      outExtents[2 * i + 1] = steppedExtents[i].second;
+    }
 
-  // Translate extents into a single vector
-  std::vector<double> outExtents(steppedExtents.size() * 2);
-  for (size_t i = 0; i < steppedExtents.size(); ++i) {
-    outExtents[2 * i] = steppedExtents[i].first;
-    outExtents[2 * i + 1] = steppedExtents[i].second;
-  }
+    cutAlg->setProperty("OutputExtents", outExtents);
+    cutAlg->setProperty("OutputBins", steppedBins);
 
-  cutAlg->setProperty("OutputExtents", outExtents);
-  cutAlg->setProperty("OutputBins", steppedBins);
+    cutAlg->execute();
+    sliceWS = cutAlg->getProperty("OutputWorkspace");
 
-  cutAlg->execute();
-  Workspace_sptr sliceWS = cutAlg->getProperty("OutputWorkspace");
-  MultipleExperimentInfos_sptr sliceInfo =
-      boost::dynamic_pointer_cast<MultipleExperimentInfos>(sliceWS);
+    MultipleExperimentInfos_sptr sliceInfo =
+        boost::dynamic_pointer_cast<MultipleExperimentInfos>(sliceWS);
 
-  if (!sliceInfo)
-    throw std::runtime_error(
-        "Could not extract experiment info from child's OutputWorkspace");
+    if (!sliceInfo)
+      throw std::runtime_error(
+          "Could not extract experiment info from child's OutputWorkspace");
 
-  // Attach projection matrix to output
-  if (sliceInfo->getNumExperimentInfo() > 0) {
-    ExperimentInfo_sptr info = sliceInfo->getExperimentInfo(0);
-    info->mutableRun().addProperty("W_MATRIX", projectionMatrix.getVector(),
-                                   true);
+    // Attach projection matrix to output
+    if (sliceInfo->getNumExperimentInfo() > 0) {
+      ExperimentInfo_sptr info = sliceInfo->getExperimentInfo(0);
+      info->mutableRun().addProperty("W_MATRIX", projectionMatrix.getVector(),
+                                     true);
+    }
   }
 
   auto geometry = boost::dynamic_pointer_cast<Mantid::API::MDGeometry>(sliceWS);
 
-  /* Original workspace and transformation information does not make sense for self-contained Horace-style
+  /* Original workspace and transformation information does not make sense for
+   * self-contained Horace-style
    * cuts, so clear it out. */
   geometry->clearTransforms();
   geometry->clearOriginalWorkspaces();
diff --git a/Code/Mantid/Framework/MDAlgorithms/src/Integrate3DEvents.cpp b/Code/Mantid/Framework/MDAlgorithms/src/Integrate3DEvents.cpp
index ee8359d1978562b25a5a12df796f3a9146e65a62..57c34fdac6b80868699f25be27df507b07169b18 100644
--- a/Code/Mantid/Framework/MDAlgorithms/src/Integrate3DEvents.cpp
+++ b/Code/Mantid/Framework/MDAlgorithms/src/Integrate3DEvents.cpp
@@ -123,11 +123,6 @@ Mantid::Geometry::PeakShape_const_sptr Integrate3DEvents::ellipseIntegrateEvents
   }
 
   std::vector<std::pair<double, V3D> > &some_events = event_lists[hkl_key];
-  for (size_t it = 0; it != some_events.size(); ++it) {
-    hkl_key = getHklKey2(some_events[it].second);
-    if (hkl_key != 0) // only save if hkl != (0,0,0)
-      peak_qs[hkl_key] = some_events[it].second;
-  }
 
   if (some_events.size() < 3) // if there are not enough events to
   {                           // find covariance matrix, return
diff --git a/Code/Mantid/Framework/MDAlgorithms/src/IntegrateEllipsoids.cpp b/Code/Mantid/Framework/MDAlgorithms/src/IntegrateEllipsoids.cpp
index e71dfda095e136b1c5949b69db3cc69aaa04d7d6..dbedf58b21ee342ef937987df6a760c665cb68ae 100644
--- a/Code/Mantid/Framework/MDAlgorithms/src/IntegrateEllipsoids.cpp
+++ b/Code/Mantid/Framework/MDAlgorithms/src/IntegrateEllipsoids.cpp
@@ -12,6 +12,7 @@
 #include "MantidKernel/BoundedValidator.h"
 #include "MantidKernel/CompositeValidator.h"
 #include "MantidKernel/Statistics.h"
+#include "MantidMDAlgorithms/MDTransfQ3D.h"
 #include "MantidMDAlgorithms/MDTransfFactory.h"
 #include "MantidMDAlgorithms/UnitsConversionHelper.h"
 #include "MantidMDAlgorithms/Integrate3DEvents.h"
@@ -26,7 +27,6 @@ using namespace Mantid::DataObjects;
 namespace Mantid {
 namespace MDAlgorithms {
 
-namespace {
 /// This only works for diffraction.
 const std::string ELASTIC("Elastic");
 
@@ -41,18 +41,28 @@ const std::size_t DIMS(3);
  * @param integrator : itegrator object on which qlists are accumulated
  * @param prog : progress object
  * @param wksp : input EventWorkspace
- * @param unitConverter : Unit converter
- * @param qConverter : Q converter
+ * @param UBinv : inverse of UB matrix
+ * @param hkl_integ ; boolean for integrating in HKL space
  */
-void qListFromEventWS(Integrate3DEvents &integrator, Progress &prog,
+void IntegrateEllipsoids::qListFromEventWS(Integrate3DEvents &integrator, Progress &prog,
                       EventWorkspace_sptr &wksp,
-                      UnitsConversionHelper &unitConverter,
-                      MDTransf_sptr &qConverter, DblMatrix const &UBinv, bool hkl_integ) {
+                      DblMatrix const &UBinv, bool hkl_integ) {
   // loop through the eventlists
-  std::vector<double> buffer(DIMS);
 
-  size_t numSpectra = wksp->getNumberHistograms();
-  for (std::size_t i = 0; i < numSpectra; ++i) {
+  int numSpectra = static_cast<int>(wksp->getNumberHistograms());
+  PARALLEL_FOR1(wksp)
+  for (int i = 0; i < numSpectra; ++i) {
+    PARALLEL_START_INTERUPT_REGION
+
+    // units conversion helper
+    UnitsConversionHelper unitConverter;
+    unitConverter.initialize(m_targWSDescr, "Momentum");
+
+    // initialize the MD coordinates conversion class
+    MDTransfQ3D qConverter;
+    qConverter.initialize(m_targWSDescr);
+
+    std::vector<double> buffer(DIMS);
     // get a reference to the event list
     EventList &events = wksp->getEventList(i);
 
@@ -67,7 +77,7 @@ void qListFromEventWS(Integrate3DEvents &integrator, Progress &prog,
     // update which pixel is being converted
     std::vector<Mantid::coord_t> locCoord(DIMS, 0.);
     unitConverter.updateConversion(i);
-    qConverter->calcYDepCoordinates(locCoord, i);
+    qConverter.calcYDepCoordinates(locCoord, i);
 
     // loop over the events
     double signal(1.);  // ignorable garbage
@@ -77,7 +87,7 @@ void qListFromEventWS(Integrate3DEvents &integrator, Progress &prog,
     std::vector<std::pair<double, V3D>> qList;
     for (auto event = raw_events.begin(); event != raw_events.end(); ++event) {
       double val = unitConverter.convertUnits(event->tof());
-      qConverter->calcMatrixCoord(val, locCoord, signal, errorSq);
+      qConverter.calcMatrixCoord(val, locCoord, signal, errorSq);
       for (size_t dim = 0; dim < DIMS; ++dim) {
         buffer[dim] = locCoord[dim];
       }
@@ -85,11 +95,14 @@ void qListFromEventWS(Integrate3DEvents &integrator, Progress &prog,
       if (hkl_integ) qVec = UBinv * qVec;
       qList.push_back(std::make_pair(event->m_weight, qVec));
     } // end of loop over events in list
-
-    integrator.addEvents(qList, hkl_integ);
+    PARALLEL_CRITICAL(addEvents){
+      integrator.addEvents(qList, hkl_integ);
+    }
 
     prog.report();
+    PARALLEL_END_INTERUPT_REGION
   } // end of loop over spectra
+  PARALLEL_CHECK_INTERUPT_REGION
 }
 
 /**
@@ -98,20 +111,30 @@ void qListFromEventWS(Integrate3DEvents &integrator, Progress &prog,
  * @param integrator : itegrator object on which qlists are accumulated
  * @param prog : progress object
  * @param wksp : input Workspace2D
- * @param unitConverter : Unit converter
- * @param qConverter : Q converter
+ * @param UBinv : inverse of UB matrix
+ * @param hkl_integ ; boolean for integrating in HKL space
  */
-void qListFromHistoWS(Integrate3DEvents &integrator, Progress &prog,
+void IntegrateEllipsoids::qListFromHistoWS(Integrate3DEvents &integrator, Progress &prog,
                       Workspace2D_sptr &wksp,
-                      UnitsConversionHelper &unitConverter,
-                      MDTransf_sptr &qConverter, DblMatrix const &UBinv, bool hkl_integ) {
+                      DblMatrix const &UBinv, bool hkl_integ) {
 
   // loop through the eventlists
-  std::vector<double> buffer(DIMS);
 
-  size_t numSpectra = wksp->getNumberHistograms();
+  int numSpectra = static_cast<int>(wksp->getNumberHistograms());
   const bool histogramForm = wksp->isHistogramData();
-  for (std::size_t i = 0; i < numSpectra; ++i) {
+  PARALLEL_FOR1(wksp)
+  for (int i = 0; i < numSpectra; ++i) {
+    PARALLEL_START_INTERUPT_REGION
+
+    // units conversion helper
+    UnitsConversionHelper unitConverter;
+    unitConverter.initialize(m_targWSDescr, "Momentum");
+
+    // initialize the MD coordinates conversion class
+    MDTransfQ3D qConverter;
+    qConverter.initialize(m_targWSDescr);
+
+    std::vector<double> buffer(DIMS);
     // get tof and counts
     const Mantid::MantidVec &xVals = wksp->readX(i);
     const Mantid::MantidVec &yVals = wksp->readY(i);
@@ -119,7 +142,7 @@ void qListFromHistoWS(Integrate3DEvents &integrator, Progress &prog,
     // update which pixel is being converted
     std::vector<Mantid::coord_t> locCoord(DIMS, 0.);
     unitConverter.updateConversion(i);
-    qConverter->calcYDepCoordinates(locCoord, i);
+    qConverter.calcYDepCoordinates(locCoord, i);
 
     // loop over the events
     double signal(1.);  // ignorable garbage
@@ -127,7 +150,6 @@ void qListFromHistoWS(Integrate3DEvents &integrator, Progress &prog,
 
     std::vector<std::pair<double, V3D>> qList;
 
-    // TODO. we should be able to do this in an OMP loop.
     for (size_t j = 0; j < yVals.size(); ++j) {
       const double &yVal = yVals[j];
       if (yVal > 0) // TODO, is this condition right?
@@ -140,7 +162,7 @@ void qListFromHistoWS(Integrate3DEvents &integrator, Progress &prog,
         }
 
         double val = unitConverter.convertUnits(tof);
-        qConverter->calcMatrixCoord(val, locCoord, signal, errorSq);
+        qConverter.calcMatrixCoord(val, locCoord, signal, errorSq);
         for (size_t dim = 0; dim < DIMS; ++dim) {
           buffer[dim] = locCoord[dim]; // TODO. Looks un-necessary to me. Can't
                                        // we just add localCoord directly to
@@ -148,22 +170,21 @@ void qListFromHistoWS(Integrate3DEvents &integrator, Progress &prog,
         }
         V3D qVec(buffer[0], buffer[1], buffer[2]);
         if (hkl_integ) qVec = UBinv * qVec;
-        int yValCounts = int(yVal); // we deliberately truncate.
+
         // Account for counts in histograms by increasing the qList with the
         // same q-point
-        qList.push_back(std::make_pair(
-            yValCounts, qVec)); // Not ideal to control the size dynamically?
+        qList.push_back(std::make_pair(yVal, qVec));
       }
-      integrator.addEvents(qList, hkl_integ); // We would have to put a lock around this.
-      prog.report();
     }
-
-    integrator.addEvents(qList, hkl_integ);
-
+    PARALLEL_CRITICAL(addHisto) {
+      integrator.addEvents(qList, hkl_integ);
+    }
     prog.report();
-  }
+    PARALLEL_END_INTERUPT_REGION
+  } // end of loop over spectra
+  PARALLEL_CHECK_INTERUPT_REGION
 }
-} // end anonymous namespace
+
 /** NOTE: This has been adapted from the SaveIsawQvector algorithm.
  */
 
@@ -199,7 +220,7 @@ const std::string IntegrateEllipsoids::category() const { return "Crystal"; }
  */
 void IntegrateEllipsoids::init() {
   auto ws_valid = boost::make_shared<CompositeValidator>();
-
+  ws_valid->add<WorkspaceUnitValidator>("TOF");
   ws_valid->add<InstrumentValidator>();
   // the validator which checks if the workspace has axis
 
@@ -356,25 +377,16 @@ void IntegrateEllipsoids::exec() {
   // set up a descripter of where we are going
   this->initTargetWSDescr(wksp);
 
-  // units conversion helper
-  UnitsConversionHelper unitConv;
-  unitConv.initialize(m_targWSDescr, "Momentum");
-
-  // initialize the MD coordinates conversion class
-  MDTransf_sptr qConverter =
-      MDTransfFactory::Instance().create(m_targWSDescr.AlgID);
-  qConverter->initialize(m_targWSDescr);
-
   // set up the progress bar
   const size_t numSpectra = wksp->getNumberHistograms();
   Progress prog(this, 0.5, 1.0, numSpectra);
 
   if (eventWS) {
     // process as EventWorkspace
-    qListFromEventWS(integrator, prog, eventWS, unitConv, qConverter, UBinv, hkl_integ);
+    qListFromEventWS(integrator, prog, eventWS, UBinv, hkl_integ);
   } else {
     // process as Workspace2D
-    qListFromHistoWS(integrator, prog, histoWS, unitConv, qConverter, UBinv, hkl_integ);
+    qListFromHistoWS(integrator, prog, histoWS, UBinv, hkl_integ);
   }
 
   double inti;
diff --git a/Code/Mantid/Framework/MDAlgorithms/src/IntegrateMDHistoWorkspace.cpp b/Code/Mantid/Framework/MDAlgorithms/src/IntegrateMDHistoWorkspace.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..31e32b39a5d419e3df2c49e41a40dd3bd6300a27
--- /dev/null
+++ b/Code/Mantid/Framework/MDAlgorithms/src/IntegrateMDHistoWorkspace.cpp
@@ -0,0 +1,377 @@
+#include "MantidMDAlgorithms/IntegrateMDHistoWorkspace.h"
+#include "MantidKernel/ArrayProperty.h"
+#include "MantidKernel/MultiThreaded.h"
+
+#include "MantidAPI/FrameworkManager.h"
+#include "MantidAPI/IMDHistoWorkspace.h"
+#include "MantidAPI/IMDIterator.h"
+#include "MantidAPI/Progress.h"
+
+#include "MantidGeometry/MDGeometry/MDHistoDimension.h"
+#include "MantidGeometry/MDGeometry/MDBoxImplicitFunction.h"
+#include "MantidDataObjects/MDHistoWorkspace.h"
+#include "MantidDataObjects/MDHistoWorkspaceIterator.h"
+
+#include <algorithm>
+#include <map>
+#include <utility>
+#include <cmath>
+
+#include <boost/make_shared.hpp>
+#include <boost/scoped_ptr.hpp>
+
+using namespace Mantid::API;
+using namespace Mantid::Kernel;
+using namespace Mantid::Geometry;
+using namespace Mantid::DataObjects;
+
+namespace {
+
+/**
+ * Check for empty binning
+ * @param binning : binning
+ * @return : true if binning is empty
+ */
+bool emptyBinning(const std::vector<double> &binning) {
+  return binning.empty();
+}
+
+/**
+ * Check for integration binning
+ * @param binning : binning
+ * @return : true if binning is min, max integration style
+ */
+bool integrationBinning(const std::vector<double> &binning) {
+  return binning.size() == 2 && binning[0] < binning[1];
+}
+
+/**
+ * Check for similar binning
+ * @param binning : binning
+ * @return : true if binning similar, with limits but same bin width
+ */
+bool similarBinning(const std::vector<double> &binning) {
+  return binning.size() == 3 && binning[1] == 0.0;
+}
+
+/**
+ * Determine whether the binning provided is any good.
+ * @param binning : Binning property
+ * @return : string containing error. Or empty for no error.
+ */
+std::string checkBinning(const std::vector<double> &binning) {
+  std::string error; // No error.
+  if (!emptyBinning(binning)) {
+    if (binning.size() == 3) {
+      const double step = binning[1];
+      if (step != 0) {
+        error = "Only step size zero is allowed. Denotes copy of original step "
+                "size for that dimension.";
+      } else {
+         auto min = binning[0];
+         auto max = binning[2];
+         if (min >= max) {
+            error = "Min must be < max limit for binning";
+         }
+      }
+
+    } else if (binning.size() == 2) {
+         auto min = binning[0];
+         auto max = binning[1];
+         if (min >= max) {
+            error = "Min must be < max limit for binning";
+         }
+    } else {
+      error = "Unknown binning prameters for dimension.";
+    }
+  }
+  return error;
+}
+
+/**
+ * Create the output workspace in the right shape.
+ * @param inWS : Input workspace for dimensionality
+ * @param pbins : User provided binning
+ * @param logger : Logging object
+ * @return
+ */
+MDHistoWorkspace_sptr
+createShapedOutput(IMDHistoWorkspace const *const inWS,
+                   std::vector<std::vector<double>> pbins, Logger& logger) {
+  const size_t nDims = inWS->getNumDims();
+  std::vector<Mantid::Geometry::IMDDimension_sptr> dimensions(nDims);
+  for (size_t i = 0; i < nDims; ++i) {
+
+    IMDDimension_const_sptr inDim = inWS->getDimension(i);
+    auto outDim = boost::make_shared<MDHistoDimension>(inDim.get());
+    // Apply dimensions as inputs.
+    if (i < pbins.size() && integrationBinning(pbins[i])) {
+      auto binning = pbins[i];
+      outDim->setRange(
+          1 /*single bin*/,
+          static_cast<Mantid::coord_t>(binning.front()) /*min*/,
+          static_cast<Mantid::coord_t>(
+              binning.back()) /*max*/); // Set custom min, max and nbins.
+    } else if( i < pbins.size() && similarBinning(pbins[i]) ) {
+      auto binning = pbins[i];
+      const double width = inDim->getBinWidth(); // Take the width from the input dimension
+      double min = binning.front();
+      double max = binning.back();
+
+      // Correct users, input, output and rounded to the nearest whole width.
+      min = width * std::floor(min/width); // Rounded down
+      max = width * std::ceil(max/width); // Rounded up
+
+      if(min != binning.front()) {
+          std::stringstream buffer;
+          buffer << "Rounding min from: " << binning.front() << " to the nearest whole width at: " << min;
+          logger.warning(buffer.str());
+      }
+      if(max != binning.back()) {
+          std::stringstream buffer;
+          buffer << "Rounding max from: " << binning.back() << " to the nearest whole width at: " << max;
+          logger.warning(buffer.str());
+      }
+      const size_t roundedNBins = static_cast<size_t>((max-min)/width+0.5); // round up to a whole number of bins.
+      outDim->setRange(
+          roundedNBins,
+          static_cast<Mantid::coord_t>(min) /*min*/,
+          static_cast<Mantid::coord_t>(max) /*max*/); // Set custom min, max and nbins.
+    }
+    dimensions[i] = outDim;
+  }
+  return MDHistoWorkspace_sptr(new MDHistoWorkspace(dimensions));
+}
+
+/**
+ * Perform a weighted sum at the iterator position. This function does not
+ * increment the iterator.
+ * @param iterator : Iterator to use in sum
+ * @param box : Box implicit function defining valid region.
+ * @param sumSignal : Accumlation in/out ref.
+ * @param sumSQErrors : Accumulation error in/out ref. Squared value.
+ * @param sumNEvents : Accumulation n_event in/out ref.
+ */
+void performWeightedSum(MDHistoWorkspaceIterator const *const iterator,
+                        MDBoxImplicitFunction &box, double &sumSignal,
+                        double &sumSQErrors, double &sumNEvents) {
+  const double weight = box.fraction(iterator->getBoxExtents());
+  sumSignal += weight * iterator->getSignal();
+  const double error = iterator->getError();
+  sumSQErrors += weight * (error * error);
+  sumNEvents += weight * double(iterator->getNumEventsFraction());
+}
+}
+
+namespace Mantid {
+namespace MDAlgorithms {
+
+using Mantid::Kernel::Direction;
+using Mantid::API::WorkspaceProperty;
+
+// Register the algorithm into the AlgorithmFactory
+DECLARE_ALGORITHM(IntegrateMDHistoWorkspace)
+
+//----------------------------------------------------------------------------------------------
+/** Constructor
+ */
+IntegrateMDHistoWorkspace::IntegrateMDHistoWorkspace() {}
+
+//----------------------------------------------------------------------------------------------
+/** Destructor
+ */
+IntegrateMDHistoWorkspace::~IntegrateMDHistoWorkspace() {}
+
+//----------------------------------------------------------------------------------------------
+
+/// Algorithms name for identification. @see Algorithm::name
+const std::string IntegrateMDHistoWorkspace::name() const {
+  return "IntegrateMDHistoWorkspace";
+}
+
+/// Algorithm's version for identification. @see Algorithm::version
+int IntegrateMDHistoWorkspace::version() const { return 1; }
+
+/// Algorithm's category for identification. @see Algorithm::category
+const std::string IntegrateMDHistoWorkspace::category() const {
+  return "MDAlgorithms";
+}
+
+/// Algorithm's summary for use in the GUI and help. @see Algorithm::summary
+const std::string IntegrateMDHistoWorkspace::summary() const {
+  return "Performs axis aligned integration of MDHistoWorkspaces";
+}
+
+//----------------------------------------------------------------------------------------------
+/** Initialize the algorithm's properties.
+ */
+void IntegrateMDHistoWorkspace::init() {
+  declareProperty(new WorkspaceProperty<IMDHistoWorkspace>("InputWorkspace", "",
+                                                           Direction::Input),
+                  "An input workspace.");
+
+  const std::vector<double> defaultBinning;
+  declareProperty(new ArrayProperty<double>("P1Bin", defaultBinning),
+                  "Projection 1 binning.");
+  declareProperty(new ArrayProperty<double>("P2Bin", defaultBinning),
+                  "Projection 2 binning.");
+  declareProperty(new ArrayProperty<double>("P3Bin", defaultBinning),
+                  "Projection 3 binning.");
+  declareProperty(new ArrayProperty<double>("P4Bin", defaultBinning),
+                  "Projection 4 binning.");
+  declareProperty(new ArrayProperty<double>("P5Bin", defaultBinning),
+                  "Projection 5 binning.");
+
+  declareProperty(new WorkspaceProperty<IMDHistoWorkspace>(
+                      "OutputWorkspace", "", Direction::Output),
+                  "An output workspace.");
+}
+
+//----------------------------------------------------------------------------------------------
+/** Execute the algorithm.
+ */
+void IntegrateMDHistoWorkspace::exec() {
+  IMDHistoWorkspace_sptr inWS = this->getProperty("InputWorkspace");
+  const size_t nDims = inWS->getNumDims();
+  std::vector<std::vector<double>> pbins(5);
+  pbins[0] = this->getProperty("P1Bin");
+  pbins[1] = this->getProperty("P2Bin");
+  pbins[2] = this->getProperty("P3Bin");
+  pbins[3] = this->getProperty("P4Bin");
+  pbins[4] = this->getProperty("P5Bin");
+
+  const size_t emptyCount =
+      std::count_if(pbins.begin(), pbins.end(), emptyBinning);
+  if (emptyCount == pbins.size()) {
+    // No work to do.
+    g_log.information(this->name() + " Direct clone of input.");
+    this->setProperty("OutputWorkspace", inWS->clone());
+  } else {
+
+    /* Create the output workspace in the right shape. This allows us to iterate
+       over our output
+       structure and fill it.
+     */
+    MDHistoWorkspace_sptr outWS = createShapedOutput(inWS.get(), pbins, g_log);
+
+    Progress progress(this, 0, 1, size_t(outWS->getNPoints()));
+
+    // Store in each dimension
+    std::vector<Mantid::coord_t> binWidthsOut(nDims);
+    std::vector<int> widthVector(nDims); // used for nearest neighbour search
+    for (size_t i = 0; i < nDims; ++i) {
+      binWidthsOut[i] = outWS->getDimension(i)->getBinWidth();
+
+      // Maximum width vector for region in output workspace corresponding to
+      // region in input workspace.
+
+      /* ceil(wout/win) = n_pixels in input corresponding to 1 pixel in output.
+         The width vector is the total width. So we always need to double it to
+         take account of the whole region.
+         For example, 8/4 = 2, but thats only 1 pixel on each side of the
+         center, we need 2 * that to give the correct answer of 4.
+      */
+      widthVector[i] =
+          2 * static_cast<int>(std::ceil(binWidthsOut[i] /
+                                         inWS->getDimension(i)->getBinWidth()));
+
+      if (widthVector[i] % 2 == 0) {
+        widthVector[i] += 1; // make it odd if not already.
+      }
+    }
+
+    // Outer loop over the output workspace iterator poistions.
+    const int nThreads = Mantid::API::FrameworkManager::Instance()
+                             .getNumOMPThreads(); // NThreads to Request
+
+    auto outIterators = outWS->createIterators(nThreads, NULL);
+
+    PARALLEL_FOR_NO_WSP_CHECK()
+    for (int i = 0; i < int(outIterators.size()); ++i) {
+
+      PARALLEL_START_INTERUPT_REGION
+      boost::scoped_ptr<MDHistoWorkspaceIterator> outIterator(
+          dynamic_cast<MDHistoWorkspaceIterator *>(outIterators[i]));
+
+      do {
+
+        Mantid::Kernel::VMD outIteratorCenter = outIterator->getCenter();
+
+        // Calculate the extents for this out iterator position.
+        std::vector<Mantid::coord_t> mins(nDims);
+        std::vector<Mantid::coord_t> maxs(nDims);
+        for (size_t i = 0; i < nDims; ++i) {
+          const coord_t delta = binWidthsOut[i] / 2;
+          mins[i] = outIteratorCenter[i] - delta;
+          maxs[i] = outIteratorCenter[i] + delta;
+        }
+        MDBoxImplicitFunction box(mins, maxs);
+
+        double sumSignal = 0;
+        double sumSQErrors = 0;
+        double sumNEvents = 0;
+
+        // Create a thread-local input iterator.
+        boost::scoped_ptr<MDHistoWorkspaceIterator> inIterator(
+            dynamic_cast<MDHistoWorkspaceIterator *>(inWS->createIterator()));
+
+        /*
+        We jump to the iterator position which is closest in the model
+        coordinates
+        to the centre of our output iterator. This allows us to consider a much
+        smaller region of space as part of our inner loop
+        rather than iterating over the full set of boxes of the input workspace.
+        */
+        inIterator->jumpToNearest(outIteratorCenter);
+
+        performWeightedSum(inIterator.get(), box, sumSignal,
+                           sumSQErrors, sumNEvents); // Use the present position. neighbours
+                                         // below exclude the current position.
+
+        // Look at all of the neighbours of our position. We previously
+        // calculated what the width vector would need to be.
+        auto neighbourIndexes =
+            inIterator->findNeighbourIndexesByWidth(widthVector);
+        for (size_t i = 0; i < neighbourIndexes.size(); ++i) {
+          inIterator->jumpTo(neighbourIndexes[i]); // Go to that neighbour
+          performWeightedSum(inIterator.get(), box, sumSignal, sumSQErrors, sumNEvents);
+        }
+
+        const size_t iteratorIndex = outIterator->getLinearIndex();
+        outWS->setSignalAt(iteratorIndex, sumSignal);
+        outWS->setErrorSquaredAt(iteratorIndex, sumSQErrors);
+        outWS->setNumEventsAt(iteratorIndex, sumNEvents);
+
+        progress.report();
+      } while (outIterator->next());
+      PARALLEL_END_INTERUPT_REGION
+    }
+    PARALLEL_CHECK_INTERUPT_REGION
+    this->setProperty("OutputWorkspace", outWS);
+  }
+}
+
+/**
+ * Overriden validate inputs
+ * @return map of property names to problems for bad inputs
+ */
+std::map<std::string, std::string>
+Mantid::MDAlgorithms::IntegrateMDHistoWorkspace::validateInputs() {
+  // Check binning parameters
+  std::map<std::string, std::string> errors;
+
+  for (int i = 1; i < 6; ++i) {
+    std::stringstream propBuffer;
+    propBuffer << "P" << i << "Bin";
+    std::string propertyName = propBuffer.str();
+    std::vector<double> binning = this->getProperty(propertyName);
+    std::string result = checkBinning(binning);
+    if (!result.empty()) {
+      errors.insert(std::make_pair(propertyName, result));
+    }
+  }
+  return errors;
+}
+
+} // namespace MDAlgorithms
+} // namespace Mantid
diff --git a/Code/Mantid/Framework/MDAlgorithms/src/LoadMD.cpp b/Code/Mantid/Framework/MDAlgorithms/src/LoadMD.cpp
index 694014471026ca7fd6e59de755a4f2bb92c69293..3b33597fc7fde3801810a27cc62ab73e7b4da0b2 100644
--- a/Code/Mantid/Framework/MDAlgorithms/src/LoadMD.cpp
+++ b/Code/Mantid/Framework/MDAlgorithms/src/LoadMD.cpp
@@ -158,17 +158,27 @@ void LoadMD::exec() {
   // Open the entry
   m_file->openGroup(entryName, "NXentry");
 
-  // How many dimensions?
-  std::vector<int32_t> vecDims;
-  m_file->readData("dimensions", vecDims);
-  if (vecDims.empty())
-    throw std::runtime_error("LoadMD:: Error loading number of dimensions.");
-  m_numDims = vecDims[0];
-  if (m_numDims <= 0)
-    throw std::runtime_error("LoadMD:: number of dimensions <= 0.");
-
-  // Now load all the dimension xml
-  this->loadDimensions();
+  // Check is SaveMD version 2 was used
+  SaveMDVersion = 0;
+  if (m_file->hasAttr("SaveMDVersion"))
+    m_file->getAttr("SaveMDVersion", SaveMDVersion);
+
+  if (SaveMDVersion == 2)
+    this->loadDimensions2();
+  else {
+    // How many dimensions?
+    std::vector<int32_t> vecDims;
+    m_file->readData("dimensions", vecDims);
+    if (vecDims.empty())
+      throw std::runtime_error("LoadMD:: Error loading number of dimensions.");
+    m_numDims = vecDims[0];
+    if (m_numDims <= 0)
+      throw std::runtime_error("LoadMD:: number of dimensions <= 0.");
+
+    // Now load all the dimension xml
+    this->loadDimensions();
+  }
+
   // Coordinate system
   this->loadCoordinateSystem();
 
@@ -211,12 +221,19 @@ void LoadMD::loadSlab(std::string name, void *data, MDHistoWorkspace_sptr ws,
   if (m_file->getInfo().type != dataType)
     throw std::runtime_error("Unexpected data type for '" + name +
                              "' data set.'");
-  if (m_file->getInfo().dims[0] != static_cast<int>(ws->getNPoints()))
+
+  int nPoints = 1;
+  size_t numDims = m_file->getInfo().dims.size();
+  std::vector<int> size(numDims);
+  for (size_t d = 0; d < numDims; d++) {
+    nPoints *= static_cast<int>(m_file->getInfo().dims[d]);
+    size[d] = static_cast<int>(m_file->getInfo().dims[d]);
+  }
+  if (nPoints != static_cast<int>(ws->getNPoints()))
     throw std::runtime_error(
         "Inconsistency between the number of points in '" + name +
         "' and the number of bins defined by the dimensions.");
-  std::vector<int> start(1, 0);
-  std::vector<int> size(1, static_cast<int>(ws->getNPoints()));
+  std::vector<int> start(numDims, 0);
   try {
     m_file->getSlab(data, start, size);
   } catch (...) {
@@ -244,6 +261,8 @@ void LoadMD::loadHisto() {
 
   this->loadAffineMatricies(boost::dynamic_pointer_cast<IMDWorkspace>(ws));
 
+  if (SaveMDVersion == 2 )
+    m_file->openGroup("data","NXdata");
   // Load each data slab
   this->loadSlab("signal", ws->getSignalArray(), ws, ::NeXus::FLOAT64);
   this->loadSlab("errors_squared", ws->getErrorSquaredArray(), ws,
@@ -273,6 +292,39 @@ void LoadMD::loadDimensions() {
   }
 }
 
+//----------------------------------------------------------------------------------------------
+/** Load all the dimensions into this->m_dims
+* The dimensions are stored as an nxData array */
+void LoadMD::loadDimensions2() {
+  m_dims.clear();
+
+  std::string axes;
+
+  m_file->openGroup("data","NXdata");
+  m_file->openData("signal");
+  m_file->getAttr("axes", axes);
+  m_file->closeData();
+
+  std::vector<std::string> splitAxes;
+  boost::split(splitAxes, axes, boost::is_any_of(":"));
+  // Create each dimension from axes data
+  // We loop axes backwards because Mantid
+  for (size_t d = splitAxes.size(); d > 0; d--) {
+    std::string long_name;
+    std::string units;
+    std::vector<double> axis;
+    m_file->openData(splitAxes[d - 1]);
+    m_file->getAttr("long_name", long_name);
+    m_file->getAttr("units", units);
+    m_file->getData(axis);
+    m_file->closeData();
+    m_dims.push_back(boost::make_shared<MDHistoDimension>(
+        long_name, splitAxes[d - 1], units, static_cast<coord_t>(axis.front()),
+        static_cast<coord_t>(axis.back()), axis.size() - 1));
+  }
+  m_file->closeGroup();
+}
+
 /** Load the coordinate system **/
 void LoadMD::loadCoordinateSystem() {
   // Current version stores the coordinate system
diff --git a/Code/Mantid/Framework/MDAlgorithms/src/LoadSQW.cpp b/Code/Mantid/Framework/MDAlgorithms/src/LoadSQW.cpp
index 4f71e5fd9bbf2003ed9e1100f0f7dfa7cd06bf2b..b0ae1eebee894d45643ec1b9749f1c0662d7016d 100644
--- a/Code/Mantid/Framework/MDAlgorithms/src/LoadSQW.cpp
+++ b/Code/Mantid/Framework/MDAlgorithms/src/LoadSQW.cpp
@@ -276,10 +276,10 @@ void
           interpretAs<float>(Buffer, current_pix + column_size),
           interpretAs<float>(Buffer, current_pix + column_size_2),
           interpretAs<float>(Buffer, current_pix + column_size_3)};
-      float error = interpretAs<float>(Buffer, current_pix + column_size_8);
+      const float errorSQ = interpretAs<float>(Buffer, current_pix + column_size_8);
       ws->addEvent(MDEvent<4>(
           interpretAs<float>(Buffer, current_pix + column_size_7), // Signal
-          error * error,                                           // Error sq
+          errorSQ,                                           // Error sq
           static_cast<uint16_t>(interpretAs<float>(
               Buffer, current_pix + column_size_6)), // run Index
           static_cast<int32_t>(interpretAs<float>(
diff --git a/Code/Mantid/Framework/MDAlgorithms/src/MDTransfModQ.cpp b/Code/Mantid/Framework/MDAlgorithms/src/MDTransfModQ.cpp
index fe1aecb8937c0377fb03b91a31fc0ee8146c129a..d367fdedbace6a2428bbfa9413949b6ed6553c1c 100644
--- a/Code/Mantid/Framework/MDAlgorithms/src/MDTransfModQ.cpp
+++ b/Code/Mantid/Framework/MDAlgorithms/src/MDTransfModQ.cpp
@@ -4,7 +4,9 @@
 namespace Mantid {
 namespace MDAlgorithms {
 // register the class, whith conversion factory under ModQ name
+// clang-format off
 DECLARE_MD_TRANSFID(MDTransfModQ, |Q|)
+// clang-format on
 
 /**method calculates the units, the transformation expects the input ws to be
 in. If the input ws is in different units,
diff --git a/Code/Mantid/Framework/MDAlgorithms/src/MergeMDFiles.cpp b/Code/Mantid/Framework/MDAlgorithms/src/MergeMDFiles.cpp
index 44d21fa14a44d348e74887dbebadfd9028cdb734..03f3afd4a056a53ad85884b9eb0a7ff0e6ee62d1 100644
--- a/Code/Mantid/Framework/MDAlgorithms/src/MergeMDFiles.cpp
+++ b/Code/Mantid/Framework/MDAlgorithms/src/MergeMDFiles.cpp
@@ -314,8 +314,10 @@ void MergeMDFiles::finalizeOutput(const std::string &outputFile) {
     // create or open WS group and put there additional information about WS and
     // its dimensions
     bool old_data_there;
+    // clang-format off
     boost::scoped_ptr< ::NeXus::File> file(MDBoxFlatTree::createOrOpenMDWSgroup(
         outputFile, m_nDims, m_MDEventType, false, old_data_there));
+    // clang-format on
     this->progress(0.94, "Saving ws history and dimensions");
     MDBoxFlatTree::saveWSGenericInfo(file.get(), m_OutIWS);
     // Save each ExperimentInfo to a spot in the file
diff --git a/Code/Mantid/Framework/MDAlgorithms/src/SaveMD.cpp b/Code/Mantid/Framework/MDAlgorithms/src/SaveMD.cpp
index 0200c834d96546b539517a385f48774d87ebc731..2a16afdc07de8a922d624643050d3846e03ada08 100644
--- a/Code/Mantid/Framework/MDAlgorithms/src/SaveMD.cpp
+++ b/Code/Mantid/Framework/MDAlgorithms/src/SaveMD.cpp
@@ -15,11 +15,13 @@
 #include "MantidDataObjects/MDBoxFlatTree.h"
 #include "MantidDataObjects/BoxControllerNeXusIO.h"
 
+// clang-format off
 #if defined(__GLIBCXX__) && __GLIBCXX__ >= 20100121 // libstdc++-4.4.3
 typedef std::unique_ptr< ::NeXus::File> file_holder_type;
 #else
 typedef std::auto_ptr< ::NeXus::File> file_holder_type;
 #endif
+// clang-format on
 
 using namespace Mantid::Kernel;
 using namespace Mantid::API;
diff --git a/Code/Mantid/Framework/MDAlgorithms/src/SaveMD2.cpp b/Code/Mantid/Framework/MDAlgorithms/src/SaveMD2.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..068061edf103f332d69006641d66f6d70750ca3f
--- /dev/null
+++ b/Code/Mantid/Framework/MDAlgorithms/src/SaveMD2.cpp
@@ -0,0 +1,221 @@
+#include "MantidAPI/CoordTransform.h"
+#include "MantidAPI/FileProperty.h"
+#include "MantidAPI/IMDEventWorkspace.h"
+#include "MantidKernel/Matrix.h"
+#include "MantidKernel/System.h"
+#include "MantidDataObjects/MDBoxIterator.h"
+#include "MantidDataObjects/MDEventFactory.h"
+#include "MantidDataObjects/MDEventWorkspace.h"
+#include "MantidMDAlgorithms/SaveMD2.h"
+#include "MantidDataObjects/MDBox.h"
+#include "MantidAPI/Progress.h"
+#include "MantidKernel/EnabledWhenProperty.h"
+#include <Poco/File.h>
+#include "MantidDataObjects/MDHistoWorkspace.h"
+#include "MantidDataObjects/MDBoxFlatTree.h"
+#include "MantidDataObjects/BoxControllerNeXusIO.h"
+
+// clang-format off
+#if defined(__GLIBCXX__) && __GLIBCXX__ >= 20100121 // libstdc++-4.4.3
+typedef std::unique_ptr< ::NeXus::File> file_holder_type;
+#else
+typedef std::auto_ptr< ::NeXus::File> file_holder_type;
+#endif
+// clang-format on
+
+using namespace Mantid::Kernel;
+using namespace Mantid::API;
+using namespace Mantid::DataObjects;
+using namespace Mantid::Geometry;
+
+namespace Mantid {
+namespace MDAlgorithms {
+
+// Register the algorithm into the AlgorithmFactory
+DECLARE_ALGORITHM(SaveMD2)
+
+//----------------------------------------------------------------------------------------------
+/** Constructor
+ */
+SaveMD2::SaveMD2() {}
+
+//----------------------------------------------------------------------------------------------
+/** Destructor
+ */
+SaveMD2::~SaveMD2() {}
+
+//----------------------------------------------------------------------------------------------
+
+//----------------------------------------------------------------------------------------------
+/** Initialize the algorithm's properties.
+ */
+void SaveMD2::init() {
+  declareProperty(new WorkspaceProperty<IMDWorkspace>("InputWorkspace", "",
+                                                      Direction::Input),
+                  "An input MDEventWorkspace or MDHistoWorkspace.");
+
+  std::vector<std::string> exts;
+  exts.push_back(".nxs");
+  declareProperty(
+      new FileProperty("Filename", "", FileProperty::OptionalSave, exts),
+      "The name of the Nexus file to write, as a full or relative path.\n"
+      "Optional if UpdateFileBackEnd is checked.");
+  // Filename is NOT used if UpdateFileBackEnd
+  setPropertySettings("Filename", new EnabledWhenProperty("UpdateFileBackEnd",
+                                                          IS_EQUAL_TO, "0"));
+
+  declareProperty(
+      "UpdateFileBackEnd", false,
+      "Only for MDEventWorkspaces with a file back end: check this to update "
+      "the NXS file on disk\n"
+      "to reflect the current data structure. Filename parameter is ignored.");
+  setPropertySettings(
+      "UpdateFileBackEnd",
+      new EnabledWhenProperty("MakeFileBacked", IS_EQUAL_TO, "0"));
+
+  declareProperty("MakeFileBacked", false,
+                  "For an MDEventWorkspace that was created in memory:\n"
+                  "This saves it to a file AND makes the workspace into a "
+                  "file-backed one.");
+  setPropertySettings(
+      "MakeFileBacked",
+      new EnabledWhenProperty("UpdateFileBackEnd", IS_EQUAL_TO, "0"));
+}
+
+//----------------------------------------------------------------------------------------------
+/** Save a MDHistoWorkspace to a .nxs file
+ *
+ * @param ws :: MDHistoWorkspace to save
+ */
+void SaveMD2::doSaveHisto(Mantid::DataObjects::MDHistoWorkspace_sptr ws) {
+  std::string filename = getPropertyValue("Filename");
+
+  // Erase the file if it exists
+  Poco::File oldFile(filename);
+  if (oldFile.exists())
+    oldFile.remove();
+
+  // Create a new file in HDF5 mode.
+  ::NeXus::File *file;
+  file = new ::NeXus::File(filename, NXACC_CREATE5);
+
+  // The base entry. Named so as to distinguish from other workspace types.
+  file->makeGroup("MDHistoWorkspace", "NXentry", true);
+  file->putAttr("SaveMDVersion", 2);
+
+  // Write out the coordinate system
+  file->writeData("coordinate_system",
+                  static_cast<uint32_t>(ws->getSpecialCoordinateSystem()));
+
+  // Save the algorithm history under "process"
+  ws->getHistory().saveNexus(file);
+
+  // Save all the ExperimentInfos
+  for (uint16_t i = 0; i < ws->getNumExperimentInfo(); i++) {
+    ExperimentInfo_sptr ei = ws->getExperimentInfo(i);
+    std::string groupName = "experiment" + Strings::toString(i);
+    if (ei) {
+      // Can't overwrite entries. Just add the new ones
+      file->makeGroup(groupName, "NXgroup", true);
+      file->putAttr("version", 1);
+      ei->saveExperimentInfoNexus(file);
+      file->closeGroup();
+    }
+  }
+
+  // Write out the affine matrices
+  MDBoxFlatTree::saveAffineTransformMatricies(
+      file, boost::dynamic_pointer_cast<const IMDWorkspace>(ws));
+
+  // Check that the typedef has not been changed. The NeXus types would need
+  // changing if it does!
+  assert(sizeof(signal_t) == sizeof(double));
+
+  file->makeGroup("data", "NXdata", true);
+
+  // Save each axis dimension as an array
+  size_t numDims = ws->getNumDims();
+  std::string axes_label;
+  for (size_t d = 0; d < numDims; d++) {
+    std::vector<double> axis;
+    IMDDimension_const_sptr dim = ws->getDimension(d);
+    for (size_t n = 0; n < dim->getNBins()+1; n++)
+      axis.push_back(dim->getX(n));
+    file->makeData(dim->getDimensionId(), ::NeXus::FLOAT64,
+                   static_cast<int>(dim->getNBins()+1), true);
+    file->putData(&axis[0]);
+    file->putAttr("units", std::string(dim->getUnits()));
+    file->putAttr("long_name", std::string(dim->getName()));
+    file->closeData();
+    if (d != 0)
+      axes_label.insert(0, ":");
+    axes_label.insert(0, dim->getDimensionId());
+  }
+
+  // Number of data points
+  // Size in each dimension (in the "C" style order, so z,y,x
+  // That is, data[z][y][x] = etc.
+  std::vector<int> size(numDims);
+  for (size_t d = 0; d < numDims; d++) {
+    IMDDimension_const_sptr dim = ws->getDimension(d);
+    // Size in each dimension (reverse order for RANK)
+    size[numDims - 1 - d] = int(dim->getNBins());
+  }
+
+  file->makeData("signal", ::NeXus::FLOAT64, size, true);
+  file->putData(ws->getSignalArray());
+  file->putAttr("signal", 1);
+  file->putAttr("axes", axes_label);
+  file->closeData();
+
+  file->makeData("errors_squared", ::NeXus::FLOAT64, size, true);
+  file->putData(ws->getErrorSquaredArray());
+  file->closeData();
+
+  file->makeData("num_events", ::NeXus::FLOAT64, size, true);
+  file->putData(ws->getNumEventsArray());
+  file->closeData();
+
+  file->makeData("mask", ::NeXus::INT8, size, true);
+  file->putData(ws->getMaskArray());
+  file->closeData();
+
+  file->closeGroup();
+
+  // TODO: Links to original workspace???
+
+  file->closeGroup();
+  file->close();
+}
+
+//----------------------------------------------------------------------------------------------
+/** Execute the algorithm.
+ */
+void SaveMD2::exec() {
+  IMDWorkspace_sptr ws = getProperty("InputWorkspace");
+  IMDEventWorkspace_sptr eventWS =
+      boost::dynamic_pointer_cast<IMDEventWorkspace>(ws);
+  MDHistoWorkspace_sptr histoWS =
+      boost::dynamic_pointer_cast<MDHistoWorkspace>(ws);
+
+  if (eventWS) {
+    // If event workspace use SaveMD version 1.
+    IAlgorithm_sptr saveMDv1 = createChildAlgorithm("SaveMD", -1, -1, true, 1);
+    saveMDv1->setProperty<IMDWorkspace_sptr>("InputWorkspace", ws);
+    saveMDv1->setProperty<std::string>("Filename", getProperty("Filename"));
+    saveMDv1->setProperty<bool>("UpdateFileBackEnd",
+                                getProperty("UpdateFileBackEnd"));
+    saveMDv1->setProperty<bool>("MakeFileBacked",
+                                getProperty("MakeFileBacked"));
+    saveMDv1->execute();
+  } else if (histoWS) {
+    this->doSaveHisto(histoWS);
+  } else
+    throw std::runtime_error("SaveMD can only save MDEventWorkspaces and "
+                             "MDHistoWorkspaces.\nPlease use SaveNexus or "
+                             "another algorithm appropriate for this workspace "
+                             "type.");
+}
+
+} // namespace Mantid
+} // namespace DataObjects
diff --git a/Code/Mantid/Framework/MDAlgorithms/src/SlicingAlgorithm.cpp b/Code/Mantid/Framework/MDAlgorithms/src/SlicingAlgorithm.cpp
index 3e3057530fd1b0c4609e60dd86776d21cddc877f..a09e4a04a6b87c3cceffecbfa3eed30d6166867b 100644
--- a/Code/Mantid/Framework/MDAlgorithms/src/SlicingAlgorithm.cpp
+++ b/Code/Mantid/Framework/MDAlgorithms/src/SlicingAlgorithm.cpp
@@ -592,9 +592,12 @@ void SlicingAlgorithm::createAlignedTransform() {
         new DataObjects::CoordTransformAffine(inD, m_outD);
     tmp->setMatrix(mat);
     m_transformToOriginal = tmp;
-  } else
+  } else {
     // Changed # of dimensions - can't reverse the transform
     m_transformToOriginal = NULL;
+    g_log.warning("SlicingAlgorithm: Your slice will cause the output workspace to have less dimensions than the input. This will affect your ability to create subsequent slices.");
+  }
+   
 }
 
 //-----------------------------------------------------------------------------------------------
diff --git a/Code/Mantid/Framework/MDAlgorithms/test/CreateMDHistoWorkspaceTest.h b/Code/Mantid/Framework/MDAlgorithms/test/CreateMDHistoWorkspaceTest.h
index 3bfe22e06062366607d9a2775b3bb3c2eed3c3d4..66982677d4912764bc477fd3fa796ec0b51f90d5 100644
--- a/Code/Mantid/Framework/MDAlgorithms/test/CreateMDHistoWorkspaceTest.h
+++ b/Code/Mantid/Framework/MDAlgorithms/test/CreateMDHistoWorkspaceTest.h
@@ -81,6 +81,16 @@ public:
     AnalysisDataService::Instance().remove(outWSName);
   }
 
+  void test_throws_if_wrong_number_of_nevents()
+  {
+    std::string outWSName = "test_ws";
+    IAlgorithm_sptr alg = make_standard_algorithm(outWSName);
+    alg->setProperty("NumberOfEvents", "1"); //Only one number of events value provided, but NumberOfBins set to 5!
+    TS_ASSERT_THROWS(alg->execute(), std::invalid_argument);
+    AnalysisDataService::Instance().remove(outWSName);
+  }
+
+
   void test_exec_1D()
   {
     // Name of the output workspace.
diff --git a/Code/Mantid/Framework/MDAlgorithms/test/CutMDTest.h b/Code/Mantid/Framework/MDAlgorithms/test/CutMDTest.h
index 64bf8835f730cef267501d583f4d81fae45bba3e..1000cfbafcc543ff7d8c43e8957310acaf648607 100644
--- a/Code/Mantid/Framework/MDAlgorithms/test/CutMDTest.h
+++ b/Code/Mantid/Framework/MDAlgorithms/test/CutMDTest.h
@@ -8,8 +8,10 @@
 #include "MantidAPI/IMDEventWorkspace.h"
 #include "MantidAPI/IMDHistoWorkspace.h"
 #include "MantidAPI/TableRow.h"
+#include "MantidTestHelpers/MDEventsTestHelper.h"
 
 #include <cxxtest/TestSuite.h>
+#include <boost/assign/list_of.hpp>
 
 using namespace Mantid::MDAlgorithms;
 using namespace Mantid::API;
@@ -105,7 +107,6 @@ public:
     algCutMD->setProperty("P1Bin", "0.1");
     algCutMD->setProperty("P2Bin", "0.1");
     algCutMD->setProperty("P3Bin", "0.1");
-    algCutMD->setProperty("CheckAxes", false);
     algCutMD->execute();
     TS_ASSERT(algCutMD->isExecuted());
 
@@ -150,7 +151,6 @@ public:
     algCutMD->setProperty("P1Bin", "0,0.3,0.8");
     algCutMD->setProperty("P2Bin", "0.1");
     algCutMD->setProperty("P3Bin", "0.1");
-    algCutMD->setProperty("CheckAxes", false);
     algCutMD->setProperty("NoPix", true);
     algCutMD->execute();
     TS_ASSERT(algCutMD->isExecuted());
@@ -177,7 +177,6 @@ public:
     algCutMD->setProperty("P1Bin", "0,1.1,1");
     algCutMD->setProperty("P2Bin", "21");
     algCutMD->setProperty("P3Bin", "0.1");
-    algCutMD->setProperty("CheckAxes", false);
     algCutMD->setProperty("NoPix", true);
     algCutMD->execute();
     TS_ASSERT(algCutMD->isExecuted());
@@ -442,6 +441,79 @@ public:
     AnalysisDataService::Instance().remove(wsName);
     AnalysisDataService::Instance().remove(wsOutName);
   }
+
+  void test_slice_md_histo_workspace() {
+
+      
+      /*
+
+      Input filled with 1's binning = 1 in each dimension
+      ----------------------------- (10, 10)
+      |                           |
+      |                           |
+      |                           |
+      |                           |
+      |                           |
+      |                           |
+      |                           |
+      |                           |
+      |                           |
+      |                           |
+      -----------------------------
+    (0, 0)
+
+
+      Slice. Two vertical columns. Each 1 in width.
+
+      ----------------------------- (10, 10)
+      |                           |
+      |                           |
+      |__________________________ | (10, 7.1)
+      |    |    |   ...           |
+      |    |    |                 |
+      |    |    |                 |
+      |    |    |                 |
+      |    |    |                 |
+      |__________________________ | (10, 1.1)
+      |                           |
+      -----------------------------
+    (0, 0)
+
+    */
+
+    using namespace Mantid::DataObjects;
+    MDHistoWorkspace_sptr ws = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0 /*signal*/, 2 /*nd*/, 10 /*nbins*/, 10 /*max*/, 1.0 /*error sq*/);
+
+    CutMD alg; // This should be a pass-through to IntegrateMDHistoWorkspace
+    alg.setChild(true);
+    alg.setRethrows(true);
+    alg.initialize();
+    alg.setProperty("InputWorkspace", ws);
+    const double min = 1.1;
+    const double max = 7.1; // 7.1 - 1.1 = 6
+    alg.setProperty("P1Bin", std::vector<double>(0)); // Pass through. Do not change binning.
+    alg.setProperty("P2Bin", boost::assign::list_of(min)(max).convert_to_container<std::vector<double> >());
+    alg.setPropertyValue("OutputWorkspace", "dummy");
+    alg.execute();
+    IMDWorkspace_sptr outWS=alg.getProperty("OutputWorkspace");
+
+    // Quick check that output seems to have the right shape.
+    TSM_ASSERT_EQUALS("All integrated", 10, outWS->getNPoints()); // one dimension unchanged the other integrated
+    auto intdim = outWS->getDimension(1);
+    TS_ASSERT_DELTA(min, intdim->getMinimum(), 1e-4);
+    TS_ASSERT_DELTA(max, intdim->getMaximum(), 1e-4);
+    TS_ASSERT_EQUALS(1, intdim->getNBins());
+    auto dim = outWS->getDimension(0);
+    TSM_ASSERT_DELTA("Not integrated binning should be the same as the original dimension", 0, dim->getMinimum(), 1e-4);
+    TSM_ASSERT_DELTA("Not integrated binning should be the same as the original dimension", 10, dim->getMaximum(), 1e-4);
+    TSM_ASSERT_EQUALS("Not integrated binning should be the same as the original dimension", 10, dim->getNBins());
+
+    // Check the data.
+    auto histoOutWS = boost::dynamic_pointer_cast<IMDHistoWorkspace>(outWS);
+    TS_ASSERT(histoOutWS);
+    TSM_ASSERT_DELTA("Wrong integrated value", 6.0, histoOutWS->getSignalAt(0), 1e-4);
+    TSM_ASSERT_DELTA("Wrong error value", std::sqrt(6.0 * (ws->getErrorAt(0) * ws->getErrorAt(0))), histoOutWS->getErrorAt(0), 1e-4);
+  }
 };
 
 #endif /* MANTID_MDALGORITHMS_CUTMDTEST_H_ */
diff --git a/Code/Mantid/Framework/MDAlgorithms/test/IntegrateEllipsoidsTest.h b/Code/Mantid/Framework/MDAlgorithms/test/IntegrateEllipsoidsTest.h
index bb36ebbce9d868a18c2d01b8c8090e56f4c6ebc6..108ca61408f6b54514822dfa03e4f1354d38c9d0 100644
--- a/Code/Mantid/Framework/MDAlgorithms/test/IntegrateEllipsoidsTest.h
+++ b/Code/Mantid/Framework/MDAlgorithms/test/IntegrateEllipsoidsTest.h
@@ -8,6 +8,7 @@
 #include "MantidDataObjects/PeakShapeEllipsoid.h"
 #include "MantidDataObjects/WorkspaceSingleValue.h"
 #include "MantidGeometry/Crystal/OrientedLattice.h"
+#include "MantidAPI/NumericAxis.h"
 #include <boost/make_shared.hpp>
 #include <boost/tuple/tuple.hpp>
 
@@ -79,7 +80,7 @@ createDiffractionData(const int nPixels = 100, const int nEventsPerPeak = 20,
                    tofGapBetweenEvents, eventWS, peaksWS);
   addFakeEllipsoid(V3D(1, -3, -5), nPixelsTotal, nEventsPerPeak,
                    tofGapBetweenEvents, eventWS, peaksWS);
-  addFakeEllipsoid(V3D(1, -4, -1), nPixelsTotal, nEventsPerPeak,
+  addFakeEllipsoid(V3D(1, -4, -2), nPixelsTotal, nEventsPerPeak,
                    tofGapBetweenEvents, eventWS, peaksWS);
   addFakeEllipsoid(V3D(1, -4, 0), nPixelsTotal, nEventsPerPeak,
                    tofGapBetweenEvents, eventWS, peaksWS);
@@ -200,25 +201,6 @@ public:
       TS_ASSERT_THROWS(alg.setProperty("InputWorkspace", inputWorkspaceNoInstrument), std::invalid_argument&);
   }
 
-
-  void test_event_or_workspace2d_inputs_only() {
-
-    auto otherMatrixWorkspaceInstance =
-        boost::make_shared<WorkspaceSingleValue>();
-    otherMatrixWorkspaceInstance->setInstrument(m_eventWS->getInstrument());
-
-    IntegrateEllipsoids alg;
-    alg.setChild(true);
-    alg.setRethrows(true);
-    alg.initialize();
-    alg.setProperty("InputWorkspace", otherMatrixWorkspaceInstance);
-    alg.setProperty("PeaksWorkspace", m_peaksWS);
-    alg.setPropertyValue("OutputWorkspace", "dummy");
-
-    TSM_ASSERT_THROWS("Only these two subtypes of Matrix workspace allowed",
-                     alg.execute(), std::runtime_error &);
-  }
-
   void test_execution_events() {
 
     IntegrateEllipsoids alg;
@@ -276,9 +258,8 @@ public:
           integratedPeaksWS->getPeak(1).getIntensity(), 2, 0.01);
     TSM_ASSERT_DELTA("Wrong intensity for peak 2",
           integratedPeaksWS->getPeak(2).getIntensity(), -2, 0.01);
-    //Answer is 16 on Mac ???
-    //TSM_ASSERT_DELTA("Wrong intensity for peak 3",
-          //integratedPeaksWS->getPeak(3).getIntensity(), 6, 0.01);
+    TSM_ASSERT_DELTA("Wrong intensity for peak 3",
+          integratedPeaksWS->getPeak(3).getIntensity(), 15, 0.01);
     TSM_ASSERT_DELTA("Wrong intensity for peak 4",
           integratedPeaksWS->getPeak(4).getIntensity(), 11, 0.01);
     TSM_ASSERT_DELTA("Wrong intensity for peak 5",
@@ -302,18 +283,17 @@ public:
                       integratedPeaksWS->getNumberPeaks(),
                       m_peaksWS->getNumberPeaks());
     TSM_ASSERT_DELTA("Wrong intensity for peak 0",
-          integratedPeaksWS->getPeak(0).getIntensity(), 163, 0.01);
+          integratedPeaksWS->getPeak(0).getIntensity(), 1.0, 0.01);
     TSM_ASSERT_DELTA("Wrong intensity for peak 1",
           integratedPeaksWS->getPeak(1).getIntensity(), 0, 0.01);
     TSM_ASSERT_DELTA("Wrong intensity for peak 2",
-          integratedPeaksWS->getPeak(2).getIntensity(), 163, 0.01);
-    //Answer is 951 on Mac ???
-    //TSM_ASSERT_DELTA("Wrong intensity for peak 3",
-          //integratedPeaksWS->getPeak(3).getIntensity(), 711, 0.01);
+          integratedPeaksWS->getPeak(2).getIntensity(), 1.0, 0.01);
+    TSM_ASSERT_DELTA("Wrong intensity for peak 3",
+          integratedPeaksWS->getPeak(3).getIntensity(), 10, 0.01);
     TSM_ASSERT_DELTA("Wrong intensity for peak 4",
-          integratedPeaksWS->getPeak(4).getIntensity(), 694, 0.01);
+          integratedPeaksWS->getPeak(4).getIntensity(), 13, 0.01);
     TSM_ASSERT_DELTA("Wrong intensity for peak 5",
-          integratedPeaksWS->getPeak(5).getIntensity(), 218, 0.01);
+          integratedPeaksWS->getPeak(5).getIntensity(), 12, 0.01);
 
   }
 };
diff --git a/Code/Mantid/Framework/MDAlgorithms/test/IntegrateMDHistoWorkspaceTest.h b/Code/Mantid/Framework/MDAlgorithms/test/IntegrateMDHistoWorkspaceTest.h
new file mode 100644
index 0000000000000000000000000000000000000000..54ad6af8eea1365dde91df51054c36150082432f
--- /dev/null
+++ b/Code/Mantid/Framework/MDAlgorithms/test/IntegrateMDHistoWorkspaceTest.h
@@ -0,0 +1,440 @@
+#ifndef MANTID_MDALGORITHMS_INTEGRATEMDHISTOWORKSPACETEST_H_
+#define MANTID_MDALGORITHMS_INTEGRATEMDHISTOWORKSPACETEST_H_
+
+#include <cxxtest/TestSuite.h>
+#include <boost/assign/list_of.hpp>
+
+#include "MantidMDAlgorithms/IntegrateMDHistoWorkspace.h"
+#include "MantidDataObjects/MDEventWorkspace.h"
+#include "MantidTestHelpers/MDEventsTestHelper.h"
+
+using Mantid::MDAlgorithms::IntegrateMDHistoWorkspace;
+using namespace Mantid::API;
+
+//=====================================================================================
+// Functional Tests
+//=====================================================================================
+class IntegrateMDHistoWorkspaceTest : public CxxTest::TestSuite
+{
+public:
+  // This pair of boilerplate methods prevent the suite being created statically
+  // This means the constructor isn't called when running other tests
+  static IntegrateMDHistoWorkspaceTest *createSuite() { return new IntegrateMDHistoWorkspaceTest(); }
+  static void destroySuite( IntegrateMDHistoWorkspaceTest *suite ) { delete suite; }
+
+
+  void test_Init()
+  {
+    IntegrateMDHistoWorkspace alg;
+    TS_ASSERT_THROWS_NOTHING( alg.initialize() );
+    TS_ASSERT( alg.isInitialized() );
+  }
+
+  void test_throw_if_new_steps_in_binning()
+  {
+    using namespace Mantid::DataObjects;
+    MDHistoWorkspace_sptr ws = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 1 /*nd*/, 10);
+
+    IntegrateMDHistoWorkspace alg;
+    alg.setChild(true);
+    alg.setRethrows(true);
+    alg.initialize();
+    alg.setProperty("InputWorkspace", ws);
+    const double step = 0.1;
+    alg.setProperty("P1Bin", boost::assign::list_of(0.0)(step)(1.0).convert_to_container<std::vector<double> >());
+    alg.setPropertyValue("OutputWorkspace", "dummy");
+    TSM_ASSERT("Expect validation errors", alg.validateInputs().size() > 0);
+    TSM_ASSERT_THROWS("No new steps allowed", alg.execute(), std::runtime_error&);
+  }
+
+  void test_throw_if_incorrect_binning_limits_when_integrating()
+  {
+    using namespace Mantid::DataObjects;
+    MDHistoWorkspace_sptr ws = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 1 /*nd*/, 10);
+
+    IntegrateMDHistoWorkspace alg;
+    alg.setChild(true);
+    alg.setRethrows(true);
+    alg.initialize();
+    alg.setProperty("InputWorkspace", ws);
+    alg.setPropertyValue("OutputWorkspace", "dummy");
+
+    const double min = 3;
+
+    // Test equal to
+    double max = min;
+    alg.setProperty("P1Bin", boost::assign::list_of(min)(max).convert_to_container<std::vector<double> >());
+    TSM_ASSERT("Expect validation errors", alg.validateInputs().size() > 0);
+    TSM_ASSERT_THROWS("Incorrect limits", alg.execute(), std::runtime_error&);
+
+    // Test less than
+    max = min - 0.01;
+    alg.setProperty("P1Bin", boost::assign::list_of(min)(max).convert_to_container<std::vector<double> >());
+    TSM_ASSERT("Expect validation errors", alg.validateInputs().size() > 0);
+    TSM_ASSERT_THROWS("Incorrect limits", alg.execute(), std::runtime_error&);
+  }
+
+  void test_throw_if_incorrect_binning_limits_when_similar()
+  {
+    using namespace Mantid::DataObjects;
+    MDHistoWorkspace_sptr ws = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 1 /*nd*/, 10);
+
+    IntegrateMDHistoWorkspace alg;
+    alg.setChild(true);
+    alg.setRethrows(true);
+    alg.initialize();
+    alg.setProperty("InputWorkspace", ws);
+    alg.setPropertyValue("OutputWorkspace", "dummy");
+
+    const double min = 3;
+    double step = 0;
+    // Test equal to
+    double max = min;
+    alg.setProperty("P1Bin", boost::assign::list_of(min)(step)(max).convert_to_container<std::vector<double> >());
+    TSM_ASSERT("Expect validation errors", alg.validateInputs().size() > 0);
+    TSM_ASSERT_THROWS("Incorrect limits", alg.execute(), std::runtime_error&);
+
+    // Test less than
+    max = min - 0.01;
+    alg.setProperty("P1Bin", boost::assign::list_of(min)(step)(max).convert_to_container<std::vector<double> >());
+    TSM_ASSERT("Expect validation errors", alg.validateInputs().size() > 0);
+    TSM_ASSERT_THROWS("Incorrect limits", alg.execute(), std::runtime_error&);
+
+    // Test non-zero step. ZERO means copy!
+    max = min - 0.01;
+    alg.setProperty("P1Bin", boost::assign::list_of(min)(1.0)(max).convert_to_container<std::vector<double> >());
+    TSM_ASSERT("Expect validation errors", alg.validateInputs().size() > 0);
+    TSM_ASSERT_THROWS("Step has been specified", alg.execute(), std::runtime_error&);
+  }
+
+  // Users may set all binning parameter to [] i.e. direct copy, no integration.
+  void test_exec_do_nothing_but_clone()
+  {
+    using namespace Mantid::DataObjects;
+    MDHistoWorkspace_sptr ws = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 1 /*nd*/, 10);
+
+    IntegrateMDHistoWorkspace alg;
+    alg.setChild(true);
+    alg.setRethrows(true);
+    alg.initialize();
+    alg.setProperty("InputWorkspace", ws);
+    alg.setPropertyValue("OutputWorkspace", "dummy");
+    alg.execute();
+    IMDHistoWorkspace_sptr outWS=alg.getProperty("OutputWorkspace");
+
+    // Quick check that output seems to be a copy of input.
+    TS_ASSERT_EQUALS(outWS->getNPoints(), ws->getNPoints());
+    TS_ASSERT_EQUALS(outWS->getNumDims(), ws->getNumDims());
+    TS_ASSERT_EQUALS(outWS->getSignalAt(0), ws->getSignalAt(0));
+    TS_ASSERT_EQUALS(outWS->getSignalAt(1), ws->getSignalAt(1));
+  }
+
+  void test_1D_integration_exact_binning()
+  {
+
+      /*
+
+                           input
+      (x = 0) *|--|--|--|--|--|--|--|--|--|--|* (x = 10)
+                1  1  1  1  1  1  1  1  1  1
+
+                  output requested
+
+      (x = 0) *|--------------|* (x = 5)
+                1 + 1 + 1 + 1 + 1 = 5 counts
+
+      */
+
+      using namespace Mantid::DataObjects;
+      MDHistoWorkspace_sptr ws = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0 /*signal*/, 1 /*nd*/, 10 /*nbins*/, 10 /*max*/, 1.0 /*error sq*/);
+
+      IntegrateMDHistoWorkspace alg;
+      alg.setChild(true);
+      alg.setRethrows(true);
+      alg.initialize();
+      alg.setProperty("InputWorkspace", ws);
+      const double min = 0;
+      const double max = 5;
+      alg.setProperty("P1Bin", boost::assign::list_of(min)(max).convert_to_container<std::vector<double> >());
+      alg.setPropertyValue("OutputWorkspace", "dummy");
+      alg.execute();
+      IMDHistoWorkspace_sptr outWS=alg.getProperty("OutputWorkspace");
+
+      // Quick check that output seems to have the right shape.
+      TSM_ASSERT_EQUALS("All integrated", 1, outWS->getNPoints());
+      auto dim = outWS->getDimension(0);
+      TS_ASSERT_EQUALS(min, dim->getMinimum());
+      TS_ASSERT_EQUALS(max, dim->getMaximum());
+
+      // Check the data.
+      TSM_ASSERT_DELTA("Wrong integrated value", 5.0, outWS->getSignalAt(0), 1e-4);
+      TSM_ASSERT_DELTA("Wrong error value", std::sqrt(5 * (ws->getErrorAt(0) * ws->getErrorAt(0))), outWS->getErrorAt(0), 1e-4);
+  }
+
+
+  void test_1D_integration_partial_binning_complex(){
+
+      /*
+
+                           input
+      (x = 0) *|--|--|--|--|--|--|--|--|--|--|* (x = 10)
+                1  1  1  1  1  1  1  1  1  1
+
+                  output requested
+
+      (x = 0.75) *|--------------|* (x = 4.25)
+                1/4 + 1 + 1 + 1 + 1/4 = 3.5 counts
+
+      */
+
+
+      using namespace Mantid::DataObjects;
+      MDHistoWorkspace_sptr ws = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0 /*signal*/, 1 /*nd*/, 10 /*nbins*/, 10 /*max*/, 1.0 /*error sq*/);
+
+      IntegrateMDHistoWorkspace alg;
+      alg.setChild(true);
+      alg.setRethrows(true);
+      alg.initialize();
+      alg.setProperty("InputWorkspace", ws);
+      const double min = 0.75;
+      const double max = 4.25;
+      alg.setProperty("P1Bin", boost::assign::list_of(min)(max).convert_to_container<std::vector<double> >());
+      alg.setPropertyValue("OutputWorkspace", "dummy");
+      alg.execute();
+      IMDHistoWorkspace_sptr outWS=alg.getProperty("OutputWorkspace");
+
+      // Quick check that output seems to have the right shape.
+      TSM_ASSERT_EQUALS("All integrated", 1, outWS->getNPoints());
+      auto dim = outWS->getDimension(0);
+      TS_ASSERT_EQUALS(min, dim->getMinimum());
+      TS_ASSERT_EQUALS(max, dim->getMaximum());
+
+      // Check the data.
+      TSM_ASSERT_DELTA("Wrong integrated value", 3.5, outWS->getSignalAt(0), 1e-4);
+      TSM_ASSERT_DELTA("Wrong error value", std::sqrt(3.5 * (ws->getErrorAt(0) * ws->getErrorAt(0))), outWS->getErrorAt(0), 1e-4);
+  }
+
+  void test_1D_integration_with_original_step_and_forbidden_partial_binning(){
+
+      /*
+
+                           input
+      (x = 0) *|--|--|--|--|--|--|--|--|--|--|* (x = 10)
+                1  1  1  1  1  1  1  1  1  1
+
+                  output requested, but partial bins are forbidden so round to the nearest bin edges
+
+      (x = 0.75) *|--------------|* (x = 4.25)
+                1/4 , 1 , 1 , 1 , 1/4
+
+                  output with rounding (maintain closest possible bin boundaries. no partial binning)
+
+      (x = 0) *|--------------------|* (x = 5)
+                 1 , 1 , 1 , 1 , 1, 1
+
+      */
+
+
+      using namespace Mantid::DataObjects;
+      MDHistoWorkspace_sptr ws = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0 /*signal*/, 1 /*nd*/, 10 /*nbins*/, 10 /*max*/, 1.0 /*error sq*/);
+
+      IntegrateMDHistoWorkspace alg;
+      alg.setChild(true);
+      alg.setRethrows(true);
+      alg.initialize();
+      alg.setProperty("InputWorkspace", ws);
+      const double min = 0.75;
+      const double max = 4.25;
+      alg.setProperty("P1Bin", boost::assign::list_of(min)(0.0)(max).convert_to_container<std::vector<double> >());
+      alg.setPropertyValue("OutputWorkspace", "dummy");
+      alg.execute();
+      IMDHistoWorkspace_sptr outWS=alg.getProperty("OutputWorkspace");
+
+      // Quick check that output seems to have the right shape.
+      TSM_ASSERT_EQUALS("Should have rounded to whole widths.", 5, outWS->getNPoints());
+      auto outDim = outWS->getDimension(0);
+      auto inDim = ws->getDimension(0);
+      TS_ASSERT_EQUALS(0.0f, outDim->getMinimum());
+      TS_ASSERT_EQUALS(5.0f, outDim->getMaximum());
+      TSM_ASSERT_EQUALS("Bin width should be unchanged", inDim->getBinWidth(), outDim->getBinWidth());
+
+      // Check the data.
+      TSM_ASSERT_DELTA("Wrong value", 1.0, outWS->getSignalAt(0), 1e-4);
+      TSM_ASSERT_DELTA("Wrong value", 1.0, outWS->getSignalAt(1), 1e-4);
+      TSM_ASSERT_DELTA("Wrong value", 1.0, outWS->getSignalAt(2), 1e-4);
+      TSM_ASSERT_DELTA("Wrong value", 1.0, outWS->getSignalAt(3), 1e-4);
+      TSM_ASSERT_DELTA("Wrong value", 1.0, outWS->getSignalAt(4), 1e-4);
+
+   }
+
+  void test_2d_partial_binning() {
+
+    /*
+
+      Input filled with 1's binning = 1 in each dimension
+      ----------------------------- (10, 10)
+      |                           |
+      |                           |
+      |                           |
+      |                           |
+      |                           |
+      |                           |
+      |                           |
+      |                           |
+      |                           |
+      |                           |
+      -----------------------------
+    (0, 0)
+
+
+      Slice. Two vertical columns. Each 1 in width.
+
+      ----------------------------- (10, 10)
+      |                           |
+      |                           |
+      |__________________________ | (10, 7.1)
+      |    |    |   ...           |
+      |    |    |                 |
+      |    |    |                 |
+      |    |    |                 |
+      |    |    |                 |
+      |__________________________ | (10, 1.1)
+      |                           |
+      -----------------------------
+    (0, 0)
+
+    */
+
+    using namespace Mantid::DataObjects;
+    MDHistoWorkspace_sptr ws = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0 /*signal*/, 2 /*nd*/, 10 /*nbins*/, 10 /*max*/, 1.0 /*error sq*/);
+
+    IntegrateMDHistoWorkspace alg;
+    alg.setChild(true);
+    alg.setRethrows(true);
+    alg.initialize();
+    alg.setProperty("InputWorkspace", ws);
+    const double min = 1.1;
+    const double max = 7.1; // 7.1 - 1.1 = 6
+    alg.setProperty("P1Bin", std::vector<double>(0)); // Pass through. Do not change binning.
+    alg.setProperty("P2Bin", boost::assign::list_of(min)(max).convert_to_container<std::vector<double> >());
+    alg.setPropertyValue("OutputWorkspace", "dummy");
+    alg.execute();
+    IMDHistoWorkspace_sptr outWS=alg.getProperty("OutputWorkspace");
+
+    // Quick check that output seems to have the right shape.
+    TSM_ASSERT_EQUALS("All integrated", 10, outWS->getNPoints()); // one dimension unchanged the other integrated
+    auto intdim = outWS->getDimension(1);
+    TS_ASSERT_DELTA(min, intdim->getMinimum(), 1e-4);
+    TS_ASSERT_DELTA(max, intdim->getMaximum(), 1e-4);
+    TS_ASSERT_EQUALS(1, intdim->getNBins());
+    auto dim = outWS->getDimension(0);
+    TSM_ASSERT_DELTA("Not integrated binning should be the same as the original dimension", 0, dim->getMinimum(), 1e-4);
+    TSM_ASSERT_DELTA("Not integrated binning should be the same as the original dimension", 10, dim->getMaximum(), 1e-4);
+    TSM_ASSERT_EQUALS("Not integrated binning should be the same as the original dimension", 10, dim->getNBins());
+
+    // Check the data.
+    TSM_ASSERT_DELTA("Wrong integrated value", 6.0, outWS->getSignalAt(0), 1e-4);
+    TSM_ASSERT_DELTA("Wrong error value", std::sqrt(6.0 * (ws->getErrorAt(0) * ws->getErrorAt(0))), outWS->getErrorAt(0), 1e-4);
+  }
+
+  void test_update_n_events_for_normalization() {
+
+      /*
+                    input
+      (x = 0) *|--|--|--|--|--|--|--|--|--|--|* (x = 10)
+                1  2  3  4  5  6  7  8  9  10    (signal values in bins)
+                1  2  3  4  5  6  7  8  9  10    (n_events in bins)
+
+                  output requested
+
+      (x = 0.75) *|--------------|* (x = 4.25)
+                1/4 , 1 , 1 , 1 , 1/4 = weights based on fraction overlap
+                1/4 + 2 + 3 + 4 + 5/4  (signal values in bins)
+                1/4 + 2 + 3 + 4 + 5/4  (n_events in bins)
+
+
+      */
+
+
+      using namespace Mantid::DataObjects;
+      MDHistoWorkspace_sptr ws = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0 /*signal*/, 1 /*nd*/, 10 /*nbins*/, 10 /*max*/, 1.0 /*error sq*/);
+      // Fill signal and n-events as above
+      for(size_t i = 0; i < ws->getNPoints(); ++i) {
+        ws->setSignalAt(i, Mantid::signal_t(i+1));
+        ws->setNumEventsAt(i, Mantid::signal_t(i+1));
+        std::cout << "signal " << i+1 <<  "\t" << "nevents" <<  "\t" << "at" << "\t" << i << std::endl;
+      }
+
+      IntegrateMDHistoWorkspace alg;
+      alg.setChild(true);
+      alg.setRethrows(true);
+      alg.initialize();
+      alg.setProperty("InputWorkspace", ws);
+      const double min = 0.75;
+      const double max = 4.25;
+      alg.setProperty("P1Bin", boost::assign::list_of(min)(max).convert_to_container<std::vector<double> >());
+      alg.setPropertyValue("OutputWorkspace", "dummy");
+      alg.execute();
+      IMDHistoWorkspace_sptr outWS=alg.getProperty("OutputWorkspace");
+
+      // Quick check that output seems to have the right shape.
+      TSM_ASSERT_EQUALS("All integrated", 1, outWS->getNPoints());
+      auto dim = outWS->getDimension(0);
+      TS_ASSERT_EQUALS(min, dim->getMinimum());
+      TS_ASSERT_EQUALS(max, dim->getMaximum());
+
+      // Check the data. No accounting for normalization.
+      TSM_ASSERT_DELTA("Wrong integrated value", 1.0/4 + 2 + 3 + 4 + 5.0/4, outWS->getSignalAt(0), 1e-4);
+
+      Mantid::coord_t point[1] = {3.0}; // Roughly centre of the single output bin
+      TSM_ASSERT_DELTA("Number of events normalization. Weights for n-events used incorrectly.", 1.0, outWS->getSignalAtCoord(point, Mantid::API::NumEventsNormalization), 1e-4);
+      
+  }
+
+
+};
+
+//=====================================================================================
+// Performance Tests
+//=====================================================================================
+using namespace Mantid::DataObjects;
+class IntegrateMDHistoWorkspaceTestPerformance : public CxxTest::TestSuite
+{
+
+private:
+
+  MDHistoWorkspace_sptr m_ws;
+
+public:
+  // This pair of boilerplate methods prevent the suite being created statically
+  // This means the constructor isn't called when running other tests
+  static IntegrateMDHistoWorkspaceTestPerformance *createSuite() { return new IntegrateMDHistoWorkspaceTestPerformance(); }
+  static void destroySuite( IntegrateMDHistoWorkspaceTestPerformance *suite ) { delete suite; }
+
+  IntegrateMDHistoWorkspaceTestPerformance() {
+      // Create a 4D workspace.
+      m_ws = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0 /*signal*/, 4 /*nd*/, 100 /*nbins*/, 10 /*max*/, 1.0 /*error sq*/);
+  }
+
+  void test_execute_4d()
+  {
+      IntegrateMDHistoWorkspace alg;
+      alg.setChild(true);
+      alg.setRethrows(true);
+      alg.initialize();
+      const double min = 0;
+      const double max = 1;
+      alg.setProperty("InputWorkspace", m_ws);
+      alg.setProperty("P1Bin", boost::assign::list_of(min)(max).convert_to_container<std::vector<double> >());
+      alg.setProperty("P2Bin", boost::assign::list_of(min)(max).convert_to_container<std::vector<double> >());
+      alg.setProperty("P3Bin", boost::assign::list_of(min)(max).convert_to_container<std::vector<double> >());
+      alg.setProperty("P4Bin", boost::assign::list_of(min)(max).convert_to_container<std::vector<double> >());
+      alg.setPropertyValue("OutputWorkspace", "dummy");
+      alg.execute();
+      IMDHistoWorkspace_sptr outWS=alg.getProperty("OutputWorkspace");
+      TS_ASSERT(outWS);
+  }
+
+};
+
+#endif /* MANTID_MDALGORITHMS_INTEGRATEMDHISTOWORKSPACETEST_H_ */
diff --git a/Code/Mantid/Framework/MDAlgorithms/test/LoadMDTest.h b/Code/Mantid/Framework/MDAlgorithms/test/LoadMDTest.h
index 25c23a4ac3cf6d4ec05be270cc249fef0e99da82..e9502cb8cee42d98670daae6965416016807d104 100644
--- a/Code/Mantid/Framework/MDAlgorithms/test/LoadMDTest.h
+++ b/Code/Mantid/Framework/MDAlgorithms/test/LoadMDTest.h
@@ -2,6 +2,7 @@
 #define MANTID_MDALGORITHMS_LOADMDEWTEST_H_
 
 #include "SaveMDTest.h"
+#include "SaveMD2Test.h"
 
 #include "MantidAPI/IMDEventWorkspace.h"
 #include "MantidAPI/ExperimentInfo.h"
@@ -196,7 +197,7 @@ public:
     ws1->addExperimentInfo(ei);
 
     // -------- Save it ---------------
-    SaveMD saver;
+    SaveMD2 saver;
     TS_ASSERT_THROWS_NOTHING( saver.initialize() )
     TS_ASSERT( saver.isInitialized() )
     TS_ASSERT_THROWS_NOTHING( saver.setProperty("InputWorkspace", "LoadMDTest_ws" ) );
@@ -319,7 +320,7 @@ public:
 
     // There are some new boxes that are not cached to disk at this point.
     // Save it again.
-    SaveMD saver;
+    SaveMD2 saver;
     TS_ASSERT_THROWS_NOTHING( saver.initialize() )
     TS_ASSERT( saver.isInitialized() )
     TS_ASSERT_THROWS_NOTHING( saver.setPropertyValue("InputWorkspace", outWSName ) );
@@ -429,7 +430,7 @@ public:
     AnalysisDataService::Instance().addOrReplace("LoadMDTest_ws", boost::dynamic_pointer_cast<IMDEventWorkspace>(ws1));
 
     // Save it
-    SaveMD saver;
+    SaveMD2 saver;
     TS_ASSERT_THROWS_NOTHING( saver.initialize() )
     TS_ASSERT( saver.isInitialized() )
     TS_ASSERT_THROWS_NOTHING( saver.setProperty("InputWorkspace", "LoadMDTest_ws" ) );
@@ -470,14 +471,52 @@ public:
 
   }
 
+  /** Run SaveMD v1 with the MDHistoWorkspace */
+  void doTestHistoV1(MDHistoWorkspace_sptr ws)
+  {
+    std::string filename = "SaveMDTestHisto.nxs";
+
+    SaveMD alg1;
+    TS_ASSERT_THROWS_NOTHING( alg1.initialize() )
+    TS_ASSERT( alg1.isInitialized() )
+    TS_ASSERT_THROWS_NOTHING( alg1.setProperty("InputWorkspace", ws) );
+    TS_ASSERT_THROWS_NOTHING( alg1.setPropertyValue("Filename", filename) );
+    alg1.execute();
+    TS_ASSERT( alg1.isExecuted() );
+    filename = alg1.getPropertyValue("Filename");
+
+    LoadMD alg;
+    TS_ASSERT_THROWS_NOTHING( alg.initialize() )
+    TS_ASSERT( alg.isInitialized() )
+    TS_ASSERT_THROWS_NOTHING( alg.setPropertyValue("Filename", filename) );
+    TS_ASSERT_THROWS_NOTHING( alg.setPropertyValue("OutputWorkspace", "loaded") );
+    TS_ASSERT_THROWS_NOTHING( alg.execute(); );
+    TS_ASSERT( alg.isExecuted() );
 
+    MDHistoWorkspace_sptr newWS;
+    TS_ASSERT_THROWS_NOTHING( newWS = AnalysisDataService::Instance().retrieveWS<MDHistoWorkspace>("loaded") );
+    TS_ASSERT(newWS); if (!newWS) return;
 
-  /** Run SaveMD with the MDHistoWorkspace */
+    TS_ASSERT_EQUALS( ws->getNPoints(), newWS->getNPoints());
+    TS_ASSERT_EQUALS( ws->getNumDims(), newWS->getNumDims());
+    for (size_t i=0; i<ws->getNPoints(); i++)
+    {
+      TS_ASSERT_DELTA(ws->getSignalAt(i), newWS->getSignalAt(i), 1e-6);
+      TS_ASSERT_DELTA(ws->getErrorAt(i), newWS->getErrorAt(i), 1e-6);
+      TS_ASSERT_DELTA(ws->getNumEventsAt(i), newWS->getNumEventsAt(i), 1e-6);
+      TS_ASSERT_EQUALS(ws->getIsMaskedAt(i), newWS->getIsMaskedAt(i));
+    }
+
+    if (Poco::File(filename).exists())
+      Poco::File(filename).remove();
+  }
+
+  /** Run SaveMD2 with the MDHistoWorkspace */
   void doTestHisto(MDHistoWorkspace_sptr ws)
   {
-    std::string filename = "SaveMDTestHisto.nxs";
+    std::string filename = "SaveMD2TestHisto.nxs";
 
-    SaveMD alg1;
+    SaveMD2 alg1;
     TS_ASSERT_THROWS_NOTHING( alg1.initialize() )
     TS_ASSERT( alg1.isInitialized() )
     TS_ASSERT_THROWS_NOTHING( alg1.setProperty("InputWorkspace", ws) );
@@ -515,12 +554,14 @@ public:
   void test_histo2() 
   {
     MDHistoWorkspace_sptr ws = MDEventsTestHelper::makeFakeMDHistoWorkspace(2.5, 2, 10, 10.0, 3.5, "histo2", 4.5);
+    doTestHistoV1(ws);
     doTestHisto(ws);
   }
 
   void test_histo3()
   {
     MDHistoWorkspace_sptr ws = MDEventsTestHelper::makeFakeMDHistoWorkspace(2.5, 3, 4, 10.0, 3.5, "histo3", 4.5);
+    doTestHistoV1(ws);
     doTestHisto(ws);
   }
 
@@ -600,7 +641,7 @@ public:
                            const char *rootGroup,
                            const bool rmCoordField = false) {
     const std::string fileName = "SaveMDSpecialCoordinatesTest.nxs";
-    SaveMD saveAlg;
+    SaveMD2 saveAlg;
     saveAlg.setChild(true);
     saveAlg.initialize();
     saveAlg.setProperty("InputWorkspace", inputWS);
@@ -661,7 +702,7 @@ public:
     balg.setProperty("AlignedDim3", "Axis3,0,10,2");
     balg.execute();
 
-    SaveMD alg;
+    SaveMD2 alg;
     alg.initialize();
     alg.setPropertyValue("InputWorkspace", "SaveMDAffineTestHisto_ws");
     alg.setPropertyValue("Filename", filename);
diff --git a/Code/Mantid/Framework/MDAlgorithms/test/SaveMD2Test.h b/Code/Mantid/Framework/MDAlgorithms/test/SaveMD2Test.h
new file mode 100644
index 0000000000000000000000000000000000000000..f482b9ddee328185ada20b7331330a0837ce9eb6
--- /dev/null
+++ b/Code/Mantid/Framework/MDAlgorithms/test/SaveMD2Test.h
@@ -0,0 +1,298 @@
+#ifndef MANTID_MDEVENTS_SAVEMD2EWTEST_H_
+#define MANTID_MDEVENTS_SAVEMD2EWTEST_H_
+
+#include "MantidAPI/IMDEventWorkspace.h"
+#include "MantidAPI/FrameworkManager.h"
+#include "MantidDataObjects/MDEventFactory.h"
+#include "MantidMDAlgorithms/BinMD.h"
+#include "MantidMDAlgorithms/SaveMD2.h"
+#include "MantidTestHelpers/MDEventsTestHelper.h"
+
+#include <cxxtest/TestSuite.h>
+
+#include <Poco/File.h>
+
+using namespace Mantid::API;
+using namespace Mantid::DataObjects;
+using namespace Mantid::MDAlgorithms;
+
+class SaveMD2Tester: public SaveMD2
+{
+public:
+  void saveExperimentInfos(::NeXus::File * const file, IMDEventWorkspace_const_sptr ws)
+  {
+    this->saveExperimentInfos(file, ws);
+  }
+};
+
+/** Note: See the LoadMDTest class
+ * for a more thorough test that does
+ * a round-trip.
+ */
+class SaveMD2Test : public CxxTest::TestSuite
+{
+public:
+
+    
+  void test_Init()
+  {
+    SaveMD2 alg;
+    TS_ASSERT_THROWS_NOTHING( alg.initialize() )
+    TS_ASSERT( alg.isInitialized() )
+  }
+  
+  void test_exec()
+  {
+    do_test_exec(23, "SaveMD2Test.nxs");
+  }
+
+  void test_exec_noEvents()
+  {
+    do_test_exec(0, "SaveMD2Test_noEvents.nxs");
+  }
+
+  void test_MakeFileBacked()
+  {
+    do_test_exec(23, "SaveMD2Test.nxs", true);
+  }
+
+  void test_MakeFileBacked_then_UpdateFileBackEnd()
+  {
+    do_test_exec(23, "SaveMD2Test_updating.nxs", true, true);
+  }
+
+
+  void do_test_exec(size_t numPerBox, std::string filename, bool MakeFileBacked = false, bool UpdateFileBackEnd = false)
+  {
+   
+    // Make a 1D MDEventWorkspace
+    MDEventWorkspace1Lean::sptr ws = MDEventsTestHelper::makeMDEW<1>(10, 0.0, 10.0, numPerBox);
+    // Make sure it is split
+    ws->splitBox();
+
+    AnalysisDataService::Instance().addOrReplace("SaveMD2Test_ws", ws);
+
+    ws->refreshCache();
+
+    // There are this many boxes, so this is the max ID.
+    TS_ASSERT_EQUALS( ws->getBoxController()->getMaxId(), 11);
+
+    IMDEventWorkspace_sptr iws = ws;
+
+    SaveMD2 alg;
+    TS_ASSERT_THROWS_NOTHING( alg.initialize() )
+    TS_ASSERT( alg.isInitialized() )
+    TS_ASSERT_THROWS_NOTHING( alg.setPropertyValue("InputWorkspace", "SaveMD2Test_ws") );
+    TS_ASSERT_THROWS_NOTHING( alg.setPropertyValue("Filename", filename) );
+    TS_ASSERT_THROWS_NOTHING( alg.setProperty("MakeFileBacked", MakeFileBacked) );
+
+    // clean up possible rubbish from the previous runs
+    std::string fullName = alg.getPropertyValue("Filename");
+    if (fullName!="")
+      if(Poco::File(fullName).exists()) Poco::File(fullName).remove();
+
+    alg.execute();
+    TS_ASSERT( alg.isExecuted() );
+
+    std::string this_filename = alg.getProperty("Filename");
+    TSM_ASSERT( "File was indeed created", Poco::File(this_filename).exists());
+
+    if (MakeFileBacked)
+    {
+      TSM_ASSERT("Workspace was made file-backed", ws->isFileBacked() );
+      TSM_ASSERT("File back-end no longer needs updating.", !ws->fileNeedsUpdating() );
+    }
+
+    // Continue the test
+    if (UpdateFileBackEnd)
+      do_test_UpdateFileBackEnd(ws, filename);
+    else
+    {
+
+      ws->clearFileBacked(false);
+      if (Poco::File(this_filename).exists()) Poco::File(this_filename).remove();
+    }
+
+  }
+  
+  /// Add some data and update the back-end
+  void do_test_UpdateFileBackEnd(MDEventWorkspace1Lean::sptr ws,  std::string filename)
+  {
+    size_t initial_numEvents = ws->getNPoints();
+    TSM_ASSERT_EQUALS("Starting off with 230 events.", initial_numEvents, 230);
+
+    // Add 100 events
+    for (size_t i=0; i<100; i++)
+    {
+      MDLeanEvent<1> ev(1.0, 1.0);
+      ev.setCenter(0, double(i) * 0.01 + 0.4);
+      ws->addEvent(ev);
+    }
+    ws->splitAllIfNeeded(NULL);
+    ws->refreshCache();
+    // Manually set the flag that the algo would set
+    ws->setFileNeedsUpdating(true);
+
+    TSM_ASSERT_EQUALS("Correctly added 100 events to original 230.",  ws->getNPoints(), 230+100);
+
+    SaveMD2 alg;
+    TS_ASSERT_THROWS_NOTHING( alg.initialize() )
+    TS_ASSERT( alg.isInitialized() )
+    TS_ASSERT_THROWS_NOTHING( alg.setPropertyValue("InputWorkspace", "SaveMD2Test_ws") );
+    TS_ASSERT_THROWS_NOTHING( alg.setPropertyValue("Filename", filename) );
+    TS_ASSERT_THROWS_NOTHING( alg.setProperty("UpdateFileBackEnd", true) );
+    alg.execute();
+    TS_ASSERT( alg.isExecuted() );
+
+    // Since there are 330 events, the file needs to be that big (or bigger).
+    TS_ASSERT_LESS_THAN( 330, ws->getBoxController()->getFileIO()->getFileLength());
+
+    TSM_ASSERT("File back-end no longer needs updating.", !ws->fileNeedsUpdating() );
+    // Clean up file
+    ws->clearFileBacked(false);
+    std::string fullPath = alg.getPropertyValue("Filename");
+    if (Poco::File(fullPath).exists()) Poco::File(fullPath).remove();
+  }
+
+  void test_saveExpInfo()
+  {
+    std::string filename("MultiExperSaveMD2Test.nxs");
+    // Make a 1D MDEventWorkspace
+    MDEventWorkspace1Lean::sptr ws = MDEventsTestHelper::makeMDEW<1>(10, 0.0, 10.0, 2);
+    // Make sure it is split
+    ws->splitBox();
+
+    Mantid::Geometry::Goniometer gon;
+    gon.pushAxis("Psi",0,1,0);
+    // add experiment infos 
+    for(int i=0;i<80;i++)
+    {
+      ExperimentInfo_sptr ei = boost::shared_ptr<ExperimentInfo>(new ExperimentInfo());
+      ei->mutableRun().addProperty("Psi",double(i));
+      ei->mutableRun().addProperty("Ei",400.);
+      ei->mutableRun().setGoniometer(gon,true);
+      ws->addExperimentInfo(ei);
+    }
+
+    AnalysisDataService::Instance().addOrReplace("SaveMD2Test_ws", ws);
+
+    ws->refreshCache();
+
+    // There are this many boxes, so this is the max ID.
+    TS_ASSERT_EQUALS( ws->getBoxController()->getMaxId(), 11);
+
+    IMDEventWorkspace_sptr iws = ws;
+
+    SaveMD2 alg;
+    TS_ASSERT_THROWS_NOTHING( alg.initialize() )
+    TS_ASSERT( alg.isInitialized() )
+    TS_ASSERT_THROWS_NOTHING( alg.setPropertyValue("InputWorkspace", "SaveMD2Test_ws") );
+    TS_ASSERT_THROWS_NOTHING( alg.setPropertyValue("Filename", filename) );
+    TS_ASSERT_THROWS_NOTHING( alg.setProperty("MakeFileBacked","0") );
+    alg.execute();
+    TS_ASSERT( alg.isExecuted() );
+    std::string this_filename = alg.getProperty("Filename");
+    ws->clearFileBacked(false);
+    if (Poco::File(this_filename).exists()) Poco::File(this_filename).remove();
+
+  }
+
+  void test_saveAffine()
+  {
+    std::string filename("MDAffineSaveMD2Test.nxs");
+    // Make a 4D MDEventWorkspace
+    MDEventWorkspace4Lean::sptr ws = MDEventsTestHelper::makeMDEW<4>(10, 0.0, 10.0, 2);
+    AnalysisDataService::Instance().addOrReplace("SaveMD2Test_ws", ws);
+
+    // Bin data to get affine matrix
+    BinMD balg;
+    balg.initialize();
+    balg.setProperty("InputWorkspace", "SaveMD2Test_ws");
+    balg.setProperty("OutputWorkspace", "SaveMD2TestHisto_ws");
+    balg.setProperty("AlignedDim0", "Axis2,0,10,10");
+    balg.setProperty("AlignedDim1", "Axis0,0,10,5");
+    balg.setProperty("AlignedDim2", "Axis1,0,10,5");
+    balg.setProperty("AlignedDim3", "Axis3,0,10,2");
+    balg.execute();
+
+    SaveMD2 alg;
+    TS_ASSERT_THROWS_NOTHING( alg.initialize() )
+    TS_ASSERT( alg.isInitialized() )
+    TS_ASSERT_THROWS_NOTHING( alg.setPropertyValue("InputWorkspace", "SaveMD2TestHisto_ws") );
+    TS_ASSERT_THROWS_NOTHING( alg.setPropertyValue("Filename", filename) );
+    TS_ASSERT_THROWS_NOTHING( alg.setProperty("MakeFileBacked","0") );
+    alg.execute();
+    TS_ASSERT( alg.isExecuted() );
+    std::string this_filename = alg.getProperty("Filename");
+    ws->clearFileBacked(false);
+    if (Poco::File(this_filename).exists())
+    {
+      Poco::File(this_filename).remove();
+    }
+  }
+
+  /** Run SaveMD with the MDHistoWorkspace */
+  void doTestHisto(MDHistoWorkspace_sptr ws)
+  {
+    std::string filename = "SaveMD2TestHisto.nxs";
+
+    SaveMD2 alg;
+    TS_ASSERT_THROWS_NOTHING( alg.initialize() )
+    TS_ASSERT( alg.isInitialized() )
+    TS_ASSERT_THROWS_NOTHING( alg.setProperty("InputWorkspace", ws) );
+    TS_ASSERT_THROWS_NOTHING( alg.setPropertyValue("Filename", filename) );
+    alg.execute();
+    TS_ASSERT( alg.isExecuted() );
+
+    filename = alg.getPropertyValue("Filename");
+    TSM_ASSERT( "File was indeed created", Poco::File(filename).exists());
+    if (Poco::File(filename).exists())
+      Poco::File(filename).remove();
+  }
+
+  void test_histo2()
+  {
+    MDHistoWorkspace_sptr ws = MDEventsTestHelper::makeFakeMDHistoWorkspace(2.5, 2, 10, 10.0, 3.5, "histo2", 4.5);
+    doTestHisto(ws);
+  }
+
+};
+
+
+
+class SaveMD2TestPerformance : public CxxTest::TestSuite
+{
+public:
+  MDEventWorkspace3Lean::sptr  ws;
+  void setUp()
+  {
+    // Make a 1D MDEventWorkspace
+    ws = MDEventsTestHelper::makeMDEW<3>(10, 0.0, 10.0, 0);
+    ws->getBoxController()->setSplitInto(5);
+    ws->getBoxController()->setSplitThreshold(2000);
+
+    AnalysisDataService::Instance().addOrReplace("SaveMD2TestPerformance_ws", ws);
+
+    FrameworkManager::Instance().exec("FakeMDEventData", 4,
+        "InputWorkspace", "SaveMD2TestPerformance_ws", "UniformParams", "10000000");
+
+    ws->refreshCache();
+  }
+
+  void test_exec_3D()
+  {
+    SaveMD2 alg;
+    TS_ASSERT_THROWS_NOTHING( alg.initialize() )
+    TS_ASSERT( alg.isInitialized() )
+    TS_ASSERT_THROWS_NOTHING( alg.setPropertyValue("InputWorkspace", "SaveMD2TestPerformance_ws") );
+    TS_ASSERT_THROWS_NOTHING( alg.setPropertyValue("Filename", "SaveMD2TestPerformance.nxs") );
+    alg.execute();
+    TS_ASSERT( alg.isExecuted() );
+  }
+
+
+};
+
+
+#endif /* MANTID_MDEVENTS_SAVEMD2EWTEST_H_ */
+
diff --git a/Code/Mantid/Framework/Nexus/inc/MantidNexus/NexusFileIO.h b/Code/Mantid/Framework/Nexus/inc/MantidNexus/NexusFileIO.h
index 3c3ce6a16fb755e9d23cd49d534e40d495a3c4cc..2c3129fc10e627e0030bf2f0389b0275e14d9ea3 100644
--- a/Code/Mantid/Framework/Nexus/inc/MantidNexus/NexusFileIO.h
+++ b/Code/Mantid/Framework/Nexus/inc/MantidNexus/NexusFileIO.h
@@ -60,7 +60,7 @@ public:
   /// Default constructor
   NexusFileIO();
 
-  /// Contructor with Progress suplied
+  /// Contructor with Progress supplied
   NexusFileIO(API::Progress *prog);
 
   /// Destructor
@@ -128,7 +128,9 @@ public:
 
 private:
   /// C++ API file handle
+  // clang-format off
   boost::shared_ptr< ::NeXus::File> m_filehandle;
+  // clang-format on
   /// Nexus compression method
   int m_nexuscompression;
   /// Allow an externally supplied progress object to be used
diff --git a/Code/Mantid/Framework/Nexus/src/NexusClasses.cpp b/Code/Mantid/Framework/Nexus/src/NexusClasses.cpp
index e7a141f094f829e5a75f4cb8ed05baac18cb39aa..83c01c82b57a8ff240e8690f1ca804eab89bc3e1 100644
--- a/Code/Mantid/Framework/Nexus/src/NexusClasses.cpp
+++ b/Code/Mantid/Framework/Nexus/src/NexusClasses.cpp
@@ -2,8 +2,6 @@
 // Includes
 //----------------------------------------------------------------------
 #include "MantidNexus/NexusClasses.h"
-#include "MantidKernel/Exception.h"
-#include <cstdio>
 
 namespace Mantid {
 namespace NeXus {
diff --git a/Code/Mantid/Framework/Nexus/src/NexusFileIO.cpp b/Code/Mantid/Framework/Nexus/src/NexusFileIO.cpp
index 341c06fa43df8ca3952741a628d9e682ab83182a..0984355bcd319cfefa9c8fa190b44751c277b85b 100644
--- a/Code/Mantid/Framework/Nexus/src/NexusFileIO.cpp
+++ b/Code/Mantid/Framework/Nexus/src/NexusFileIO.cpp
@@ -5,7 +5,7 @@
 //----------------------------------------------------------------------
 #include <vector>
 #include <sstream>
-#include <stdlib.h>
+
 #ifdef _WIN32
 #include <io.h>
 #endif /* _WIN32 */
@@ -13,24 +13,14 @@
 #include "MantidKernel/TimeSeriesProperty.h"
 #include "MantidNexus/NexusFileIO.h"
 #include "MantidDataObjects/Workspace2D.h"
-#include "MantidKernel/Unit.h"
 #include "MantidKernel/UnitFactory.h"
-#include "MantidKernel/DateAndTime.h"
-#include "MantidKernel/ConfigService.h"
 #include "MantidKernel/ArrayProperty.h"
 #include "MantidAPI/NumericAxis.h"
-#include "MantidKernel/PhysicalConstants.h"
 #include "MantidKernel/VectorHelper.h"
 #include "MantidDataObjects/TableWorkspace.h"
 #include "MantidDataObjects/PeaksWorkspace.h"
-#include "MantidDataObjects/TableColumn.h"
-#include "MantidDataObjects/VectorColumn.h"
 #include "MantidDataObjects/RebinnedOutput.h"
-#include "MantidAPI/ITableWorkspace.h"
-#include "MantidAPI/AlgorithmHistory.h"
 
-#include <boost/tokenizer.hpp>
-#include <boost/make_shared.hpp>
 #include <Poco/File.h>
 
 namespace Mantid {
@@ -116,7 +106,9 @@ void NexusFileIO::openNexusWrite(const std::string &fileName,
       throw Exception::FileError("Unable to open File:", fileName);
     }
     ::NeXus::File *file = new ::NeXus::File(fileID, true);
+    // clang-format off
     m_filehandle = boost::shared_ptr< ::NeXus::File>(file);
+    // clang-format on
   }
 
   //
@@ -1042,7 +1034,9 @@ int NexusFileIO::getWorkspaceSize(int &numberOfSpectra, int &numberOfChannels,
 bool NexusFileIO::checkAttributeName(const std::string &target) const {
   // see if the given attribute name is in the current level
   // return true if it is.
+  // clang-format off
   const std::vector< ::NeXus::AttrInfo> infos = m_filehandle->getAttrInfos();
+  // clang-format on
   for (auto it = infos.begin(); it != infos.end(); ++it) {
     if (target.compare(it->name) == 0)
       return true;
diff --git a/Code/Mantid/Framework/Nexus/test/NexusAPITest.h b/Code/Mantid/Framework/Nexus/test/NexusAPITest.h
index 29c836431c2376baf1c157e5aaacc529533d022a..a65c4bd0aec3bcb7a522ed9e24df2ff0ba23b67c 100644
--- a/Code/Mantid/Framework/Nexus/test/NexusAPITest.h
+++ b/Code/Mantid/Framework/Nexus/test/NexusAPITest.h
@@ -193,7 +193,9 @@ public:
     const string SDS("SDS");
     // top level file information
     ::NeXus::File file(filename);
+    // clang-format off
     vector< ::NeXus::AttrInfo> attr_infos = file.getAttrInfos();
+    // clang-format on
     // check group attributes
     file.openGroup("entry", "NXentry");
 
diff --git a/Code/Mantid/Framework/Properties/Mantid.properties.template b/Code/Mantid/Framework/Properties/Mantid.properties.template
index 4c4cadd31c370e555ccb2632afe3a6e91e57e628..5f04c183d33ac185a5b3554b9336067d34e4dfc0 100644
--- a/Code/Mantid/Framework/Properties/Mantid.properties.template
+++ b/Code/Mantid/Framework/Properties/Mantid.properties.template
@@ -16,7 +16,8 @@ default.facility = ISIS
 default.instrument =
 
 # Set of PyQt interfaces to add to the Interfaces menu, separated by a space.  Interfaces are seperated from their respective categories by a "/".
-mantidqt.python_interfaces = Direct/DGS_Reduction.py Direct/DGSPlanner.py SANS/ORNL_SANS.py Reflectometry/REFL_Reduction.py Reflectometry/REFL_SF_Calculator.py Reflectometry/REFM_Reduction.py Utility/TofConverter.py Reflectometry/ISIS_Reflectometry.py Diffraction/Powder_Diffraction_Reduction.py Utility/FilterEvents.py
+mantidqt.python_interfaces = Direct/DGS_Reduction.py Direct/DGSPlanner.py SANS/ORNL_SANS.py Reflectometry/REFL_Reduction.py Reflectometry/REFL_SF_Calculator.py Reflectometry/REFM_Reduction.py Utility/TofConverter.py Reflectometry/ISIS_Reflectometry.py Diffraction/Powder_Diffraction_Reduction.py Utility/FilterEvents.py Diffraction/HFIR_Powder_Diffraction_Reduction.py
+
 mantidqt.python_interfaces_directory = @MANTID_ROOT@/scripts
 
 # Where to find mantid plugin libraries
diff --git a/Code/Mantid/Framework/PythonInterface/inc/MantidPythonInterface/kernel/Converters/NumpyFunctions.h b/Code/Mantid/Framework/PythonInterface/inc/MantidPythonInterface/kernel/Converters/NumpyFunctions.h
index 473189403f991563d30440d500a2c302104226a7..04043977a6a817795c34b0b7a9c8ba370130aa4c 100644
--- a/Code/Mantid/Framework/PythonInterface/inc/MantidPythonInterface/kernel/Converters/NumpyFunctions.h
+++ b/Code/Mantid/Framework/PythonInterface/inc/MantidPythonInterface/kernel/Converters/NumpyFunctions.h
@@ -28,13 +28,19 @@
 
 #include <boost/python/list.hpp>
 #include "MantidKernel/WarningSuppressions.h"
-GCC_DIAG_OFF(cast - qual)
+
+// clang-format off
+GCC_DIAG_OFF(cast-qual)
+// clang-format on
+
 // See
 // http://docs.scipy.org/doc/numpy/reference/c-api.array.html#PY_ARRAY_UNIQUE_SYMBOL
 #define PY_ARRAY_UNIQUE_SYMBOL KERNEL_ARRAY_API
 #define NO_IMPORT_ARRAY
 #include <numpy/arrayobject.h>
-GCC_DIAG_ON(cast - qual)
+// clang-format off
+GCC_DIAG_ON(cast-qual)
+// clang-format on
 
 /**functions containing numpy macros. We put them in a separate header file to
   *suppress the warning
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Algorithm.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Algorithm.cpp
index 99e7e215f5d7f55b1d030bf42a7d644114cda969..eb372bd605fb8b9105477752da3b17c2e7238151 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Algorithm.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Algorithm.cpp
@@ -38,7 +38,9 @@ namespace
   BOOST_PYTHON_FUNCTION_OVERLOADS(declarePropertyType3_Overload, PythonAlgorithm::declarePyAlgProperty, 4, 5)
 }
 
+// clang-format off
 void export_leaf_classes()
+// clang-format on
 {
 
   register_ptr_to_python<boost::shared_ptr<Algorithm>>();
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmFactory.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmFactory.cpp
index 4719f8e959126fdb9aa392704adc0518d41a8b3d..374187c08e7bfe10fdaf042c32024e2607cf4e64 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmFactory.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmFactory.cpp
@@ -63,7 +63,9 @@ namespace
   // Python algorithm registration mutex in anonymous namespace (aka static)
   Poco::Mutex PYALG_REGISTER_MUTEX;
 
+// clang-format off
 GCC_DIAG_OFF(cast-qual)
+// clang-format on
   /**
    * A free function to subscribe a Python algorithm into the factory
    * @param obj :: A Python object that should either be a class type derived from PythonAlgorithm
@@ -101,9 +103,13 @@ GCC_DIAG_OFF(cast-qual)
 
   ///@endcond
 }
+// clang-format off
 GCC_DIAG_ON(cast-qual)
+// clang-format on
 
+// clang-format off
 void export_AlgorithmFactory()
+// clang-format on
 {
 
   class_<AlgorithmFactoryImpl,boost::noncopyable>("AlgorithmFactoryImpl", no_init)
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmHistory.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmHistory.cpp
index 6ebd0b981e56720f1279d0eaab4b899b325bc37a..3febd8e0af53ba30f66692d3ceab7412e9e2eb42 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmHistory.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmHistory.cpp
@@ -54,7 +54,9 @@ boost::python::object getPropertiesAsList(AlgorithmHistory& self)
   return names;
 }
 
+// clang-format off
 void export_AlgorithmHistory()
+// clang-format on
 {
   register_ptr_to_python<Mantid::API::AlgorithmHistory_sptr >();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmManager.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmManager.cpp
index 4296086b4f68f950c5e8326dd0de2d9bf6a57914..970a6999a46779c70435c40fef2ec94d03e90113 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmManager.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmManager.cpp
@@ -64,7 +64,9 @@ namespace
   ///@endcond
 }
 
+// clang-format off
 void export_AlgorithmManager()
+// clang-format on
 {
   typedef class_<AlgorithmManagerImpl,boost::noncopyable> PythonType;
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmProperty.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmProperty.cpp
index 27eb76b69b3f9bf6f288f919c008fb3419d1b392..532266fc4308dd393775ccaf5c4fcfa628409e27 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmProperty.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmProperty.cpp
@@ -38,7 +38,9 @@ namespace
 
 }
 
+// clang-format off
 void export_AlgorithmProperty()
+// clang-format on
 {
   // AlgorithmProperty has base PropertyWithValue<boost::shared_ptr<IAlgorithm>>
   // which must be exported
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmProxy.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmProxy.cpp
index 34b4053367b6abbee01a2921500e6147f65062d7..da3f99efa96710fa2931fb9d3685247f9e4c3448 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmProxy.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmProxy.cpp
@@ -9,7 +9,9 @@
 using namespace Mantid::API;
 using namespace boost::python;
 
+// clang-format off
 void export_algorithm_proxy()
+// clang-format on
 {
 
   register_ptr_to_python<boost::shared_ptr<AlgorithmProxy>>();
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/AnalysisDataService.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/AnalysisDataService.cpp
index a2d181201d66ab805c617b728c041abe22102bc7..7723bf3eb02ed2287b729c41423ecd7c4e98a8e4 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/AnalysisDataService.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/AnalysisDataService.cpp
@@ -65,7 +65,9 @@ namespace
 
 }
 
+// clang-format off
 void export_AnalysisDataService()
+// clang-format on
 {
   typedef DataServiceExporter<AnalysisDataServiceImpl, Workspace_sptr> ADSExporter;
   auto pythonClass = ADSExporter::define("AnalysisDataServiceImpl");
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Axis.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Axis.cpp
index 4151bcbebf843e22591789803a3f9136041fc14e..7ab4b583a6f9f26dacb9f84aa7bfb244aaa58acd 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Axis.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Axis.cpp
@@ -78,7 +78,9 @@ namespace
 }
 
 
+// clang-format off
 void export_Axis()
+// clang-format on
 {
   register_ptr_to_python<Axis*>();
 
@@ -119,7 +121,9 @@ Axis* createNumericAxis(int length)
   return new Mantid::API::NumericAxis(length);
 }
 
+// clang-format off
 void export_NumericAxis()
+// clang-format on
 {
   /// Exported so that Boost.Python can give back a NumericAxis class when an Axis* is returned
   class_< NumericAxis, bases<Axis>, boost::noncopyable >("NumericAxis", no_init)
@@ -143,7 +147,9 @@ Axis* createBinEdgeAxis(int length)
   return new Mantid::API::BinEdgeAxis(length);
 }
 
+// clang-format off
 void export_BinEdgeAxis()
+// clang-format on
 {
   /// Exported so that Boost.Python can give back a BinEdgeAxis class when an Axis* is returned
   class_< BinEdgeAxis, bases<NumericAxis>, boost::noncopyable >("BinEdgeAxis", no_init)
@@ -168,7 +174,9 @@ Axis* createTextAxis(int length)
 }
 
 
+// clang-format off
 void export_TextAxis()
+// clang-format on
 {
   class_< TextAxis, bases<Axis>, boost::noncopyable >("TextAxis", no_init)
     .def("setLabel", & TextAxis::setLabel, "Set the label at the given entry")
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/BinaryOperations.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/BinaryOperations.cpp
index e2f388a9d7bacd6dc7a4f3eaaeba4428c61e1206..ca1f13e79308f33a59e8634aba466d07cd0de475 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/BinaryOperations.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/BinaryOperations.cpp
@@ -14,7 +14,9 @@
 
 namespace Policies = Mantid::PythonInterface::Policies;
 
+// clang-format off
 void export_BinaryOperations()
+// clang-format on
 {
   using namespace Mantid::API;
   using boost::python::return_value_policy;
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/BoxController.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/BoxController.cpp
index a77e0b319adec044dedb1985a10001e6e63ea2a3..950a9cdb187ec280d364b45002db216548e61f29 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/BoxController.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/BoxController.cpp
@@ -7,7 +7,9 @@
 using Mantid::API::BoxController;
 using namespace boost::python;
 
+// clang-format off
 void export_BoxController()
+// clang-format on
 {
   register_ptr_to_python<boost::shared_ptr<BoxController>>();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/CatalogManager.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/CatalogManager.cpp
index 9104eead36962acfe797c73acf2267014e3c1187..46bedf92c58ef8240559cbc522c8d6a517770f57 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/CatalogManager.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/CatalogManager.cpp
@@ -19,7 +19,9 @@ boost::python::object getActiveSessionsAsList(CatalogManagerImpl& self)
   return sessions;
 }
 
+// clang-format off
 void export_CatalogManager()
+// clang-format on
 {
   register_ptr_to_python<CatalogManagerImpl*>();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/CatalogSession.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/CatalogSession.cpp
index f888c6110c7d061eb15df4cab67aadcc41e17199..98532ffe0fa490db067baeffdaf34d75690a0a38 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/CatalogSession.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/CatalogSession.cpp
@@ -7,7 +7,9 @@
 using Mantid::API::CatalogSession;
 using namespace boost::python;
 
+// clang-format off
 void export_CatalogSession()
+// clang-format on
 {
     register_ptr_to_python<boost::shared_ptr<CatalogSession> >();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/DataProcessorAlgorithm.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/DataProcessorAlgorithm.cpp
index a8bcac9e082e16224c5b359de332183aebac4f40..08a1b34c686ed72cc19da2dc5d4842416ce012c4 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/DataProcessorAlgorithm.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/DataProcessorAlgorithm.cpp
@@ -14,7 +14,9 @@ namespace
   typedef Workspace_sptr(DataProcessorAdapter::*loadOverload2)(const std::string&, const bool);
 }
 
+// clang-format off
 void export_DataProcessorAlgorithm()
+// clang-format on
 {
   // for strings will actually create a list
   using Mantid::PythonInterface::Policies::VectorToNumpy;
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/DeprecatedAlgorithmChecker.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/DeprecatedAlgorithmChecker.cpp
index 53f4cb6fa0ec04a05d505de3234b2e6c5a9622c3..821e324d7c9ebe331dbad8bc993f0a708514543a 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/DeprecatedAlgorithmChecker.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/DeprecatedAlgorithmChecker.cpp
@@ -50,7 +50,9 @@ namespace
   };
 }
 
+// clang-format off
 void export_DeprecatedAlgorithmChecker()
+// clang-format on
 {
   class_<DeprecatedAlgorithmChecker>("DeprecatedAlgorithmChecker", no_init)
     .def(init<const std::string&,int>((arg("algName"),arg("version")),"Constructs a DeprecatedAlgorithmChecker for the given algorithm & version. (-1 indicates latest version)"))
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ExperimentInfo.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ExperimentInfo.cpp
index b02c444f40f44c630a6a4e48363a50a87983f78d..e6dcc21ac75d002da3601af2b15958460a742b9a 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ExperimentInfo.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ExperimentInfo.cpp
@@ -13,7 +13,9 @@ using namespace boost::python;
 /// Overload generator for getInstrumentFilename
 BOOST_PYTHON_FUNCTION_OVERLOADS(getInstrumentFilename_Overload, ExperimentInfo::getInstrumentFilename, 1, 2)
 
+// clang-format off
 void export_ExperimentInfo()
+// clang-format on
 {
   register_ptr_to_python<boost::shared_ptr<ExperimentInfo>>();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/FileFinder.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/FileFinder.cpp
index d4bec6851b00d0549be757ae4136600725e18278..12fdb1d5a8e59385d9d6ae82b2ac278fb183854c 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/FileFinder.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/FileFinder.cpp
@@ -11,7 +11,9 @@ namespace {
   BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(getFullPathOverloader, getFullPath, 1, 2)
 }
 
+// clang-format off
 void export_FileFinder()
+// clang-format on
 {
   class_<FileFinderImpl, boost::noncopyable>("FileFinderImpl", no_init)
     .def("getFullPath", &FileFinderImpl::getFullPath,
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/FileProperty.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/FileProperty.cpp
index 02749eae5673b154ea72c906d1afbe0232015ecb..faa83923fff77927790faed5a863d4c837b6c5b5 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/FileProperty.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/FileProperty.cpp
@@ -17,7 +17,9 @@ using Mantid::Kernel::PropertyWithValue;
 using Mantid::PythonInterface::Converters::PySequenceToVector;
 namespace bpl = boost::python;
 
+// clang-format off
 void export_ActionEnum()
+// clang-format on
 {
   bpl::enum_<FileProperty::FileAction>("FileAction")
         .value("Save", FileProperty::Save)
@@ -63,7 +65,9 @@ namespace
 
 }
 
+// clang-format off
 void export_FileProperty()
+// clang-format on
 {
   bpl::class_<FileProperty, bpl::bases<PropertyWithValue<std::string> >, boost::noncopyable>("FileProperty", bpl::no_init)
     .def("__init__",
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/FrameworkManager.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/FrameworkManager.cpp
index b917c6637ebf73db88ba68ca884c107f80779366..f47580ff37f6863ceafcfe78e68657b8d6fe1aed 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/FrameworkManager.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/FrameworkManager.cpp
@@ -8,7 +8,9 @@ using Mantid::API::FrameworkManagerImpl;
 using Mantid::API::FrameworkManager;
 using namespace boost::python;
 
+// clang-format off
 void export_FrameworkManager()
+// clang-format on
 {
   class_<FrameworkManagerImpl,boost::noncopyable>("FrameworkManagerImpl", no_init)
     .def("setNumOMPThreadsToConfigValue", &FrameworkManagerImpl::setNumOMPThreadsToConfigValue,
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/FunctionFactory.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/FunctionFactory.cpp
index d00e88e34f35bae68c595407f6268eb42d5b0f6c..e504e39e19e32a70cee33dee74b7696307bf4705 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/FunctionFactory.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/FunctionFactory.cpp
@@ -86,7 +86,9 @@ namespace
   ///@endcond
 }
 
+// clang-format off
 void export_FunctionFactory()
+// clang-format on
 {
 
   class_<FunctionFactoryImpl,boost::noncopyable>("FunctionFactoryImpl", no_init)
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/FunctionProperty.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/FunctionProperty.cpp
index 1f042a31cf66298e55d5368e8628d0dbaa187495..ffbfbdb11b812874b7b0aec6d6f5f6a319a24b77 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/FunctionProperty.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/FunctionProperty.cpp
@@ -8,7 +8,9 @@ using Mantid::Kernel::PropertyWithValue;
 using Mantid::PythonInterface::PropertyWithValueExporter;
 using namespace boost::python;
 
+// clang-format off
 void export_FunctionProperty()
+// clang-format on
 {
   // FuncitonProperty has base PropertyWithValue<boost::shared_ptr<IFunction>>
   // which must be exported
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IAlgorithm.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IAlgorithm.cpp
index 07ef49a108f54e31646f4fd7addfd8a80049b5de..2f5406854f326bc1e62a6721ec665fd6ea8c6e63 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IAlgorithm.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IAlgorithm.cpp
@@ -262,7 +262,9 @@ namespace
 
 }
 
+// clang-format off
 void export_ialgorithm()
+// clang-format on
 {
   class_<AlgorithmIDProxy>("AlgorithmID", no_init)
     .def(self == self)
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IEventList.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IEventList.cpp
index 19fd218d92f4f0cc27bef83a3f34fe0d44d1caf6..7537d8f60f8182af7f2bf3ee499b7085e40e724e 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IEventList.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IEventList.cpp
@@ -20,7 +20,9 @@ using namespace boost::python;
 /// return_value_policy for copied numpy array
 typedef return_value_policy<Policies::VectorToNumpy> return_clone_numpy;
 
+// clang-format off
 void export_IEventList()
+// clang-format on
 {
   register_ptr_to_python<IEventList *>();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IEventWorkspace.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IEventWorkspace.cpp
index 57bd6601a2403ca14c10b5933f3fdbd9cf703163..af2bfc0bea8f16c6bf73ef04b7cf1185931ca4a8 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IEventWorkspace.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IEventWorkspace.cpp
@@ -12,7 +12,9 @@ using namespace boost::python;
 /**
  * Python exports of the Mantid::API::IEventWorkspace class.
  */
+// clang-format off
 void export_IEventWorkspace()
+// clang-format on
 {
   class_<IEventWorkspace, bases<Mantid::API::MatrixWorkspace>, boost::noncopyable>("IEventWorkspace", no_init)
     .def("getNumberEvents", &IEventWorkspace::getNumberEvents, args("self"),
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IEventWorkspaceProperty.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IEventWorkspaceProperty.cpp
index 99afcf21875d9ee34985992a2243fabc90862135..241e1e9825ba96098d631c70b285b10906895916 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IEventWorkspaceProperty.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IEventWorkspaceProperty.cpp
@@ -1,7 +1,9 @@
 #include "MantidPythonInterface/api/WorkspacePropertyExporter.h"
 #include "MantidAPI/IEventWorkspace.h"
 
+// clang-format off
 void export_IEventWorkspaceProperty()
+// clang-format on
 {
   using Mantid::API::IEventWorkspace;
   using Mantid::PythonInterface::WorkspacePropertyExporter;
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IFunction.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IFunction.cpp
index d43ac0538b798e6bf3bf5978e8e9af36a0e3d391..292be1504f6da2dafb5ef300598075c263013749 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IFunction.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IFunction.cpp
@@ -44,7 +44,9 @@ namespace
   ///@endcond
 }
 
+// clang-format off
 void export_IFunction()
+// clang-format on
 {
 
   register_ptr_to_python<boost::shared_ptr<IFunction>>();
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IFunction1D.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IFunction1D.cpp
index 726caf7ea272f73a1e2e031bcecda66267089857..df88a040e9ffeb1ed55fb09513e7f2a0fd4fd953 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IFunction1D.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IFunction1D.cpp
@@ -8,7 +8,9 @@ using Mantid::PythonInterface::IFunction1DAdapter;
 using Mantid::PythonInterface::IFunctionAdapter;
 using namespace boost::python;
 
+// clang-format off
 void export_IFunction1D()
+// clang-format on
 {
   /**
    * The Python held type, boost::shared_ptr<IFunction1DAdapter>, allows
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IMDEventWorkspace.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IMDEventWorkspace.cpp
index 436f05446246dd576646dcd0368d02370a4d59b3..8bc619371670f41c9fc99f1eead55e945b3c399d 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IMDEventWorkspace.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IMDEventWorkspace.cpp
@@ -15,7 +15,9 @@ namespace
   static const unsigned int NUM_EVENT_TYPES = 2;
 }
 
+// clang-format off
 void export_IMDEventWorkspace()
+// clang-format on
 {
   // MDEventWorkspace class
   class_< IMDEventWorkspace, bases<IMDWorkspace, MultipleExperimentInfos>,
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IMDEventWorkspaceProperty.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IMDEventWorkspaceProperty.cpp
index c0169c29fc04ecf90e8a3ef7ed72fa9b5f3437a7..74795da8d32154a086418f3600fb5fbb3e583079 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IMDEventWorkspaceProperty.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IMDEventWorkspaceProperty.cpp
@@ -1,7 +1,9 @@
 #include "MantidPythonInterface/api/WorkspacePropertyExporter.h"
 #include "MantidAPI/IMDEventWorkspace.h"
 
+// clang-format off
 void export_IMDEventWorkspaceProperty()
+// clang-format on
 {
   using Mantid::API::IMDEventWorkspace;
   using Mantid::PythonInterface::WorkspacePropertyExporter;
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IMDHistoWorkspace.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IMDHistoWorkspace.cpp
index b33c0331041bff38ea8247bf94f16a96b0aa5c30..24ab708188feaed3c6f3592b3e5d0cb28277eb87 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IMDHistoWorkspace.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IMDHistoWorkspace.cpp
@@ -140,7 +140,9 @@ namespace
 
 }
 
+// clang-format off
 void export_IMDHistoWorkspace()
+// clang-format on
 {
   // IMDHistoWorkspace class
   class_< IMDHistoWorkspace, bases<IMDWorkspace,MultipleExperimentInfos>, boost::noncopyable >("IMDHistoWorkspace", no_init)
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IMDHistoWorkspaceProperty.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IMDHistoWorkspaceProperty.cpp
index 7457356b21cde000c2b55c5d6f96abea84cfadb5..44e6346bf64a831fa210f1de05c976e9ffd7ae12 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IMDHistoWorkspaceProperty.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IMDHistoWorkspaceProperty.cpp
@@ -1,7 +1,9 @@
 #include "MantidPythonInterface/api/WorkspacePropertyExporter.h"
 #include "MantidAPI/IMDHistoWorkspace.h"
 
+// clang-format off
 void export_IMDHistoWorkspaceProperty()
+// clang-format on
 {
   using Mantid::API::IMDHistoWorkspace;
   using Mantid::PythonInterface::WorkspacePropertyExporter;
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IMDWorkspace.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IMDWorkspace.cpp
index 5c728e614f8305026ed6ff190ac6cbcd4aeba7ca..8b0931b83894190d4042dafbfcb9abb67d5d85a4 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IMDWorkspace.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IMDWorkspace.cpp
@@ -9,7 +9,9 @@ using namespace Mantid::API;
 using Mantid::PythonInterface::Registry::DataItemInterface;
 using namespace boost::python;
 
+// clang-format off
 void export_IMDWorkspace()
+// clang-format on
 {
   boost::python::enum_<Mantid::API::MDNormalization>("MDNormalization")
           .value("NoNormalization", Mantid::API::NoNormalization)
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IMDWorkspaceProperty.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IMDWorkspaceProperty.cpp
index 23299662ed1e30997cd97be300a0622cd0dfcb32..6c90bfc8c30a579cbea25e106a5435538adfce06 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IMDWorkspaceProperty.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IMDWorkspaceProperty.cpp
@@ -1,7 +1,9 @@
 #include "MantidPythonInterface/api/WorkspacePropertyExporter.h"
 #include "MantidAPI/IMDWorkspace.h"
 
+// clang-format off
 void export_IMDWorkspaceProperty()
+// clang-format on
 {
   using Mantid::API::IMDWorkspace;
   using Mantid::PythonInterface::WorkspacePropertyExporter;
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp
index e12912bc5a0a8b6419a16ea5e56ebfc4451ea248..223e88b9fced890464c52ac5f808630149d43e3f 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp
@@ -31,7 +31,9 @@ void setQSampleFrame2(IPeak &peak, Mantid::Kernel::V3D qSampleFrame, double dist
 
 }
 
+// clang-format off
 void export_IPeak()
+// clang-format on
 {
   register_ptr_to_python<IPeak*>();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeakFunction.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeakFunction.cpp
index c8589a927a7212d5937fe5b28674052c35e95a2c..ae238374b382d1d2ab854d265998d3c25a9c9991 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeakFunction.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeakFunction.cpp
@@ -7,7 +7,9 @@ using Mantid::API::IPeakFunction;
 using Mantid::PythonInterface::IPeakFunctionAdapter;
 using namespace boost::python;
 
+// clang-format off
 void export_IPeakFunction()
+// clang-format on
 {
   class_<IPeakFunction, bases<IFunction1D>, boost::shared_ptr<IPeakFunctionAdapter>,
           boost::noncopyable>("IPeakFunction")
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeaksWorkspace.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeaksWorkspace.cpp
index 965bf50050c39cbd0ca1ad11fdad3282a429a1fc..9ea3e721fbc80ff44e299dfd57cc6baf5a8afed8 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeaksWorkspace.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeaksWorkspace.cpp
@@ -33,7 +33,9 @@ IPeak* createPeakQLabWithDistance(IPeaksWorkspace & self, const object& data, do
 
 }
 
+// clang-format off
 void export_IPeaksWorkspace()
+// clang-format on
 {
   // IPeaksWorkspace class
   class_< IPeaksWorkspace, bases<ITableWorkspace, ExperimentInfo>, boost::noncopyable >("IPeaksWorkspace", no_init)
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeaksWorkspaceProperty.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeaksWorkspaceProperty.cpp
index f98cc9dec625582b0b3f9fbd8271b26c113cd8ae..c34674f7982ecc934d4430af194ba1d001cfb395 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeaksWorkspaceProperty.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeaksWorkspaceProperty.cpp
@@ -1,7 +1,9 @@
 #include "MantidPythonInterface/api/WorkspacePropertyExporter.h"
 #include "MantidAPI/IPeaksWorkspace.h"
 
+// clang-format off
 void export_IPeaksWorkspaceProperty()
+// clang-format on
 {
   using Mantid::API::IPeaksWorkspace;
   using Mantid::PythonInterface::WorkspacePropertyExporter;
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ISpectrum.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ISpectrum.cpp
index 364740c59131415b6c868974d2a888c850e82e26..615caeda892480beaef32c365f2e8aed8ccb0f18 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ISpectrum.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ISpectrum.cpp
@@ -7,7 +7,9 @@ using Mantid::API::ISpectrum;
 using Mantid::detid_t;
 using namespace boost::python;
 
+// clang-format off
 void export_ISpectrum()
+// clang-format on
 {
   register_ptr_to_python<ISpectrum*>();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ISplittersWorkspace.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ISplittersWorkspace.cpp
index 0216ac789bd688dfec75cb501c2a63779276964b..6511a0fa0896e031919cfee94db29f92362ff24c 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ISplittersWorkspace.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ISplittersWorkspace.cpp
@@ -7,7 +7,9 @@
 using namespace Mantid::API;
 using namespace boost::python;
 
+// clang-format off
 void export_IPeaksWorkspace()
+// clang-format on
 {
   register_ptr_to_python<boost::shared_ptr<ISplittersWorkspace>>();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ITableWorkspace.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ITableWorkspace.cpp
index e892a1c8e4b5065e222418c58ab50eb88000abde..a614c7c8ae00098147013994f1a3098826d37136 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ITableWorkspace.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ITableWorkspace.cpp
@@ -338,7 +338,9 @@ namespace
    }
 }
 
+// clang-format off
 void export_ITableWorkspace()
+// clang-format on
 {
   using Mantid::PythonInterface::Policies::VectorToNumpy;
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ITableWorkspaceProperty.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ITableWorkspaceProperty.cpp
index 28d6bc0abcf1b42e68bff6358a28424f8799c219..2eeaa76e02051f5dad234209326a0beccda408c4 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ITableWorkspaceProperty.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ITableWorkspaceProperty.cpp
@@ -1,7 +1,9 @@
 #include "MantidPythonInterface/api/WorkspacePropertyExporter.h"
 #include "MantidAPI/ITableWorkspace.h"
 
+// clang-format off
 void export_ITableWorkspaceProperty()
+// clang-format on
 {
   using Mantid::API::ITableWorkspace;
   using Mantid::PythonInterface::WorkspacePropertyExporter;
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IWorkspaceProperty.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IWorkspaceProperty.cpp
index 598d3d4ad74905b7a9a20de73edea734ac6ed542..ebff24c9de7b85b8af1f5fd448f2211aad5e09c5 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IWorkspaceProperty.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IWorkspaceProperty.cpp
@@ -1,7 +1,9 @@
 #include "MantidAPI/IWorkspaceProperty.h"
 #include <boost/python/class.hpp>
 
+// clang-format off
 void export_IWorkspaceProperty()
+// clang-format on
 {
   using namespace boost::python;
   using Mantid::API::IWorkspaceProperty;
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/InstrumentValidator.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/InstrumentValidator.cpp
index 45390cfe462a68cef75c73a56d81d48ad7f55500..fc49fcd67d1144f2d72b591a925e8d87c04c2483 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/InstrumentValidator.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/InstrumentValidator.cpp
@@ -8,7 +8,9 @@ using namespace boost::python;
 
 
 // This is typed on the ExperimentInfo class
+// clang-format off
 void export_InstrumentValidator()
+// clang-format on
 {
   TypedValidatorExporter<ExperimentInfo_sptr>::define("ExperimentInfoValidator");
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Jacobian.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Jacobian.cpp
index 690476a19300ee1e4be4b951e949e918288ec306..ccd3830fe274a90d0ee47ff3673367eea4e663b0 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Jacobian.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Jacobian.cpp
@@ -5,7 +5,9 @@
 using Mantid::API::Jacobian;
 using namespace boost::python;
 
+// clang-format off
 void export_Jacobian()
+// clang-format on
 {
   register_ptr_to_python<Jacobian*>();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/MDGeometry.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/MDGeometry.cpp
index da17825399bcdffc854733f86571a3ab1560ed62..815cf0cb23922f757dfd6c8e6bcafc00c33d5342 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/MDGeometry.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/MDGeometry.cpp
@@ -36,7 +36,9 @@ namespace
 
 }
 
+// clang-format off
 void export_MDGeometry()
+// clang-format on
 {
   class_<MDGeometry,boost::noncopyable>("MDGeometry", no_init)
     .def("getNumDims", &MDGeometry::getNumDims, "Returns the number of dimensions present")
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/MatrixWorkspace.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/MatrixWorkspace.cpp
index c2ed44869bd1d08342011c2c7909e300ad451675..326886edf0d704e1889a86e3876197fa3977b7bb 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/MatrixWorkspace.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/MatrixWorkspace.cpp
@@ -127,7 +127,9 @@ namespace
 }
 
 /** Python exports of the Mantid::API::MatrixWorkspace class. */
+// clang-format off
 void export_MatrixWorkspace()
+// clang-format on
 {
   /// Typedef to remove const qualifier on input detector shared_ptr. See Policies/RemoveConst.h for more details
   typedef double (MatrixWorkspace::*getDetectorSignature)(Mantid::Geometry::IDetector_sptr det) const;
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/MatrixWorkspaceProperty.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/MatrixWorkspaceProperty.cpp
index 481f3c9a311f3a14130c9d8bfd6cd84153957e3c..1f7f763399716b2557ac7a61b2d26de238c34af5 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/MatrixWorkspaceProperty.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/MatrixWorkspaceProperty.cpp
@@ -1,7 +1,9 @@
 #include "MantidPythonInterface/api/WorkspacePropertyExporter.h"
 #include "MantidAPI/MatrixWorkspace.h"
 
+// clang-format off
 void export_MatrixWorkspaceProperty()
+// clang-format on
 {
   using Mantid::API::MatrixWorkspace;
   using Mantid::PythonInterface::WorkspacePropertyExporter;
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/MultipleExperimentInfos.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/MultipleExperimentInfos.cpp
index e84dca456990bcfc613c67d458614a9561416fa0..b0570359ba93669dc8b2662b2e6a9c3ca1d5872a 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/MultipleExperimentInfos.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/MultipleExperimentInfos.cpp
@@ -6,7 +6,9 @@ using Mantid::API::MultipleExperimentInfos;
 using Mantid::API::ExperimentInfo_sptr;
 using namespace boost::python;
 
+// clang-format off
 void export_MultipleExperimentInfos()
+// clang-format on
 {
   class_<MultipleExperimentInfos,boost::noncopyable>("MultipleExperimentInfos", no_init)
       .def("getExperimentInfo", (ExperimentInfo_sptr(MultipleExperimentInfos::*)(const uint16_t) ) &MultipleExperimentInfos::getExperimentInfo,
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/MultipleFileProperty.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/MultipleFileProperty.cpp
index e121994dbc5bec86ba54e600e632b8b2ffb47e11..7c7e4196d73366cb1db7937699fb9b6dabbe673f 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/MultipleFileProperty.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/MultipleFileProperty.cpp
@@ -55,7 +55,9 @@ namespace
   }
 }
 
+// clang-format off
 void export_MultipleFileProperty()
+// clang-format on
 {
   typedef PropertyWithValue<HeldType> BaseClass;
   PropertyWithValueExporter<HeldType>::define("VectorVectorStringPropertyWithValue");
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Progress.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Progress.cpp
index 05da2bcef079c78b613cebcc9fcd8662e44d5cb5..5260c3d0099dc46de97a013d7c23654b9b5f0a31 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Progress.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Progress.cpp
@@ -9,7 +9,9 @@ using Mantid::API::Algorithm;
 using Mantid::Kernel::ProgressBase;
 using namespace boost::python;
 
+// clang-format off
 void export_Progress()
+// clang-format on
 {
   class_<Progress,
          bases<ProgressBase>,
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Projection.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Projection.cpp
index 02120fb651a6d36b03c8230cba766774cbbe1310..3aef685af33a7457f8d9666e314c53b857477571 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Projection.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Projection.cpp
@@ -15,7 +15,9 @@ using namespace Mantid::API;
 using namespace Mantid::PythonInterface;
 using namespace boost::python;
 
+// clang-format off
 GCC_DIAG_OFF(strict-aliasing)
+// clang-format on
 
 namespace {
 std::string getUnit(Projection &p, size_t nd) {
@@ -98,7 +100,9 @@ Projection_sptr projCtor3(
 
 } //anonymous namespace
 
+// clang-format off
 void export_Projection()
+// clang-format on
 {
   class_<Projection>(
     "Projection",
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/PropertyHistory.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/PropertyHistory.cpp
index 3d1be876fd7c98198a2e9222266467e47c09c205..e1af05fc98df0a3fcadc805158851818dc738ded 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/PropertyHistory.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/PropertyHistory.cpp
@@ -10,7 +10,9 @@ using Mantid::Kernel::PropertyHistory;
 using Mantid::API::IAlgorithm;
 using namespace boost::python;
 
+// clang-format off
 void export_PropertyHistory()
+// clang-format on
 {
   register_ptr_to_python<PropertyHistory*>();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/PropertyManagerDataService.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/PropertyManagerDataService.cpp
index 19b8cbb58a841b9b78b434a64e776aac53bcf060..157a454a24c6620a2a758ecb2342e87908d6daaa 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/PropertyManagerDataService.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/PropertyManagerDataService.cpp
@@ -15,7 +15,9 @@ using namespace boost::python;
 /// Weak pointer to DataItem typedef
 typedef boost::weak_ptr<PropertyManager> PropertyManager_wptr;
 
+// clang-format off
 void export_PropertyManagerDataService()
+// clang-format on
 {
 
   register_ptr_to_python<PropertyManager_wptr>();
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Run.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Run.cpp
index e83d7784d1637ca26703772a885baf173c8d07ba..dc253da4b81322b35a7d21a1a979eaa96a165cb0 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Run.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Run.cpp
@@ -111,7 +111,9 @@ namespace
 
 }
 
+// clang-format off
 void export_Run()
+// clang-format on
 {
   //Pointer
   register_ptr_to_python<Run*>();
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Sample.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Sample.cpp
index 232dda2f067990704186c3c4c444a0e721cfeb9c..1da621ce987bdc73a6c07d6f1e9ee6f69bb09766 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Sample.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Sample.cpp
@@ -10,7 +10,9 @@ using Mantid::Geometry::OrientedLattice;
 using Mantid::Kernel::Material;
 using namespace boost::python;
 
+// clang-format off
 void export_Sample()
+// clang-format on
 {
   register_ptr_to_python<Sample*>();
   register_ptr_to_python<boost::shared_ptr<Sample> >();
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ScriptRepository.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ScriptRepository.cpp
index 206afe3f75c315f537f02790eff372a6a227057f..b655a853a5592bc2de99d03bef24aaa82be7c755 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ScriptRepository.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ScriptRepository.cpp
@@ -77,7 +77,9 @@ namespace
   /** @endcond */
 }
 
+// clang-format off
 void export_ScriptRepository()
+// clang-format on
 {
 
   register_ptr_to_python<boost::shared_ptr<ScriptRepository>>();
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ScriptRepositoryFactory.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ScriptRepositoryFactory.cpp
index 6b7d223e588ebbff50198031704f2af69107d179..ec3af278f39b1027094b04c809f7690beb47e2d2 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ScriptRepositoryFactory.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/ScriptRepositoryFactory.cpp
@@ -16,7 +16,9 @@ namespace
   ///@endcond
 }
 
+// clang-format off
 void export_ScriptRepositoryFactory()
+// clang-format on
 {
   class_<ScriptRepositoryFactoryImpl,boost::noncopyable>("ScriptRepositoryFactory", no_init)
       .def("create", &ScriptRepositoryFactoryImpl::create,
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Workspace.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Workspace.cpp
index 11dd4f9b8bff6891cb963f523178ba945c98c2b5..20da316f1509f7fbf87c5bddb5f804dce74d152a 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Workspace.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/Workspace.cpp
@@ -17,7 +17,9 @@ namespace
   ///@endcond
 }
 
+// clang-format off
 void export_Workspace()
+// clang-format on
 {
   class_<Workspace, bases<DataItem>, boost::noncopyable>("Workspace", no_init)
     .def("getName", &Workspace::getName, return_value_policy<copy_const_reference>(), 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceFactory.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceFactory.cpp
index e7cc6802b0fa5033923d65d5a65afe00c161053b..775bcaa2dcf6df2b8fa9b2cecff70e83343f8eee 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceFactory.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceFactory.cpp
@@ -39,7 +39,9 @@ namespace
   BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(createPeaks_Overload, createPeaks, 0, 1)
 }
 
+// clang-format off
 void export_WorkspaceFactory()
+// clang-format on
 {
   const char * createFromParentDoc = "Create a workspace based on the given one. The meta-data, instrument etc are copied from the input"
       "If the size parameters are passed then the workspace will be a different size.";
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceGroup.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceGroup.cpp
index 494562d45640225ba8d4c1da5f4180d0fc88b672..67de0e52e7fc165ba27630dac6563117f31a8a97 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceGroup.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceGroup.cpp
@@ -10,7 +10,9 @@ using Mantid::PythonInterface::Registry::DataItemInterface;
 using namespace boost::python;
 namespace Policies = Mantid::PythonInterface::Policies;
 
+// clang-format off
 void export_WorkspaceGroup() 
+// clang-format on
 {
   class_< WorkspaceGroup, bases<Workspace>, boost::noncopyable >("WorkspaceGroup", no_init)
     .def("getNumberOfEntries", &WorkspaceGroup::getNumberOfEntries, "Returns the number of entries in the group")
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceGroupProperty.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceGroupProperty.cpp
index 5fc61cf55e6d5ef9ff56d02eb691171da75751f4..ef7cfb1a90509a53ebd28288658da9b33d72a490 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceGroupProperty.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceGroupProperty.cpp
@@ -1,7 +1,9 @@
 #include "MantidPythonInterface/api/WorkspacePropertyExporter.h"
 #include "MantidAPI/WorkspaceGroup.h"
 
+// clang-format off
 void export_WorkspaceGroupProperty()
+// clang-format on
 {
   using Mantid::API::WorkspaceGroup;
   using Mantid::PythonInterface::WorkspacePropertyExporter;
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceHistory.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceHistory.cpp
index 7875df880363daf65a7fc1f643301725d768e381..175af51dc422327dc9d51d4fda21e06e4c570518 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceHistory.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceHistory.cpp
@@ -35,7 +35,9 @@ boost::python::object getHistoriesAsList(WorkspaceHistory& self)
   return names;
 }
 
+// clang-format off
 void export_WorkspaceHistory()
+// clang-format on
 {
   register_ptr_to_python<WorkspaceHistory*>();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceProperty.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceProperty.cpp
index d147a1402cbd64d414579545d12b12a21a3aa92d..a6ba97642d7bb2a9c77a1b79f0c43231ba5977d7 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceProperty.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceProperty.cpp
@@ -2,7 +2,9 @@
 #include "MantidAPI/Workspace.h"
 #include <boost/python/enum.hpp>
 
+// clang-format off
 void export_WorkspaceProperty()
+// clang-format on
 {
   using Mantid::API::PropertyMode;
   // Property and Lock mode enums
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceValidators.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceValidators.cpp
index 593da16e88aa676c4cc5b741e21662d37c5aafa6..9ff38ace9cc06638c63bfda837174e032aadcd36 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceValidators.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceValidators.cpp
@@ -7,7 +7,9 @@ using Mantid::PythonInterface::TypedValidatorExporter;
 using namespace boost::python;
 
 /// This is the base TypedValidator for most of the WorkspaceValidators
+// clang-format off
 void export_MatrixWorkspaceValidator()
+// clang-format on
 {
   using Mantid::API::MatrixWorkspace_sptr;
   using Mantid::API::MatrixWorkspaceValidator;
@@ -44,7 +46,9 @@ void export_MatrixWorkspaceValidator()
           init<ArgType>(arg(ArgName)=DefaultValue, DocString))\
    ;
 
+// clang-format off
 void export_WorkspaceValidators()
+// clang-format on
 {
   using namespace Mantid::API;
   
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/BoundingBox.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/BoundingBox.cpp
index 015dc563df249d7974ae9224243e2f1a84323a06..207c55d8ba35fa14e9c23d502070fd2a1b8757f5 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/BoundingBox.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/BoundingBox.cpp
@@ -6,7 +6,9 @@ using Mantid::Geometry::BoundingBox;
 using Mantid::Kernel::V3D;
 using namespace boost::python;
 
+// clang-format off
 void export_BoundingBox()
+// clang-format on
 {
   class_<BoundingBox>("BoundingBox", "Constructs a zero-sized box")
     .def(init<double, double, double, double, double, double>(
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/CompAssembly.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/CompAssembly.cpp
index 9ae85503981ddd09730d8b2066f8af4b8b1e0016..1362f10ebc751cfc656c00b9fb7e7a970e4a0143 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/CompAssembly.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/CompAssembly.cpp
@@ -10,7 +10,9 @@ using namespace boost::python;
  * Enables boost.python to automatically "cast" an object up to the
  * appropriate CompAssembly leaf type 
  */
+// clang-format off
 void export_CompAssembly()
+// clang-format on
 {
   class_<CompAssembly, bases<ICompAssembly, Component>, boost::noncopyable>("CompAssembly", no_init)
     ;
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/Component.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/Component.cpp
index 02856d5765b992fc759ed31b96ea8768567ed06d..a83a0c9cb79257bce0a9f18b749c998e1ab53a5e 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/Component.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/Component.cpp
@@ -22,7 +22,9 @@ namespace
 
 }
 
+// clang-format off
 void export_Component()
+// clang-format on
 {
   class_<Component, bases<IComponent>, boost::noncopyable>("Component", no_init)
     .def("getParameterNames", &Component::getParameterNames, Component_getParameterNames())
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/Detector.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/Detector.cpp
index 33711dd7582bfb383e1a9fa90d0356226a9e5192..091bb7c5a0c1120ae66fb633489b8354062b5995 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/Detector.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/Detector.cpp
@@ -10,7 +10,9 @@ using namespace boost::python;
  * Enables boost.python to automatically "cast" an object up to the
  * appropriate Detector leaf type 
  */
+// clang-format off
 void export_Detector()
+// clang-format on
 {
   class_<Detector, bases<IDetector, ObjComponent>, boost::noncopyable>("Detector", no_init)
     ;
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/DetectorGroup.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/DetectorGroup.cpp
index f83aaef0afac5286c8ff083aeeb0ef77e1416941..c32cc8784000c2b170a2a163be2acc006acfd47c 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/DetectorGroup.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/DetectorGroup.cpp
@@ -5,7 +5,9 @@ using Mantid::Geometry::DetectorGroup;
 using Mantid::Geometry::IDetector;
 using namespace boost::python;
 
+// clang-format off
 void export_DetectorGroup()
+// clang-format on
 {
   class_<DetectorGroup, bases<IDetector>, boost::noncopyable>("DetectorGroup", no_init)
     .def("getDetectorIDs", &DetectorGroup::getDetectorIDs, "Returns the list of detector IDs within this group")
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/Goniometer.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/Goniometer.cpp
index 74b37cfebead2690565ab953180431d4bc3ec39c..b3e268583f4980986d21ed355b499a1fae71c2b3 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/Goniometer.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/Goniometer.cpp
@@ -24,7 +24,9 @@ namespace //<unnamed>
   }
 }
 
+// clang-format off
 void export_Goniometer()
+// clang-format on
 {
 
   // return_value_policy for read-only numpy array
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/Group.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/Group.cpp
index 1c12be9b7f0860221c5099dc084c30f5df556215..fcc183d733263ba15e6d8caa45e6da57f2058f76 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/Group.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/Group.cpp
@@ -4,6 +4,7 @@
 #include <boost/python/class.hpp>
 #include <boost/python/enum.hpp>
 #include <boost/python/scope.hpp>
+#include <boost/python/list.hpp>
 
 using Mantid::Geometry::Group;
 using Mantid::Geometry::SymmetryOperation;
@@ -21,9 +22,22 @@ namespace {
 
       return pythonSymOps;
     }
+
+    boost::python::list getSymmetryOperations(Group &self) {
+      const std::vector<SymmetryOperation> &symOps = self.getSymmetryOperations();
+
+      boost::python::list pythonSymOps;
+      for (auto it = symOps.begin(); it != symOps.end(); ++it) {
+        pythonSymOps.append(*it);
+      }
+
+      return pythonSymOps;
+    }
 }
 
+// clang-format off
 void export_Group()
+// clang-format on
 {
   enum_<Group::CoordinateSystem>("CoordinateSystem")
       .value("Orthogonal", Group::Orthogonal)
@@ -32,5 +46,6 @@ void export_Group()
   class_<Group, boost::noncopyable>("Group", no_init)
       .def("getOrder", &Group::order, "Returns the order of the group.")
       .def("getCoordinateSystem", &Group::getCoordinateSystem, "Returns the type of coordinate system to distinguish groups with hexagonal system definition.")
+      .def("getSymmetryOperations", &getSymmetryOperations, "Returns the symmetry operations contained in the group.")
       .def("getSymmetryOperationStrings", &getSymmetryOperationStrings, "Returns the x,y,z-strings for the contained symmetry operations.");
 }
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/ICompAssembly.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/ICompAssembly.cpp
index 5e034c71bcff67c35eaf7188f287d5e6136c53e3..5b1a3e9e44685155532b3faaa4679f2f1914f499 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/ICompAssembly.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/ICompAssembly.cpp
@@ -6,7 +6,9 @@ using Mantid::Geometry::ICompAssembly;
 using Mantid::Geometry::IComponent;
 using namespace boost::python;
 
+// clang-format off
 void export_ICompAssembly()
+// clang-format on
 {
   register_ptr_to_python<boost::shared_ptr<ICompAssembly>>();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/IComponent.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/IComponent.cpp
index 46161d9e0f0d48c8c150bec7be8f2ddffb4e0b05..c1e2e2c80d740c342a99a14dba223ec2c9bd1815 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/IComponent.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/IComponent.cpp
@@ -25,7 +25,9 @@ namespace
 
 }
 
+// clang-format off
 void export_IComponent()
+// clang-format on
 {
   register_ptr_to_python<boost::shared_ptr<IComponent>>();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/IDetector.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/IDetector.cpp
index 69bb41f1898ec1cb205d1dcc4d0add8af8f18704..ce251b6f7c48e005362c01d184354b9078cc3eee 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/IDetector.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/IDetector.cpp
@@ -6,7 +6,9 @@ using Mantid::Geometry::IDetector;
 using Mantid::Geometry::IObjComponent;
 using namespace boost::python;
 
+// clang-format off
 void export_IDetector()
+// clang-format on
 {
   register_ptr_to_python<boost::shared_ptr<IDetector>>();
   
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/IMDDimension.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/IMDDimension.cpp
index 53d53027bb19cf863e6ab272ad312ce1ea06ab9c..122dbe8a72883871ac73f563b5b5dcacfecb4a18 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/IMDDimension.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/IMDDimension.cpp
@@ -20,7 +20,9 @@ namespace
   }
 }
 
+// clang-format off
 void export_IMDDimension()
+// clang-format on
 {
   register_ptr_to_python<boost::shared_ptr<IMDDimension>>();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/IObjComponent.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/IObjComponent.cpp
index c893ff5ba0b27f86a901ce2c3bdf3370beb75381..1586524e18e949d09eb294f3e8852f5ffcf0cfb1 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/IObjComponent.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/IObjComponent.cpp
@@ -20,7 +20,9 @@ namespace
   }
 }
 
+// clang-format off
 void export_IObjComponent()
+// clang-format on
 {
   register_ptr_to_python<boost::shared_ptr<IObjComponent>>();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/Instrument.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/Instrument.cpp
index b1d3ba2f116d275d92fc168de9aebc1737220faa..52c46fc5873966405dbf58b0edd72e326af0a1a6 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/Instrument.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/Instrument.cpp
@@ -10,7 +10,9 @@ using Mantid::detid_t;
 using namespace boost::python;
 using Mantid::PythonInterface::Policies::RemoveConstSharedPtr;
 
+// clang-format off
 void export_Instrument()
+// clang-format on
 {
   register_ptr_to_python<boost::shared_ptr<Instrument>>();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/ObjCompAssembly.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/ObjCompAssembly.cpp
index 2c239635a51f8ee3b3a3bd4803778e44471a19bc..bd3f6fbee5fa02fafd634173bcc9787e83f47e7a 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/ObjCompAssembly.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/ObjCompAssembly.cpp
@@ -8,7 +8,9 @@ using Mantid::Geometry::ICompAssembly;
 using Mantid::Geometry::ObjComponent;
 using namespace boost::python;
 
+// clang-format off
 void export_ObjCompAssembly()
+// clang-format on
 {
   register_ptr_to_python<boost::shared_ptr<ObjCompAssembly>>();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/ObjComponent.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/ObjComponent.cpp
index eaa0c2e310cf24d131f403909066e373f3a8ad13..61f7b9adad51698b8e40056795faa25ac6aa09ee 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/ObjComponent.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/ObjComponent.cpp
@@ -6,7 +6,9 @@ using Mantid::Geometry::IObjComponent;
 using Mantid::Geometry::Component;
 using namespace boost::python;
 
+// clang-format off
 void export_ObjComponent()
+// clang-format on
 {
   class_<ObjComponent, boost::python::bases<IObjComponent, Component>, boost::noncopyable>("ObjComponent", no_init)
     ;
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/Object.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/Object.cpp
index af1c7ac73763247c9e7cf1c8209c1d6185e91176..bd5810cec00f2a517e017ebce6e48b0fdd8d1b6f 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/Object.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/Object.cpp
@@ -7,7 +7,9 @@ using Mantid::Geometry::Object;
 using Mantid::Geometry::BoundingBox;
 using namespace boost::python;
 
+// clang-format off
 void export_Object()
+// clang-format on
 {
   register_ptr_to_python<boost::shared_ptr<Object>>();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/OrientedLattice.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/OrientedLattice.cpp
index 6204d5f4c8ec05ad0d65395f67605c0bf7f43930..c64c2e35ed453ded719b33dc3b4fdd11265ffc60 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/OrientedLattice.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/OrientedLattice.cpp
@@ -46,7 +46,9 @@ namespace //<unnamed>
 
 }
 
+// clang-format off
 void export_OrientedLattice()
+// clang-format on
 {
   /// return_value_policy for read-only numpy array
   typedef return_value_policy<Policies::MatrixToNumpy<Converters::WrapReadOnly> > return_readonly_numpy;
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/PeakShape.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/PeakShape.cpp
index d73179460a2c683dc74921c6311d9b907a601755..095c373388c87daee6a25c7e5a9b4195469d8dba 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/PeakShape.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/PeakShape.cpp
@@ -6,7 +6,9 @@ using Mantid::Geometry::PeakShape;
 using namespace boost::python;
 
 
+// clang-format off
 void export_PeakShape()
+// clang-format on
 {
   register_ptr_to_python<Mantid::Geometry::PeakShape_sptr>();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/PointGroup.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/PointGroup.cpp
index ded37c8fca9067066849990fb059517312f1aa46..b1410156a0846f474233ac1e01781d2170249870 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/PointGroup.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/PointGroup.cpp
@@ -40,7 +40,9 @@ namespace //<unnamed>
   }
 }
 
+// clang-format off
 void export_PointGroup()
+// clang-format on
 {
   register_ptr_to_python<boost::shared_ptr<PointGroup> >();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/PointGroupFactory.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/PointGroupFactory.cpp
index 17097ab43f2e4de31f0efacd06bde5818b7a0ebf..82ba14acbe930712ccfaeed364f05fa0f84595f4 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/PointGroupFactory.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/PointGroupFactory.cpp
@@ -19,7 +19,9 @@ namespace {
     }
 }
 
+// clang-format off
 void export_PointGroupFactory()
+// clang-format on
 {
 
     class_<PointGroupFactoryImpl,boost::noncopyable>("PointGroupFactoryImpl", no_init)
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/RectangularDetector.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/RectangularDetector.cpp
index 53b01d504d092106dee969ac4ce0e5c6d2f6a5a6..7131f5f2b4706129a6cb1b7cf6a0defde4b59ed1 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/RectangularDetector.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/RectangularDetector.cpp
@@ -11,7 +11,9 @@ using namespace boost::python;
  * Enables boost.python to automatically "cast" an object up to the
  * appropriate Detector leaf type 
  */
+// clang-format off
 void export_RectangularDetector()
+// clang-format on
 {
   register_ptr_to_python<boost::shared_ptr<RectangularDetector>>();
 
@@ -33,7 +35,9 @@ void export_RectangularDetector()
     ;
 }
 
+// clang-format off
 void export_RectangularDetectorPixel()
+// clang-format on
 {
   class_<RectangularDetectorPixel, bases<Detector>, boost::noncopyable>("RectangularDetectorPixel", no_init)
     ;
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/ReferenceFrame.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/ReferenceFrame.cpp
index d5e1a4500d5c3b92c0de2fddee18089cd13c63b6..78ecba343f03d19c40ab6080d0bacd761ac57055 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/ReferenceFrame.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/ReferenceFrame.cpp
@@ -9,7 +9,9 @@ using Mantid::Geometry::ReferenceFrame;
 using Mantid::Kernel::V3D;
 using namespace boost::python;
 
+// clang-format off
 void export_ReferenceFrame()
+// clang-format on
 {
   using namespace Mantid::Geometry;
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/SpaceGroup.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/SpaceGroup.cpp
index ba7a58c1575649ee82b1da7ffd4db39926f54df5..82fcc26a38d97ea7f062e541431d1aa0e58b903a 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/SpaceGroup.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/SpaceGroup.cpp
@@ -33,7 +33,9 @@ namespace //<unnamed>
 
 }
 
+// clang-format off
 void export_SpaceGroup()
+// clang-format on
 {
   register_ptr_to_python<boost::shared_ptr<SpaceGroup> >();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/SpaceGroupFactory.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/SpaceGroupFactory.cpp
index 52fa370c732bb545b6e2a748b09d82211b66eec0..a7f266ace3983dc1fc17cb93f4989423986e9d4b 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/SpaceGroupFactory.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/SpaceGroupFactory.cpp
@@ -38,7 +38,9 @@ namespace
 
 }
 
+// clang-format off
 void export_SpaceGroupFactory()
+// clang-format on
 {
 
     class_<SpaceGroupFactoryImpl,boost::noncopyable>("SpaceGroupFactoryImpl", no_init)
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/SymmetryElement.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/SymmetryElement.cpp
index b32232a7c01866bedabbe3ea396a3f88e9ecf81e..497380d38fbbc1682f3567e80aa850581bc75f4b 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/SymmetryElement.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/SymmetryElement.cpp
@@ -19,7 +19,9 @@ namespace {
     }
 }
 
+// clang-format off
 void export_SymmetryElement()
+// clang-format on
 {
   register_ptr_to_python<boost::shared_ptr<SymmetryElement> >();  
   scope symmetryElementScope = class_<SymmetryElement, boost::noncopyable>("SymmetryElement", no_init);
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/SymmetryElementFactory.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/SymmetryElementFactory.cpp
index e9b8fbce249e81ace70b3bcab0fc9b544baeda4d..d35fb43969ff09d8d99b242d9f0937dd95329faf 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/SymmetryElementFactory.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/SymmetryElementFactory.cpp
@@ -5,7 +5,9 @@
 using namespace Mantid::Geometry;
 using namespace boost::python;
 
+// clang-format off
 void export_SymmetryElementFactory()
+// clang-format on
 {
     class_<SymmetryElementFactoryImpl,boost::noncopyable>("SymmetryElementFactoryImpl", no_init)
             .def("createSymElement", &SymmetryElementFactoryImpl::createSymElement, "Creates the symmetry element that corresponds to the supplied symmetry operation.")
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/SymmetryOperation.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/SymmetryOperation.cpp
index 59d759176210a16b552ab252dac6957fd97e6553..05a248a351113df6623a402aa315f6c240e5e10e 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/SymmetryOperation.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/SymmetryOperation.cpp
@@ -28,7 +28,9 @@ namespace //<unnamed>
   }
 }
 
+// clang-format off
 void export_SymmetryOperation()
+// clang-format on
 {
   register_ptr_to_python<boost::shared_ptr<SymmetryOperation> >();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/SymmetryOperationFactory.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/SymmetryOperationFactory.cpp
index 436815a0ae22a737785ec0dad16d97b16b714684..1d3a7a9258361eacc7421ef4354f3acfc80b3b71 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/SymmetryOperationFactory.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/SymmetryOperationFactory.cpp
@@ -21,7 +21,9 @@ namespace {
 
 }
 
+// clang-format off
 void export_SymmetryOperationFactory()
+// clang-format on
 {
     class_<SymmetryOperationFactoryImpl,boost::noncopyable>("SymmetryOperationFactoryImpl", no_init)
             .def("exists", &SymmetryOperationFactoryImpl::isSubscribed, "Returns true if the symmetry operation is supplied.")
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/UnitCell.cpp b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/UnitCell.cpp
index 471f301bbaea56353375c5d632768df11daf54c1..fc71b88a46f1d8188587b38bfa6e33b32878b50d 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/UnitCell.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/UnitCell.cpp
@@ -28,7 +28,9 @@ namespace //<unnamed>
   }
 }
 
+// clang-format off
 void export_UnitCell()
+// clang-format on
 {
   enum_<AngleUnits>("AngleUnits")
     .value("Degrees", angDegrees)
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Converters/PyObjectToVMD.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Converters/PyObjectToVMD.cpp
index 4cf0b6bff089db8a1eb1b904f69918363d7872a3..677d129c3db623673fa0cb0cf4b860c9419e5bb1 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Converters/PyObjectToVMD.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Converters/PyObjectToVMD.cpp
@@ -11,7 +11,9 @@
 #define NO_IMPORT_ARRAY
 #include <numpy/arrayobject.h>
 
+// clang-format off
 GCC_DIAG_OFF(strict-aliasing)
+// clang-format on
 
 namespace Mantid
 {
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/ArrayBoundedValidator.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/ArrayBoundedValidator.cpp
index b255501eef42a0e4a12e6ce760166312cb5abfe3..93c36da8c2882966d8a1acda41e62f25fa431206 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/ArrayBoundedValidator.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/ArrayBoundedValidator.cpp
@@ -27,7 +27,9 @@ namespace
 
 }
 
+// clang-format off
 void export_ArrayBoundedValidator()
+// clang-format on
 {
   EXPORT_ARRAYBOUNDEDVALIDATOR(double, Float);
   EXPORT_ARRAYBOUNDEDVALIDATOR(long, Int);
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/ArrayLengthValidator.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/ArrayLengthValidator.cpp
index 6504f388889714b4e368f15379b381d0914bf9c1..58fed5853cab313c7ac63412a5905929b96de789 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/ArrayLengthValidator.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/ArrayLengthValidator.cpp
@@ -34,7 +34,9 @@ namespace
   ;
 }
 
+// clang-format off
 void export_ArrayLengthValidator()
+// clang-format on
 {
   EXPORT_LENGTHVALIDATOR(double, Float);
   EXPORT_LENGTHVALIDATOR(long, Int);
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/ArrayProperty.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/ArrayProperty.cpp
index b1087288d278fb23f50136df67b6d63331058fa7..80fb6fce0037c06995cae82568a616a14321ef38 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/ArrayProperty.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/ArrayProperty.cpp
@@ -88,7 +88,9 @@ namespace
 
 }
 
+// clang-format off
 void export_ArrayProperty()
+// clang-format on
 {
   // Match the python names to their C types
   EXPORT_ARRAY_PROP(double,Float);
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/BoundedValidator.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/BoundedValidator.cpp
index e0129e22ab5462fbf347107107827772d41ae074..725aa11e9ec19a08d1bb4b381e466e96c0aeb3f7 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/BoundedValidator.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/BoundedValidator.cpp
@@ -83,7 +83,9 @@ namespace
     ;
 }
 
+// clang-format off
 void export_BoundedValidator()
+// clang-format on
 {
   EXPORT_BOUNDEDVALIDATOR(double, Float);
   EXPORT_BOUNDEDVALIDATOR(long, Int);
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/CompositeValidator.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/CompositeValidator.cpp
index 3222a68833a6174b172604f9b84c377f65918abc..64c202f1b2d9ace9ed69d56bb5c5b462b49adfec 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/CompositeValidator.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/CompositeValidator.cpp
@@ -36,7 +36,9 @@ namespace
   }
 }
 
+// clang-format off
 void export_CompositeValidator()
+// clang-format on
 {
   class_<CompositeValidator, bases<IValidator>, boost::noncopyable>("CompositeValidator")
     .def("__init__", make_constructor(&createCompositeValidator, default_call_policies(),
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/ConfigService.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/ConfigService.cpp
index 8d6d56263ed0e9dccac7257fa2a35f91ad4fe464..1cb3e06dce681706daa835b50a4fa2f3a7f160a8 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/ConfigService.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/ConfigService.cpp
@@ -36,7 +36,9 @@ namespace
   BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(getString_Overload, getString, 1, 2)
 }
 
+// clang-format off
 void export_ConfigService()
+// clang-format on
 {
   using Mantid::PythonInterface::std_vector_exporter;
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/DataItem.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/DataItem.cpp
index e90ce011f8e91a4bbade11987a96ebfe3f71e254..ddcfd758bfc1e9162cba7d86aeb9af9e7fe21e6c 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/DataItem.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/DataItem.cpp
@@ -6,7 +6,9 @@
 using Mantid::Kernel::DataItem;
 using namespace boost::python;
 
+// clang-format off
 void export_DataItem()
+// clang-format on
 {
   register_ptr_to_python<boost::shared_ptr<DataItem>>();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/DateAndTime.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/DateAndTime.cpp
index a7c64fc927716e381c1bdd3d246bc5de4284039f..8c567746bd667815407025cbd35a2ef49cd8f30d 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/DateAndTime.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/DateAndTime.cpp
@@ -15,7 +15,9 @@ std::string ISO8601StringPlusSpace(DateAndTime & self)
   return self.toISO8601String()+" ";
 }
 
+// clang-format off
 void export_DateAndTime()
+// clang-format on
 {
   class_<DateAndTime>("DateAndTime", no_init)
     // Constructors
@@ -39,7 +41,9 @@ void export_DateAndTime()
   ;
 }
 
+// clang-format off
 void export_time_duration()
+// clang-format on
 {
   class_<time_duration>("time_duration", no_init)
     .def("hours", &time_duration::hours, "Returns the normalized number of hours")
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/DeltaEMode.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/DeltaEMode.cpp
index 325e1683c9baf7b515099314241d75c01b7a0834..95805dd2073af47fc3923601d62c40a6ab9f50d6 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/DeltaEMode.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/DeltaEMode.cpp
@@ -9,7 +9,9 @@ using Mantid::Kernel::DeltaEMode;
 namespace Policies = Mantid::PythonInterface::Policies;
 using namespace boost::python;
 
+// clang-format off
 void export_DeltaEMode()
+// clang-format on
 {
   enum_<Mantid::Kernel::DeltaEMode::Type>("DeltaEModeType")
     .value("Elastic", DeltaEMode::Elastic)
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/EnabledWhenProperty.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/EnabledWhenProperty.cpp
index d2b8a15ee8e58097a693694248fba549b3025dcd..37a4485452ba6cec86f9687a1ee815dcd597bb83 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/EnabledWhenProperty.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/EnabledWhenProperty.cpp
@@ -5,7 +5,9 @@
 using namespace Mantid::Kernel;
 using namespace boost::python;
 
+// clang-format off
 void export_EnabledWhenProperty()
+// clang-format on
 {
   // State enumeration
   enum_<ePropertyCriterion>("PropertyCriterion")
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/FacilityInfo.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/FacilityInfo.cpp
index 7d8144fb52e36e07453f5b71bc8024e573aafc27..05cadb4de7b2b4d17f9596a35b29df721395825b 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/FacilityInfo.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/FacilityInfo.cpp
@@ -7,7 +7,9 @@ using Mantid::Kernel::FacilityInfo;
 using Mantid::Kernel::InstrumentInfo;
 using namespace boost::python;
 
+// clang-format off
 void export_FacilityInfo()
+// clang-format on
 {
 
   register_ptr_to_python<FacilityInfo*>();
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/FilteredTimeSeriesProperty.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/FilteredTimeSeriesProperty.cpp
index 9d29696e5f7c2082b71519371daaf6eba12dcfcb..49b3e1adfc50e5801c3d3db185f7cce7ed49da8f 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/FilteredTimeSeriesProperty.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/FilteredTimeSeriesProperty.cpp
@@ -24,7 +24,9 @@ namespace
       ;
 }
 
+// clang-format off
 void export_FilteredTimeSeriesProperty()
+// clang-format on
 {
   EXPORT_FILTEREDTIMESERIES_PROP(double, Float);
   EXPORT_FILTEREDTIMESERIES_PROP(bool, Bool);
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/IPropertyManager.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/IPropertyManager.cpp
index d40c6cb68a6f4ec08d71d1da0ecae80cd8595cfa..4e686b53126341c74a59e6ff4b04a8f0b1a34723 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/IPropertyManager.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/IPropertyManager.cpp
@@ -120,7 +120,9 @@ namespace
 
 }
 
+// clang-format off
 void export_IPropertyManager()
+// clang-format on
 {
   register_ptr_to_python<IPropertyManager*>();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/IPropertySettings.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/IPropertySettings.cpp
index 5e8d17528bef7ccebdaae9642862a55afd0cdaae..426df48a16b92f5b4fcdd843918861eca3cb2e0d 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/IPropertySettings.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/IPropertySettings.cpp
@@ -6,7 +6,9 @@
 using Mantid::Kernel::IPropertySettings;
 using namespace boost::python;
 
+// clang-format off
 void export_IPropertySettings()
+// clang-format on
 {
   register_ptr_to_python<IPropertySettings*>();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/IValidator.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/IValidator.cpp
index 44f793b69fcb65fca0a2d93f46c38ad3cf9b7a54..995e528b72cd562179af200d88319491464894ad 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/IValidator.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/IValidator.cpp
@@ -5,7 +5,9 @@
 using Mantid::Kernel::IValidator;
 using namespace boost::python;
 
+// clang-format off
 void export_IValidator()
+// clang-format on
 {
   register_ptr_to_python<boost::shared_ptr<IValidator>>();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/InstrumentInfo.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/InstrumentInfo.cpp
index 6ec736305bd78d85971bdae24258ef48cbbc7be2..361bfa76ec3dd08da1cf0421d35357914d66099c 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/InstrumentInfo.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/InstrumentInfo.cpp
@@ -7,7 +7,9 @@
 using Mantid::Kernel::InstrumentInfo;
 using namespace boost::python;
 
+// clang-format off
 void export_InstrumentInfo()
+// clang-format on
 {
   using namespace Mantid::PythonInterface;
   std_vector_exporter<InstrumentInfo>::wrap("std_vector_InstrumentInfo");
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/ListValidator.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/ListValidator.cpp
index be87143732b20dbd5866c3bdb4b649701b76e572..e1f5c4b15836d448ad089c2c49ef5946a38da51c 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/ListValidator.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/ListValidator.cpp
@@ -39,7 +39,9 @@ namespace
 
 }
 
+// clang-format off
 void export_ListValidator()
+// clang-format on
 {
   EXPORT_LISTVALIDATOR(std::string, String);
   EXPORT_LISTVALIDATOR(long, Int);
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/LogFilter.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/LogFilter.cpp
index 6647cea511699746221a8f47472a9934f5fb09d9..f837a84358855404b120f1468e1485562947f044 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/LogFilter.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/LogFilter.cpp
@@ -8,7 +8,9 @@ using Mantid::Kernel::Property;
 
 using namespace boost::python;
 
+// clang-format off
 void export_LogFilter()
+// clang-format on
 {
   class_<LogFilter,boost::noncopyable>("LogFilter", 
                                         init<const Property*>("Creates a log filter using the log to be filtered"))
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Logger.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Logger.cpp
index abf45b7d820aeb2e61d42c7728793c971b38277a..ccd697878b9b6c9414f48792d532c91ec219cd18 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Logger.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Logger.cpp
@@ -20,7 +20,9 @@ namespace
   }
 }
 
+// clang-format off
 void export_Logger()
+// clang-format on
 {
   register_ptr_to_python<boost::shared_ptr<Logger>>();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/MandatoryValidator.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/MandatoryValidator.cpp
index 98a389f0f2fe7c710b081e4775beb661688b2b3e..debfe9081c2ae4d2381c062051d7df569583f2bc 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/MandatoryValidator.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/MandatoryValidator.cpp
@@ -15,7 +15,9 @@ namespace
     ;
 }
 
+// clang-format off
 void export_MandatoryValidator()
+// clang-format on
 {
   EXPORT_MANDATORYVALIDATOR(double, Float);
   EXPORT_MANDATORYVALIDATOR(long, Int);
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Material.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Material.cpp
index 9de29e96cd4d8b0f4e585a2b2d79e6bdd502b5a3..37436b0ff2abddbc8c1202f6298792897c031c5d 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Material.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Material.cpp
@@ -9,7 +9,9 @@ using Mantid::Kernel::Material;
 using Mantid::PhysicalConstants::NeutronAtom;
 using namespace boost::python;
 
+// clang-format off
 void export_Material()
+// clang-format on
 {
   register_ptr_to_python<Material*>();
   register_ptr_to_python<boost::shared_ptr<Material> >();
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Memory.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Memory.cpp
index 46e6432c8ee5014d0ecb86e2e702a4c82479d56f..4707cf36f216efcbd33447c793b3f63ff6f70d8a 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Memory.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Memory.cpp
@@ -4,7 +4,9 @@
 using Mantid::Kernel::MemoryStats;
 using namespace boost::python;
 
+// clang-format off
 void export_MemoryStats()
+// clang-format on
 {
 
   class_< MemoryStats>("MemoryStats", init<>("Construct MemoryStats object."))
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/NullValidator.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/NullValidator.cpp
index 39418a1cbbc8357e92ccac808b3bc2a51c9d12a3..0cf927b618dafe009ef1f5c7ffd8436bb22ed667 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/NullValidator.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/NullValidator.cpp
@@ -7,7 +7,9 @@ using Mantid::Kernel::NullValidator;
 using Mantid::Kernel::IValidator;
 using namespace boost::python;
 
+// clang-format off
 void export_NullValidator()
+// clang-format on
 {
   register_ptr_to_python<boost::shared_ptr<NullValidator>>();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/ProgressBase.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/ProgressBase.cpp
index 6943676f17cb2c3c6393e2bf9295e2352ee250a4..9fb35344e360a2ba2abb1413c1c6c3ea31205fae 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/ProgressBase.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/ProgressBase.cpp
@@ -4,7 +4,9 @@
 using Mantid::Kernel::ProgressBase;
 using namespace boost::python;
 
+// clang-format off
 void export_ProgressBase()
+// clang-format on
 {
   class_<ProgressBase,boost::noncopyable>("ProgressBase", no_init)
     .def("report", (void (ProgressBase::*)())&ProgressBase::report, "Increment the progress by 1 and report with no message")
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Property.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Property.cpp
index 1b85f6db92a2f2fbffc4f1dd9508290d5880b4a2..5ecd1107e1242497589fdd6cb63c476da684ed2d 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Property.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Property.cpp
@@ -16,7 +16,9 @@ using Mantid::PythonInterface::std_vector_exporter;
 using namespace boost::python;
 
 
+// clang-format off
 void export_Property()
+// clang-format on
 {
   register_ptr_to_python<Property*>();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/PropertyHistory.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/PropertyHistory.cpp
index 78f829ce76b1fe97fd9094a6b731761e6be0cbd1..5915f2910f98bb1f876132aa0b5a754938a1ca0d 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/PropertyHistory.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/PropertyHistory.cpp
@@ -9,7 +9,9 @@
 using Mantid::Kernel::PropertyHistory;
 using namespace boost::python;
 
+// clang-format off
 void export_PropertyHistory()
+// clang-format on
 {
   register_ptr_to_python<Mantid::Kernel::PropertyHistory_sptr>();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/PropertyManager.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/PropertyManager.cpp
index f958225431e252a21a0e8b595a1e540374485840..c7b6b16f0354cb52423aedf38bb4450f90ebd1da 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/PropertyManager.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/PropertyManager.cpp
@@ -26,7 +26,9 @@ namespace
 
 }
 
+// clang-format off
 void export_PropertyManager()
+// clang-format on
 {
   register_ptr_to_python<boost::shared_ptr<PropertyManager>>();
   class_<PropertyManager, bases<IPropertyManager>, boost::noncopyable>("PropertyManager")
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/PropertyWithValue.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/PropertyWithValue.cpp
index 7560ad24547012d7368d32e53ef55959ed031a04..a7eb9bd5f20f23d20b5d6ac2253fc1e920ec759f 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/PropertyWithValue.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/PropertyWithValue.cpp
@@ -2,7 +2,9 @@
 
 using Mantid::PythonInterface::PropertyWithValueExporter;
 
+// clang-format off
 void export_BasicPropertyWithValueTypes()
+// clang-format on
 {
   // cut down copy-and-paste code
 #define EXPORT_PROP(CType, ExportName) \
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Quat.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Quat.cpp
index 94f32da09029f92434058341bbd9930bb97a6e49..0c34adcab3322472aa68838908d103cd24efcbf8 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Quat.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Quat.cpp
@@ -18,7 +18,9 @@ using boost::python::return_value_policy;
 /**
  * Python exports of the Mantid::Kernel::Quat class.
  */
+// clang-format off
 void export_Quat()
+// clang-format on
 {
   //Quat class
   class_< Quat >("Quat", "Quaternions are the 3D generalization of complex numbers. "
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Statistics.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Statistics.cpp
index 3bfa9244083a18adb81d5a276d1f037ac23bf52d..94a0138cb1bd38f67152bce54e0f6d1f7326a834 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Statistics.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Statistics.cpp
@@ -213,7 +213,9 @@ namespace
 
 // -------------------------------------- Exports start here --------------------------------------
 
+// clang-format off
 void export_Statistics()
+// clang-format on
 {
   // typedef std::vector --> numpy array result converter
   typedef return_value_policy<Policies::VectorToNumpy> ReturnNumpyArray;
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/StlContainers.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/StlContainers.cpp
index 42853b3c4854ace8edf3299dd8d8569e8bc27d96..95251d4eeee72902059909cb71f4ac5e140f2fdd 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/StlContainers.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/StlContainers.cpp
@@ -5,7 +5,9 @@
 using Mantid::PythonInterface::std_vector_exporter;
 using Mantid::PythonInterface::std_set_exporter;
 
+// clang-format off
 void exportStlContainers()
+// clang-format on
 {
     // Export some frequently used stl containers
   // std::vector
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/TimeSeriesProperty.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/TimeSeriesProperty.cpp
index 2f9bf530009231a934726719b8dbaad4acd44bf5..e40411537a4181ba4ee0e4349e52f84a1b2af5c1 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/TimeSeriesProperty.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/TimeSeriesProperty.cpp
@@ -40,33 +40,45 @@ namespace
       ;
 }
 
+// clang-format off
 void export_TimeSeriesProperty_Double()
+// clang-format on
 {
   EXPORT_TIMESERIES_PROP(double, Float);
 }
 
+// clang-format off
 void export_TimeSeriesProperty_Bool()
+// clang-format on
 {
   EXPORT_TIMESERIES_PROP(bool, Bool);
 }
 
+// clang-format off
 void export_TimeSeriesProperty_Int32()
+// clang-format on
 {
   EXPORT_TIMESERIES_PROP(int32_t, Int32);
 }
 
+// clang-format off
 void export_TimeSeriesProperty_Int64()
+// clang-format on
 {
   EXPORT_TIMESERIES_PROP(int64_t, Int64);
 }
 
+// clang-format off
 void export_TimeSeriesProperty_String()
+// clang-format on
 {
   EXPORT_TIMESERIES_PROP(std::string, String);
 }
 
 
+// clang-format off
 void export_TimeSeriesPropertyStatistics()
+// clang-format on
 {
   class_<Mantid::Kernel::TimeSeriesPropertyStatistics>("TimeSeriesPropertyStatistics", no_init)
     .add_property("minimum", &Mantid::Kernel::TimeSeriesPropertyStatistics::minimum)
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Unit.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Unit.cpp
index 479d4a2b295eb23b2be1a0cf2367470c1293efeb..53635677a213bc73544621bba5d719b8106e1109 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Unit.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Unit.cpp
@@ -31,7 +31,9 @@ namespace
 
 }
 
+// clang-format off
 void export_Unit()
+// clang-format on
 {
   register_ptr_to_python<boost::shared_ptr<Unit>>();
 
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/UnitConversion.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/UnitConversion.cpp
index 65de0e2ff577fc81205e6cca268ab33378dcd3e6..2710396f41e1eb754f7a2dd2437d4d7a70e0b8ba 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/UnitConversion.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/UnitConversion.cpp
@@ -6,7 +6,9 @@ using Mantid::Kernel::UnitConversion;
 using Mantid::Kernel::DeltaEMode;
 using namespace boost::python;
 
+// clang-format off
 void export_UnitConversion()
+// clang-format on
 {
   // Function pointer typedef
   typedef double (*StringVersion)(const std::string & src, const std::string & dest,
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/UnitFactory.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/UnitFactory.cpp
index bd0850258e48776cbdd8b281d18e539e14a6debf..47afdf578fcb77cfcaa6d33e0db52f8f13b838e1 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/UnitFactory.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/UnitFactory.cpp
@@ -12,7 +12,9 @@ namespace Policies = Mantid::PythonInterface::Policies;
 namespace Converters = Mantid::PythonInterface::Converters;
 using namespace boost::python;
 
+// clang-format off
 void export_UnitFactory()
+// clang-format on
 {
   class_<UnitFactoryImpl, boost::noncopyable>("UnitFactoryImpl", no_init)
     .def("create", &UnitFactoryImpl::create, "Creates a named unit if it exists in the factory")
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/UnitLabel.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/UnitLabel.cpp
index 661eb18e8f104716d671b0e8b28a2e0f748e4c44..241a50504f13d4942096bdd9140feb3fedff6407 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/UnitLabel.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/UnitLabel.cpp
@@ -46,7 +46,9 @@ namespace
 
 }
 
+// clang-format off
 void export_UnitLabel()
+// clang-format on
 {
   class_<UnitLabel>("UnitLabel", no_init)
     .def("__init__",
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Units.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Units.cpp
index 0c60a6796839c0bd1b43ee42bd2ff645e42c6085..602cfa128083942ab292895c85eb6322364cb945 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Units.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/Units.cpp
@@ -24,7 +24,9 @@ namespace
 
 // We only export the concrete unit classes that
 // have additional functionality over the base class
+// clang-format off
 void export_Label()
+// clang-format on
 {
   class_<Label, bases<Unit>, boost::noncopyable>("Label", no_init)
     .def("setLabel", &setLabelFromStdString,
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/V3D.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/V3D.cpp
index 845ecc46f1b0f41034a3d0d4e2512ee5340bb13d..0c725af643ff4645e87bddc8b6be24e5b9703d54 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/V3D.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/V3D.cpp
@@ -29,7 +29,9 @@ namespace
 }
 
 
+// clang-format off
 void export_V3D()
+// clang-format on
 {
   //V3D class
   class_< V3D >("V3D",init<>("Construct a V3D at the origin"))
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/VMD.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/VMD.cpp
index 42ec793e917ce3389ad062e0e95c4cd0c70a6633..d6831df4826beaaf10869d18f6ef0bfc3e0f2791 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/VMD.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/VMD.cpp
@@ -47,7 +47,9 @@ namespace
   }
 }
 
+// clang-format off
 void export_VMD()
+// clang-format on
 {
   class_<VMD>("VMD", init<>("Default constructor gives an object with 1 dimension"))
     .def(init<VMD_t,VMD_t>("Constructs a 2 dimensional vector at the point given", args(("val0"),("val1"))))
diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/VisibleWhenProperty.cpp b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/VisibleWhenProperty.cpp
index 59ded113a4daf7b2c7b9af02374dfec1b025466c..5b9166a6e264d2097da97b3c2dcf9f8058120bf9 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/VisibleWhenProperty.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/src/Exports/VisibleWhenProperty.cpp
@@ -4,7 +4,9 @@
 using namespace Mantid::Kernel;
 using namespace boost::python;
 
+// clang-format off
 void export_VisibleWhenProperty()
+// clang-format on
 {
   class_<VisibleWhenProperty, bases<EnabledWhenProperty>,
          boost::noncopyable>("VisibleWhenProperty", no_init)
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py
index b8b09e7549e5c7dd2d377601a1cad53ce09e26b9..557fec9a92f6aeae24edfa9b6bb1e21bd11a19a2 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py
@@ -1,4 +1,4 @@
-#pylint: disable=no-init,invalid-name
+#pylint: disable=no-init,invalid-name,too-many-instance-attributes
 from mantid.api import *
 from mantid.kernel import *
 import os
@@ -182,7 +182,7 @@ class ExportSampleLogsToCSVFile(PythonAlgorithm):
             ofile = open(self._outputfilename, "w")
             ofile.write(wbuf)
             ofile.close()
-        except IOError as err:
+        except IOError:
             raise NotImplementedError("Unable to write file %s. Check permission." % (self._outputfilename))
 
         return
@@ -232,7 +232,7 @@ class ExportSampleLogsToCSVFile(PythonAlgorithm):
 
         wbuf = ""
         currtimeindexes = []
-        for i in xrange(len(logtimeslist)):
+        for dummy_i in xrange(len(logtimeslist)):
             currtimeindexes.append(0)
         nextlogindexes = []
 
@@ -271,7 +271,7 @@ class ExportSampleLogsToCSVFile(PythonAlgorithm):
             ofile = open(self._outputfilename, "w")
             ofile.write(wbuf)
             ofile.close()
-        except IOError as err:
+        except IOError:
             raise NotImplementedError("Unable to write file %s. Check permission." % (self._outputfilename))
 
         return
@@ -334,7 +334,6 @@ class ExportSampleLogsToCSVFile(PythonAlgorithm):
         wbuf = "%.6f\t%.6f\t" % (abstime, reltime)
 
         # Log valuess
-        tmplogvalues = []
         for i in xrange(len(logvaluelist)):
             timeindex = currtimeindexes[i]
             if not i in nexttimelogindexes:
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GenerateGroupingSNSInelastic.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GenerateGroupingSNSInelastic.py
index c01f61cbfe01f62396ba7682f469ae45ba0c6b96..f165df35ac187caa8d313e0bc285d91f3fd30a83 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GenerateGroupingSNSInelastic.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GenerateGroupingSNSInelastic.py
@@ -3,7 +3,7 @@ import mantid
 import mantid.api
 import mantid.simpleapi
 import mantid.kernel
-from numpy import arange
+import numpy
 
 
 class GenerateGroupingSNSInelastic(mantid.api.PythonAlgorithm):
@@ -35,7 +35,8 @@ class GenerateGroupingSNSInelastic(mantid.api.PythonAlgorithm):
 
         self.declareProperty("AlongTubes", "1",mantid.kernel.StringListValidator(py), "Number of pixels across tubes to be grouped")
         self.declareProperty("AcrossTubes", "1", mantid.kernel.StringListValidator(px), "Number of pixels across tubes to be grouped")
-        self.declareProperty("Instrument", instrument[0], mantid.kernel.StringListValidator(instrument), "The instrument for wich to create grouping")
+        self.declareProperty("Instrument", instrument[0], mantid.kernel.StringListValidator(instrument),
+                             "The instrument for wich to create grouping")
         f=mantid.api.FileProperty("Filename","",mantid.api.FileAction.Save,".xml")
 
         self.declareProperty(f,"Output filename.")
@@ -65,7 +66,7 @@ class GenerateGroupingSNSInelastic(mantid.api.PythonAlgorithm):
         y=__w.extractY()
         numdet=(y[y==1]).size
 
-        spectra = arange(numdet).reshape(-1,8,128)
+        spectra = numpy.arange(numdet).reshape(-1,8,128)
 
         banks = numdet/8/128
 
@@ -76,9 +77,9 @@ class GenerateGroupingSNSInelastic(mantid.api.PythonAlgorithm):
 
 
         groupnum = 0
-        for i in arange(banks):
-            for j in arange(8/pixelsx)*pixelsx:
-                for k in arange(128/pixelsy)*pixelsy:
+        for i in numpy.arange(banks):
+            for j in numpy.arange(8/pixelsx)*pixelsx:
+                for k in numpy.arange(128/pixelsy)*pixelsy:
 
                     groupname = str(groupnum)
                     ids = spectra[i, j:j+pixelsx, k:k+pixelsy].reshape(-1)
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GetEiT0atSNS.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GetEiT0atSNS.py
index 582beaf012a82ded5ae58c5decf28dc40bc6055b..5f9552241b415c145c0bebc5cacde24ed7426059 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GetEiT0atSNS.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GetEiT0atSNS.py
@@ -22,7 +22,8 @@ class GetEiT0atSNS(mantid.api.PythonAlgorithm):
     def PyInit(self):
         """ Declare properties
         """
-        self.declareProperty(mantid.api.WorkspaceProperty("MonitorWorkspace", "",direction=mantid.kernel.Direction.InOut), "Monitor workspace")
+        self.declareProperty(mantid.api.WorkspaceProperty("MonitorWorkspace", "",direction=mantid.kernel.Direction.InOut),
+                             "Monitor workspace")
         self.declareProperty("IncidentEnergyGuess",-1.,doc="Incident energy guess")
         self.declareProperty("Ei",0.0,mantid.kernel.Direction.Output)
         self.declareProperty("T0",0.0,mantid.kernel.Direction.Output)
@@ -72,8 +73,8 @@ class GetEiT0atSNS(mantid.api.PythonAlgorithm):
                 wtemp=mantid.simpleapi.ChangeBinOffset(wm,t1f*16667,sp1,sp1)
                 wtemp=mantid.simpleapi.ChangeBinOffset(wtemp,t2f*16667,sp2,sp2)
                 wtemp=mantid.simpleapi.Rebin(InputWorkspace=wtemp,Params="1",PreserveEvents=True)
-
-                alg=mantid.simpleapi.GetEi(InputWorkspace=wtemp,Monitor1Spec=sp1+1,Monitor2Spec=sp2+1,EnergyEstimate=EGuess)   #Run GetEi algorithm
+                #Run GetEi algorithm
+                alg=mantid.simpleapi.GetEi(InputWorkspace=wtemp,Monitor1Spec=sp1+1,Monitor2Spec=sp2+1,EnergyEstimate=EGuess)
                 Ei=alg[0]
                 Tzero=alg[3]                                        #Extract incident energy and T0
                 mantid.simpleapi.DeleteWorkspace(wtemp)
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/IndirectTransmission.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/IndirectTransmission.py
index e7d30359777d897fe2065f207b9fbcb296b37a9f..eb4fd986d3f4a65d6f593ddea2023f5d0b3000f3 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/IndirectTransmission.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/IndirectTransmission.py
@@ -157,18 +157,15 @@ class IndirectTransmission(PythonAlgorithm):
         @param workspace Name of workspace to extract from
         @return Fixed energy value
         """
+        from IndirectCommon import getEfixed
 
-        ws = mtd[workspace]
-
-        # Try to get efixed from the parameters first
         try:
-            instrument = ws.getInstrument()
-            efixed = instrument.getNumberParameter('efixed-val')[0]
-        except IndexError:
-            efixed = 0.0
+            # Try to get efixed from the parameters first
+            efixed = getEfixed(workspace)
 
-        # If that fails then get it by taking from group of all detectors
-        if efixed == 0.0:
+        except ValueError:
+            # If that fails then get it by taking from group of all detectors
+            ws = mtd[workspace]
             spectra_list = range(0, ws.getNumberHistograms())
             GroupDetectors(InputWorkspace=workspace,
                            OutputWorkspace=workspace,
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LRPrimaryFraction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LRPrimaryFraction.py
index 9c0c3994fd85a2a27fa2582fa5c4515fe3b9eb0a..21b91e6452b6e8cbc4e7c695b673c96c6e697408 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LRPrimaryFraction.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LRPrimaryFraction.py
@@ -30,10 +30,10 @@ class LRPrimaryFraction(PythonAlgorithm):
 
     def PyExec(self):
         workspace = self.getProperty("InputWorkspace").value
-        
+
         # Background offset in number of pixels
         bck_width = self.getProperty("BackgroundWidth").value
-        
+
         # Signal region
         [peak_from_pixel, peak_to_pixel] = self.getProperty("SignalRange").value
 
@@ -60,12 +60,14 @@ class LRPrimaryFraction(PythonAlgorithm):
         avg_bck = 0
         avg_bck_err = 0
         for i in range(bck_from_pixel, peak_from_pixel):
-            if data_e[i] == 0: data_e[i] = 1.0
+            if data_e[i] == 0:
+                data_e[i] = 1.0
             avg_bck += data_y[i] / data_e[i] / data_e[i]
             avg_bck_err += 1.0 / data_e[i] / data_e[i]
 
         for i in range(peak_to_pixel+1, bck_to_pixel+1):
-            if data_e[i] == 0: data_e[i] = 1
+            if data_e[i] == 0:
+                data_e[i] = 1
             avg_bck += data_y[i] / data_e[i] / data_e[i]
             avg_bck_err += 1.0 / data_e[i] / data_e[i]
 
@@ -78,7 +80,8 @@ class LRPrimaryFraction(PythonAlgorithm):
         specular_counts_err = 0
         for i in range(peak_from_pixel, peak_to_pixel+1):
             specular_counts += data_y[i] - avg_bck
-            if data_e[i] == 0: data_e[i] = 1.0
+            if data_e[i] == 0:
+                data_e[i] = 1.0
             specular_counts_err += data_e[i] * data_e[i] + avg_bck_err * avg_bck_err
         specular_counts_err = math.sqrt(specular_counts_err)
 
@@ -87,7 +90,7 @@ class LRPrimaryFraction(PythonAlgorithm):
         # Specular ratio
         r = specular_counts / total_counts
         r_err = r * math.sqrt(specular_counts_err * specular_counts_err / specular_counts / specular_counts) + 1.0/total_counts
-        
+
         self.setProperty("ScalingFactor", [r, r_err])
 
         logger.information("Total counts:       %s" % total_counts)
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LRScalingFactors.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LRScalingFactors.py
new file mode 100644
index 0000000000000000000000000000000000000000..b2be79cfd2604d39c46b78cc93225bab7317d299
--- /dev/null
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LRScalingFactors.py
@@ -0,0 +1,396 @@
+#pylint: disable=invalid-name
+import numpy
+import os
+from mantid.api import *
+from mantid.simpleapi import *
+from mantid.kernel import *
+
+class LRScalingFactors(PythonAlgorithm):
+    """
+        This algorithm runs through a sequence of direct beam data sets
+        to extract scaling factors. The method was developed by J. Ankner (ORNL).
+
+        As we loop through, we find matching data sets with the only
+        difference between the two is an attenuator.
+        The ratio of those matching data sets allows use to rescale
+        a direct beam run taken with a larger number of attenuators
+        to a standard data set taken with tighter slit settings and
+        no attenuators.
+
+        The normalization run for a data set taken in a given slit setting
+        configuration can then be expressed in terms of the standard 0-attenuator
+        data set with:
+            D_i = F_i D_0
+
+        Here's an example of runs and how they are related to F.
+
+        run: 55889, att: 0, s1: 0.26, s2: 0.26
+        run: 55890, att: 1, s1: 0.26, s2: 0.26
+        run: 55891, att: 1, s1: 0.33, s2: 0.26 --> F = 55891 / 55890
+        run: 55892, att: 1, s1: 0.45, s2: 0.26 --> F = 55892 / 55890
+        run: 55895, att: 1, s1: 0.81, s2: 0.26
+        run: 55896, att: 2, s1: 0.81, s2: 0.26
+        run: 55897, att: 2, s1: 1.05, s2: 0.35 --> F = 55897 / 55896 * 55895 / 55890
+
+    """
+    def category(self):
+        return "Reflectometry\\SNS"
+
+    def name(self):
+        return "LiquidsReflectometryScalingFactors"
+
+    def version(self):
+        return 1
+
+    def summary(self):
+        return "Liquids Reflectometer (REFL) scaling factor calculation"
+
+    def PyInit(self):
+        self.declareProperty(IntArrayProperty("DirectBeamRuns", []),
+                             "Run number of the signal run to use")
+        self.declareProperty(IntArrayProperty("Attenuators", []),
+                             "Number of attenuators for each run")
+        self.declareProperty(FloatArrayProperty("TOFRange", [10000., 35000.],
+                                                FloatArrayLengthValidator(2),
+                                                direction=Direction.Input),
+                                                "TOF range to use")
+        self.declareProperty(IntArrayProperty("SignalPeakPixelRange", [150, 160]),
+                                              "Pixel range defining the data peak")
+        self.declareProperty(IntArrayProperty("SignalBackgroundPixelRange", [147, 163]),
+                                              "Pixel range defining the background")
+        self.declareProperty(IntArrayProperty("LowResolutionPixelRange", [94, 160],
+                                              IntArrayLengthValidator(2),
+                                              direction=Direction.Input),
+                                              "Pixel range defining the region to use in the low-resolution direction")
+        self.declareProperty("IncidentMedium", "Air", doc="Name of the incident medium")
+        self.declareProperty("FrontSlitName", "S1", doc="Name of the front slit")
+        self.declareProperty("BackSlitName", "Si", doc="Name of the back slit")
+        self.declareProperty("TOFSteps", 50.0, doc="TOF step size")
+        self.declareProperty(FileProperty("ScalingFactorFile","",
+                                          action=FileAction.Save,
+                                          extensions=['cfg']))
+
+    def PyExec(self):
+        # Verify whether we have a sorted list of runs.
+        data_runs = self.getProperty("DirectBeamRuns").value
+
+        # Check whether the supplied attenuation array is of the same length,
+        # otherwise we will deduce the number of attenuators.
+        attenuators = self.getProperty("Attenuators").value
+        have_attenuator_info = False
+        if len(attenuators)==0:
+            logger.notice("No attenuator information supplied: will be determined.")
+        elif not len(attenuators) == len(data_runs):
+            logger.error("Attenuation list should be of the same length as the list of runs")
+        else:
+            have_attenuator_info = True
+        if have_attenuator_info is False:
+            attenuators = len(data_runs)*[0]
+            
+        # Get the slit information
+        front_slit = self.getProperty("FrontSlitName").value
+        back_slit = self.getProperty("BackSlitName").value
+        medium = self.getProperty("IncidentMedium").value
+
+        # Get peak ranges
+        peak_range = self.getProperty("SignalPeakPixelRange").value
+        background_range = self.getProperty("SignalBackgroundPixelRange").value
+
+        # Supply good values for peak ranges
+        # If we supplied two values, use those boundaries for each run
+        if len(peak_range)==2:
+            x_min = int(peak_range[0])
+            x_max = int(peak_range[1])
+            peak_range = 2*len(data_runs)*[0]
+            for i in range(len(data_runs)):
+                peak_range[2*i] = x_min
+                peak_range[2*i+1] = x_max
+        elif len(peak_range) < 2:
+            raise RuntimeError, "SignalPeakPixelRange should have a length of at least 2."
+
+        if len(background_range)==2:
+            x_min = int(background_range[0])
+            x_max = int(background_range[1])
+            background_range = 2*len(data_runs)*[0]
+            for i in range(len(data_runs)):
+                background_range[2*i] = x_min
+                background_range[2*i+1] = x_max
+        elif len(background_range) < 2:
+            raise RuntimeError, "SignalBackgroundPixelRange should have a length of at least 2."
+
+        # Check that the peak range arrays are of the proper length
+        if not (len(peak_range) == 2*len(data_runs) \
+                and len(background_range) == 2*len(data_runs)):
+            raise RuntimeError, "Supplied peak/background arrays should be of the same length as the run array."
+
+        # Slit information for the previous run (see loop below)
+        previous_slits = None
+
+        # Previous processed workspace
+        previous_ws = None
+
+        # Number of attenuators for the run being considered
+        n_attenuator = 0
+
+        # Transition references used to propagate the attenuation
+        references = {}
+
+        # Wavelength value
+        wavelength = None
+
+        # Scaling factor output
+        scaling_factors = []
+
+        # Run through the runs
+        for i in range(len(data_runs)):
+            run = data_runs[i]
+            workspace_name = "REF_L_%s" % int(run)
+            workspace = LoadEventNexus("REF_L_%s" % run,
+                                       OutputWorkspace = workspace_name)
+
+            # Get S1H, S2H, S1W, S2W
+            s1h = abs(workspace.getRun().getProperty("%sVHeight" % front_slit).value[0])
+            s1w = abs(workspace.getRun().getProperty("%sHWidth" % front_slit).value[0])
+            try:
+                s2h = abs(workspace.getRun().getProperty("%sVHeight" % back_slit).value[0])
+                s2w = abs(workspace.getRun().getProperty("%sHWidth" % back_slit).value[0])
+            except:
+                # For backward compatibility with old code
+                logger.error("Specified slit could not be found: %s  Trying S2" % back_slit)
+                s2h = abs(workspace.getRun().getProperty("S2VHeight").value[0])
+                s2w = abs(workspace.getRun().getProperty("S2HWidth").value[0])
+
+            # Get wavelength, to make sure they all match across runs
+            wl = workspace.getRun().getProperty('LambdaRequest').value[0]
+            if wavelength is None:
+                wavelength = wl
+            elif abs(wl-wavelength) > 0.2:
+                raise RuntimeError, "Supplied runs don't have matching wavelengths."
+
+            peak = [int(peak_range[2*i]), int(peak_range[2*i+1])]
+            background = [int(background_range[2*i]), int(background_range[2*i+1])]
+            self.process_data(workspace,
+                              peak_range=peak,
+                              background_range=background)
+
+            # If we don't have the attenuator information and we have the
+            # same slit settings as the previous run, it means we added an
+            # attenuator.
+            if have_attenuator_info is True:
+                if attenuators[i] < n_attenuator:
+                    raise RuntimeError, "Runs were not supplied in increasing number of attenuators."
+                n_attenuator = attenuators[i]
+
+            is_reference = False
+            self.tolerance = 0.02
+
+            # Matching slits with the previous run signals a reference run
+            if i > 0 and previous_slits is not None \
+                and abs(previous_slits[0] - s1h) < self.tolerance \
+                and abs(previous_slits[1] - s1w) < self.tolerance \
+                and abs(previous_slits[2] - s2h) < self.tolerance \
+                and abs(previous_slits[3] - s2w) < self.tolerance:
+                is_reference = True
+                
+                # This signals an attenuation number change if we happen to need the info
+                if have_attenuator_info is False:
+                    n_attenuator += 1
+                    attenuators[i] = n_attenuator
+
+            previous_slits = [s1h, s1w, s2h, s2w]
+
+            # If the number of attenuators is zero, skip.
+            if n_attenuator == 0:
+                if references.has_key(0):
+                    raise RuntimeError, "More than one run with zero attenuator was supplied."
+                references[0] = {'index': i,
+                                 'run': run,
+                                 'ref_ws': workspace_name,
+                                 'ratio_ws': None,
+                                 'diagnostics': str(run)}
+                previous_ws = workspace_name
+                continue
+
+            if is_reference is True:
+                references[n_attenuator] = {'index': i,
+                                            'run': run,
+                                            'ref_ws': workspace_name}
+                # Compute ratio of the run with fewer attenuators and the
+                # reference with the same number of attenuators as that run.
+                Divide(LHSWorkspace = previous_ws,
+                       RHSWorkspace = references[n_attenuator-1]['ref_ws'],
+                       OutputWorkspace = "ScalingRatio_%s" % n_attenuator)
+                references[n_attenuator]['diagnostics'] = "%s / %s" % (str(data_runs[i-1]), references[n_attenuator-1]['run'])
+                # Multiply the result by the ratio for that run, and store
+                if references[n_attenuator-1]['ratio_ws'] is not None:
+                    Multiply(LHSWorkspace = references[n_attenuator-1]['ratio_ws'],
+                             RHSWorkspace = "ScalingRatio_%s" % n_attenuator,
+                             OutputWorkspace = "ScalingRatio_%s" % n_attenuator)
+                    references[n_attenuator]['diagnostics'] += " * %s" % references[n_attenuator-1]['diagnostics']
+                references[n_attenuator]['ratio_ws'] = "ScalingRatio_%s" % n_attenuator
+                
+            # If this is not a reference run, compute F
+            else:
+                # Divide by the reference for this number of attenuators
+                # and multiply by the reference ratio
+                if not references.has_key(n_attenuator):
+                    raise RuntimeError, "No reference for %s attenuators: check run ordering." % n_attenuator
+                f_ws = "F_%s_%s" % (run, n_attenuator)
+                Divide(LHSWorkspace=workspace_name,
+                       RHSWorkspace=references[n_attenuator]['ref_ws'],
+                       OutputWorkspace=f_ws)
+                Multiply(LHSWorkspace=references[n_attenuator]['ratio_ws'],
+                         RHSWorkspace=f_ws,
+                         OutputWorkspace=f_ws)
+                # Store the final result for this setting
+                ReplaceSpecialValues(InputWorkspace=f_ws, OutputWorkspace=f_ws,
+                                     NaNValue=0.0, NaNError=1000.0,
+                                     InfinityValue=0.0, InfinityError=1000.0)
+
+                # Remove prompt pulse bin, replace the y value by the
+                # average and give it a very large error.
+                x_values = mtd[f_ws].readX(0)
+                y_values = mtd[f_ws].dataY(0)
+                e_values = mtd[f_ws].dataE(0)
+                # We will create a cleaned up workspace without the bins
+                # corresponding to the prompt pulses
+                x_clean = []
+                y_clean = []
+                e_clean = []
+                for i in range(len(y_values)):
+                    # Go up to 4 frames - that should cover more than enough TOF
+                    for n in range(1, 4):
+                        peak_x = 1.0e6 / 60.0 * n
+                        if not (peak_x > x_values[i] and peak_x < x_values[i+1]) \
+                            and y_values[i] > 0.0:
+                            x_clean.append((x_values[i+1]+x_values[i])/2.0)
+                            y_clean.append(y_values[i])
+                            e_clean.append(e_values[i])
+
+                CreateWorkspace(OutputWorkspace=f_ws, DataX=x_clean,
+                                DataY=y_clean, DataE=e_clean, NSpec=1)
+
+                Fit(InputWorkspace=f_ws,
+                    Function="name=UserFunction, Formula=a+b*x, a=1, b=0",
+                    Output='fit_result')
+                a = mtd['fit_result_Parameters'].cell(0,1)
+                b = mtd['fit_result_Parameters'].cell(1,1)
+                error_a = mtd['fit_result_Parameters'].cell(0,2)
+                error_b = mtd['fit_result_Parameters'].cell(1,2)
+                scaling_factors.append({'IncidentMedium': medium,
+                                        'LambdaRequested': wl,
+                                        'S1H':s1h, 'S1W':s1w,
+                                        'S2iH':s2h, 'S2iW':s2w,
+                                        'a':a, 'error_a': error_a, 
+                                        'b':b, 'error_b': error_b,
+                                        'diagnostics': '%s / %s * %s' % (run, references[n_attenuator]['run'], references[n_attenuator]['diagnostics'])
+                                        })
+            previous_ws = workspace_name
+
+        # Log some useful information to track what happened
+        for item in scaling_factors:
+            log_info = "LambdaRequested=%s " % item["LambdaRequested"]
+            log_info += "S1H=%s " % item["S1H"]
+            log_info += "S2iH=%s " % item["S2iH"]
+            log_info += "S1W=%s " % item["S1W"]
+            log_info += "S2iW=%s " % item["S2iW"]
+            log_info += "a=%s " % item["a"]
+            log_info += "b=%s " % item["b"]
+            log_info += "  |  %s" % item["diagnostics"]
+            logger.information(log_info)
+        # Save the output in a configuration file
+        self.save_scaling_factor_file(scaling_factors)
+
+    def save_scaling_factor_file(self, scaling_factors):
+        """
+            Save the output. First see if the scaling factor file exists.
+            If it does, we need to update it.
+            @param scaling_factors: list of scaling factor dictionaries
+        """
+        scaling_file = self.getPropertyValue("ScalingFactorFile")
+        scaling_file_content = []
+        if os.path.isfile(scaling_file):
+            fd = open(scaling_file, 'r')
+            content = fd.read()
+            fd.close()
+            for line in content.split('\n'):
+                if line.startswith('#') or len(line.strip()) == 0:
+                    continue
+                toks = line.split()
+                entry = {}
+                for token in toks:
+                    pair = token.split('=')
+                    entry[pair[0].strip()] = pair[1].strip()
+                # If we are about to update an entry, don't include it in the new file
+                add_this_entry = True
+                for new_entry in scaling_factors:
+                    is_matching = entry["IncidentMedium"] == new_entry["IncidentMedium"]
+                    for slit in ["LambdaRequested", "S1H", "S1W", "S2iH", "S2iW"]:
+                        is_matching = is_matching \
+                            and abs(float(entry[slit])-float(new_entry[slit])) < self.tolerance
+                    if is_matching:
+                        add_this_entry = False
+                if add_this_entry:
+                    scaling_file_content.append(entry)
+        scaling_file_content.extend(scaling_factors)
+
+        fd = open(scaling_file, 'w')
+        fd.write("#y=a+bx\n#\n")
+        fd.write("#lambdaRequested[Angstroms] S1H[mm] (S2/Si)H[mm] S1W[mm] (S2/Si)W[mm] a b error_a error_b\n#\n")
+        for item in scaling_file_content:
+            fd.write("IncidentMedium=%s " % item["IncidentMedium"])
+            fd.write("LambdaRequested=%s " % item["LambdaRequested"])
+            fd.write("S1H=%s " % item["S1H"])
+            fd.write("S2iH=%s " % item["S2iH"])
+            fd.write("S1W=%s " % item["S1W"])
+            fd.write("S2iW=%s " % item["S2iW"])
+            fd.write("a=%s " % item["a"])
+            fd.write("b=%s " % item["b"])
+            fd.write("error_a=%s " % item["error_a"])
+            fd.write("error_b=%s\n" % item["error_b"])
+        fd.close()
+
+    def process_data(self, workspace, peak_range, background_range):
+        """
+            Common processing for both sample data and normalization.
+            @param workspace: name of the workspace to work with
+            @param peak_range: range of pixels defining the peak
+            @param background_range: range of pixels defining the background
+        """
+        # Rebin TOF axis
+        tof_range = self.getProperty("TOFRange").value
+        tof_step = self.getProperty("TOFSteps").value
+        workspace = Rebin(InputWorkspace=workspace, Params=[tof_range[0], tof_step, tof_range[1]], 
+                          PreserveEvents=False, OutputWorkspace=str(workspace))
+
+        # Integrate over low resolution range
+        low_res_range = self.getProperty("LowResolutionPixelRange").value
+        x_min = int(low_res_range[0])
+        x_max = int(low_res_range[1])
+
+        # Subtract background
+        workspace = LRSubtractAverageBackground(InputWorkspace=workspace,
+                                                PeakRange=peak_range,
+                                                BackgroundRange=background_range,
+                                                LowResolutionRange=[x_min, x_max],
+                                                OutputWorkspace=str(workspace))
+
+        # Normalize by current proton charge
+        # Note that the background subtraction will use an error weighted mean
+        # and use 1 as the error on counts of zero. We normalize by the integrated
+        # current _after_ the background subtraction so that the 1 doesn't have
+        # to be changed to a 1/Charge.
+        workspace = NormaliseByCurrent(InputWorkspace=workspace, 
+                                       OutputWorkspace=str(workspace))
+
+        # Crop to only the selected peak region
+        workspace = CropWorkspace(InputWorkspace=workspace,
+                                  StartWorkspaceIndex=int(peak_range[0]),
+                                  EndWorkspaceIndex=int(peak_range[1]),
+                                  OutputWorkspace=str(workspace))
+        workspace = SumSpectra(InputWorkspace=workspace,
+                               OutputWorkspace=str(workspace))
+
+        return str(workspace)
+
+AlgorithmFactory.subscribe(LRScalingFactors)
\ No newline at end of file
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LRSubtractAverageBackground.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LRSubtractAverageBackground.py
new file mode 100644
index 0000000000000000000000000000000000000000..d70dac37767eb635f380211488569c1dcbe1ba81
--- /dev/null
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LRSubtractAverageBackground.py
@@ -0,0 +1,124 @@
+#pylint: disable=no-init,invalid-name
+from mantid.api import *
+from mantid.simpleapi import *
+from mantid.kernel import *
+
+class LRSubtractAverageBackground(PythonAlgorithm):
+
+    def category(self):
+        return "Reflectometry\\SNS"
+
+    def name(self):
+        return "LRSubtractAverageBackground"
+
+    def version(self):
+        return 1
+
+    def summary(self):
+        return "Liquids Reflectometer background subtraction using the average on each side of the peak."
+
+    def PyInit(self):
+        self.declareProperty(WorkspaceProperty("InputWorkspace", "",Direction.Input), "The workspace to check.")
+        self.declareProperty(IntArrayProperty("PeakRange", [150, 160],
+                                              IntArrayLengthValidator(2), direction=Direction.Input),
+                             "Pixel range defining the reflectivity peak")
+        self.declareProperty(IntArrayProperty("BackgroundRange", [147, 163],
+                                              IntArrayLengthValidator(2), direction=Direction.Input),
+                             "Pixel range defining the outer range of the background on each side of the peak")
+        self.declareProperty(IntArrayProperty("LowResolutionRange", [94, 160],
+                                              IntArrayLengthValidator(2), direction=Direction.Input),
+                             "Pixel range defining the low-resolution axis to integrate over")
+        self.declareProperty("SumPeak", False, doc="If True, the resulting peak will be summed")
+        self.declareProperty(WorkspaceProperty("OutputWorkspace", "",Direction.Output), "The workspace to check.")
+
+    def PyExec(self):
+        workspace = self.getProperty("InputWorkspace").value
+
+        # Signal region
+        peak_range = self.getProperty("PeakRange").value
+        peak_min = int(peak_range[0])
+        peak_max = int(peak_range[1])
+
+        # Background outer region
+        bck_range = self.getProperty("BackgroundRange").value
+        bck_min = int(bck_range[0])
+        bck_max = int(bck_range[1])
+
+        # Low-resolution range
+        x_range = self.getProperty("LowResolutionRange").value
+        x_min = int(x_range[0])
+        x_max = int(x_range[1])
+
+        sum_peak = self.getProperty("SumPeak").value
+
+        # Number of pixels in each direction
+        #TODO: revisit this when we update the IDF
+        number_of_pixels_x = int(workspace.getInstrument().getNumberParameter("number-of-x-pixels")[0])
+        number_of_pixels_y = int(workspace.getInstrument().getNumberParameter("number-of-y-pixels")[0])
+
+        left_bck = None
+        if peak_min > bck_min:
+            left_bck = RefRoi(InputWorkspace=workspace, IntegrateY=False,
+                              NXPixel=number_of_pixels_x,
+                              NYPixel=number_of_pixels_y,
+                              ConvertToQ=False,
+                              XPixelMin=x_min,
+                              XPixelMax=x_max,
+                              YPixelMin=bck_min,
+                              YPixelMax=peak_min - 1,
+                              ErrorWeighting = True,
+                              SumPixels=True, NormalizeSum=True)
+
+        right_bck = None
+        if peak_max < bck_max:
+            right_bck = RefRoi(InputWorkspace=workspace, IntegrateY=False,
+                               NXPixel=number_of_pixels_x,
+                               NYPixel=number_of_pixels_y,
+                               ConvertToQ=False,
+                               XPixelMin=x_min,
+                               XPixelMax=x_max,
+                               YPixelMin=peak_max + 1,
+                               YPixelMax=bck_max,
+                               ErrorWeighting = True,
+                               SumPixels=True, NormalizeSum=True)
+
+        if right_bck is not None and left_bck is not None:
+            average = (left_bck + right_bck) / 2.0
+        elif right_bck is not None:
+            average = right_bck
+        elif left_bck is not None:
+            average = left_bck
+        else:
+            average = RefRoi(InputWorkspace=workspace, IntegrateY=False,
+                             NXPixel=number_of_pixels_x,
+                             NYPixel=number_of_pixels_y,
+                             ConvertToQ=False,
+                             XPixelMin=x_min,
+                             XPixelMax=x_max,
+                             YPixelMin=bck_min,
+                             YPixelMax=bck_max,
+                             ErrorWeighting = True,
+                             SumPixels=True, NormalizeSum=True)
+        # Integrate over the low-res direction
+        workspace = RefRoi(InputWorkspace=workspace, IntegrateY=False,
+                           NXPixel=number_of_pixels_x,
+                           NYPixel=number_of_pixels_y,
+                           XPixelMin=x_min,
+                           XPixelMax=x_max,
+                           ConvertToQ=False,
+                           SumPixels=sum_peak,
+                           OutputWorkspace=str(workspace))
+        workspace = Minus(LHSWorkspace=workspace, RHSWorkspace=average,
+                          OutputWorkspace=str(workspace))
+        # Avoid leaving trash behind
+        average_name = str(average)
+        if AnalysisDataService.doesExist(str(left_bck)):
+            AnalysisDataService.remove(str(left_bck))
+        if AnalysisDataService.doesExist(str(right_bck)):
+            AnalysisDataService.remove(str(right_bck))
+        if AnalysisDataService.doesExist(average_name):
+            AnalysisDataService.remove(average_name)
+
+        self.setProperty('OutputWorkspace', workspace)
+
+AlgorithmFactory.subscribe(LRSubtractAverageBackground)
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LiquidsReflectometryReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LiquidsReflectometryReduction.py
index d139d57ff507818675773064344a055cee2e8638..697a69ed09ffe16c58caad6de1017210a5715ff4 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LiquidsReflectometryReduction.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LiquidsReflectometryReduction.py
@@ -1,4 +1,12 @@
 #pylint: disable=no-init,invalid-name
+"""
+    This algorithm is a refactored version of the RefLReduction algorithm.
+    It was written in an attempt to:
+      - Not rely on external code but only on algorithms.
+      - Do work using existing algorithms as opposed to doing everything in arrays.
+      - Keep the same parameters and work as a drop-in replacement for the old algorithm.
+      - Reproduce the output of the old algorithm.
+"""
 import time
 import math
 import os
@@ -21,14 +29,17 @@ class LiquidsReflectometryReduction(PythonAlgorithm):
         return "Liquids Reflectometer (REFL) reduction"
 
     def PyInit(self):
+        #TODO: Revisit the choice of names when we are entirely rid of the old code.
         self.declareProperty(IntArrayProperty("RunNumbers"), "List of run numbers to process")
         self.declareProperty("NormalizationRunNumber", 0, "Run number of the normalization run to use")
-        self.declareProperty(IntArrayProperty("SignalPeakPixelRange"), "Pixel range defining the data peak")
+        self.declareProperty(IntArrayProperty("SignalPeakPixelRange", [123, 137],
+                                              IntArrayLengthValidator(2), direction=Direction.Input),
+                                              "Pixel range defining the data peak")
         self.declareProperty("SubtractSignalBackground", True,
                              doc='If true, the background will be subtracted from the data peak')
         self.declareProperty(IntArrayProperty("SignalBackgroundPixelRange", [123, 137],
                                               IntArrayLengthValidator(2), direction=Direction.Input),
-                                              "Pixelrange defining the background. Default:(123,137)")
+                                              "Pixel range defining the background. Default:(123,137)")
         self.declareProperty("NormFlag", True, doc="If true, the data will be normalized")
         self.declareProperty(IntArrayProperty("NormPeakPixelRange", [127, 133],
                                               IntArrayLengthValidator(2), direction=Direction.Input),
@@ -51,7 +62,7 @@ class LiquidsReflectometryReduction(PythonAlgorithm):
         self.declareProperty(FloatArrayProperty("TOFRange", [0., 340000.],
                                                 FloatArrayLengthValidator(2), direction=Direction.Input),
                                                 "TOF range to use")
-        self.declareProperty("TofRangeFlag", True,
+        self.declareProperty("TOFRangeFlag", True,
                              doc="If true, the TOF will be cropped according to the TOF range property")
         self.declareProperty("QMin", 0.05, doc="Minimum Q-value")
         self.declareProperty("QStep", 0.02, doc="Step size in Q. Enter a negative value to get a log scale")
@@ -73,11 +84,6 @@ class LiquidsReflectometryReduction(PythonAlgorithm):
                                               "Pixel range to use for calculating the primary fraction correction.")
 
     def PyExec(self):
-        # The old reflectivity reduction has an offset between the input
-        # pixel numbers and what it actually uses. Set the offset to zero
-        # to turn it off.
-        self.LEGACY_OFFSET = -1
-
         # The old reduction code had a tolerance value for matching the
         # slit parameters to get the scaling factors
         self.TOLERANCE = 0.020
@@ -105,7 +111,7 @@ class LiquidsReflectometryReduction(PythonAlgorithm):
             file_list.append(data_file)
         runs = reduce((lambda x, y: '%s+%s' % (x, y)), file_list)
         ws_event_data = Load(Filename=runs, OutputWorkspace="REF_L_%s" % dataRunNumbers[0])
-        
+
         # Compute the primary fraction using the unprocessed workspace
         apply_primary_fraction = self.getProperty("ApplyPrimaryFraction").value
         primary_fraction = [1.0, 0.0]
@@ -115,7 +121,7 @@ class LiquidsReflectometryReduction(PythonAlgorithm):
                                                  SignalRange=signal_range)
 
         # Get the TOF range
-        crop_TOF = self.getProperty("TofRangeFlag").value
+        crop_TOF = self.getProperty("TOFRangeFlag").value
         tof_step = self.getProperty("TOFSteps").value
         if crop_TOF:
             TOFrange = self.getProperty("TOFRange").value  #microS
@@ -162,7 +168,7 @@ class LiquidsReflectometryReduction(PythonAlgorithm):
                                              normPeakRange, bck_request, normBackRange)
             # Avoid leaving trash behind
             AnalysisDataService.remove(str(ws_event_norm))
-    
+
             # Sum up the normalization peak
             norm_summed = SumSpectra(InputWorkspace = norm_cropped)
             norm_summed = RebinToWorkspace(WorkspaceToRebin=norm_summed,
@@ -181,8 +187,10 @@ class LiquidsReflectometryReduction(PythonAlgorithm):
         else:
             normalized_data = data_cropped
 
+        # At this point, the workspace should be considered a distribution of points
         normalized_data = ConvertToPointData(InputWorkspace=normalized_data,
                                              OutputWorkspace=str(normalized_data))
+        normalized_data.setDistribution(True)
 
         # Apply scaling factors
         normalized_data = self.apply_scaling_factor(normalized_data)
@@ -223,7 +231,7 @@ class LiquidsReflectometryReduction(PythonAlgorithm):
         q_rebin = Rebin(InputWorkspace=q_workspace, Params=q_range,
                         OutputWorkspace=name_output_ws)
 
-        # Apply the primary fraction 
+        # Apply the primary fraction
         if apply_primary_fraction:
             ws_fraction = CreateSingleValuedWorkspace(DataValue=primary_fraction[0],
                                                       ErrorValue=primary_fraction[1])
@@ -262,7 +270,7 @@ class LiquidsReflectometryReduction(PythonAlgorithm):
         # Clean up the workspace for backward compatibility
         data_y = q_rebin.dataY(0)
         data_e = q_rebin.dataE(0)
-        # Again for backward compatibility, the first and last points of the 
+        # Again for backward compatibility, the first and last points of the
         # raw output when not cropping was simply set to 0 += 1.
         if crop is False:
             data_y[0] = 0
@@ -310,93 +318,6 @@ class LiquidsReflectometryReduction(PythonAlgorithm):
         angle_offset_deg = self.getProperty("AngleOffset").value
         return theta + angle_offset_deg * math.pi / 180.0
 
-    def subtract_background(self, workspace, peak_range, background_range,
-                            low_res_range, sum_peak=False, offset=None):
-        """
-            Subtract background in place
-            @param workspace: Mantid workspace
-            @param peak_range: range of pixels defining the peak [min, max]
-            @param background_range: range of pixels defining the background [min, max]
-            @param low_res_range: low resolution range to integrate over
-            @param sum_peak: if True, the resulting peak will be summed
-        """
-        if offset is None:
-            offset = self.LEGACY_OFFSET
-        peak_min = int(peak_range[0]) + offset
-        peak_max = int(peak_range[1]) + offset
-        bck_min = int(background_range[0]) + offset
-        bck_max = int(background_range[1]) + offset
-
-        # Get low-resolution range
-        x_min = int(low_res_range[0]) + offset
-        x_max = int(low_res_range[1]) + offset
-
-        left_bck = None
-        if peak_min > bck_min:
-            left_bck = RefRoi(InputWorkspace=workspace, IntegrateY=False,
-                              NXPixel=self.number_of_pixels_x,
-                              NYPixel=self.number_of_pixels_y,
-                              ConvertToQ=False,
-                              XPixelMin=x_min,
-                              XPixelMax=x_max,
-                              YPixelMin=bck_min,
-                              YPixelMax=peak_min - 1,
-                              ErrorWeighting = True,
-                              SumPixels=True, NormalizeSum=True)
-
-        right_bck = None
-        if peak_max < bck_max:
-            right_bck = RefRoi(InputWorkspace=workspace, IntegrateY=False,
-                               NXPixel=self.number_of_pixels_x,
-                               NYPixel=self.number_of_pixels_y,
-                               ConvertToQ=False,
-                               XPixelMin=x_min,
-                               XPixelMax=x_max,
-                               YPixelMin=peak_max + 1,
-                               YPixelMax=bck_max,
-                               ErrorWeighting = True,
-                               SumPixels=True, NormalizeSum=True)
-            
-        if right_bck is not None and left_bck is not None:
-            average = (left_bck + right_bck) / 2.0
-        elif right_bck is not None:
-            average = right_bck
-        elif left_bck is not None:
-            average = left_bck
-        else:
-            average = RefRoi(InputWorkspace=workspace, IntegrateY=False,
-                             NXPixel=self.number_of_pixels_x,
-                             NYPixel=self.number_of_pixels_y,
-                             ConvertToQ=False,
-                             XPixelMin=x_min,
-                             XPixelMax=x_max,
-                             YPixelMin=bck_min,
-                             YPixelMax=bck_max,
-                             ErrorWeighting = True,
-                             SumPixels=True, NormalizeSum=True)
-        # Integrate over the low-res direction
-        workspace = RefRoi(InputWorkspace=workspace, IntegrateY=False,
-                           NXPixel=self.number_of_pixels_x,
-                           NYPixel=self.number_of_pixels_y,
-                           XPixelMin=x_min,
-                           XPixelMax=x_max,
-                           ConvertToQ=False,
-                           SumPixels=sum_peak,
-                           OutputWorkspace=str(workspace))
-        #TODO Check whether we should multiply by the number of pixels
-        # in the low-res direction
-        workspace = Minus(LHSWorkspace=workspace, RHSWorkspace=average,
-                          OutputWorkspace=str(workspace))
-        # Avoid leaving trash behind
-        average_name = str(average)
-        if AnalysisDataService.doesExist(str(left_bck)):
-            AnalysisDataService.remove(str(left_bck))
-        if AnalysisDataService.doesExist(str(right_bck)):
-            AnalysisDataService.remove(str(right_bck))
-        if AnalysisDataService.doesExist(average_name):
-            AnalysisDataService.remove(average_name)
-        return workspace
-
     def process_data(self, workspace, tof_range, crop_low_res, low_res_range,
                      peak_range, subtract_background, background_range):
         """
@@ -413,9 +334,9 @@ class LiquidsReflectometryReduction(PythonAlgorithm):
             error_msg += "[%g, %g] found [%g, %g]" % (tof_range[0], tof_range[1],
                                                       tof_min, tof_max)
             raise RuntimeError, error_msg
-        
+
         tof_step = self.getProperty("TOFSteps").value
-        workspace = Rebin(InputWorkspace=workspace, Params=[0, tof_step, tof_max], 
+        workspace = Rebin(InputWorkspace=workspace, Params=[0, tof_step, tof_max],
                           PreserveEvents=False, OutputWorkspace="%s_histo" % str(workspace))
 
         # Crop TOF range
@@ -432,9 +353,11 @@ class LiquidsReflectometryReduction(PythonAlgorithm):
 
         # Subtract background
         if subtract_background:
-            workspace = self.subtract_background(workspace,
-                                                 peak_range, background_range,
-                                                 [x_min, x_max])
+            workspace = LRSubtractAverageBackground(InputWorkspace=workspace,
+                                                    PeakRange=peak_range,
+                                                    BackgroundRange=background_range,
+                                                    LowResolutionRange=[x_min, x_max],
+                                                    OutputWorkspace=str(workspace))
         else:
             # If we don't subtract the background, we still have to integrate
             # over the low resolution axis
@@ -453,8 +376,8 @@ class LiquidsReflectometryReduction(PythonAlgorithm):
 
         # Crop to only the selected peak region
         cropped = CropWorkspace(InputWorkspace = workspace,
-                                StartWorkspaceIndex=int(peak_range[0]) + self.LEGACY_OFFSET,
-                                EndWorkspaceIndex=int(peak_range[1]) + self.LEGACY_OFFSET,
+                                StartWorkspaceIndex=int(peak_range[0]),
+                                EndWorkspaceIndex=int(peak_range[1]),
                                 OutputWorkspace="%s_cropped" % str(workspace))
 
         # Avoid leaving trash behind
@@ -481,7 +404,7 @@ class LiquidsReflectometryReduction(PythonAlgorithm):
 
         # Get the incident medium
         incident_medium = self.getProperty("IncidentMediumSelected").value
-        
+
         # Get the wavelength
         lr = workspace.getRun().getProperty('LambdaRequest').value[0]
         lr_value = float("{0:.2f}".format(lr))
@@ -536,7 +459,7 @@ class LiquidsReflectometryReduction(PythonAlgorithm):
         scaling_data = open(scaling_factor_file, 'r')
         file_content = scaling_data.read()
         scaling_data.close()
-        
+
         data_found = None
         for line in file_content.split('\n'):
             if line.startswith('#'):
@@ -545,7 +468,7 @@ class LiquidsReflectometryReduction(PythonAlgorithm):
             # Parse the line of data and produce a dict
             toks = line.split()
             data_dict = reduce(_reduce, toks, {})
-            
+
             # Get ordered list of keys
             keys = []
             for token in toks:
@@ -560,7 +483,7 @@ class LiquidsReflectometryReduction(PythonAlgorithm):
             elif len(keys)<10:
                 logger.error("Bad scaling factor entry\n  %s" % line)
                 continue
-                
+
             # Sanity check
             if keys[0] != 'IncidentMedium' and keys[1] != 'LambdaRequested' \
                 and keys[2] != 'S1H':
@@ -595,8 +518,6 @@ class LiquidsReflectometryReduction(PythonAlgorithm):
             norm_tof = normalization.dataX(0)
             norm_value = normalization.dataY(0)
             norm_error = normalization.dataE(0)
-            #TODO: The following is done on the bin edges.
-            # Should it not be done for the center of the bin?
             for i in range(len(norm_value)):
                 norm_value[i] = norm_tof[i] * b + a
                 norm_error[i] = math.sqrt(a_error*a_error + norm_tof[i] * norm_tof[i] * b_error * b_error)
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQFile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQFile.py
index 99f276747866ed907307b0dfb4b4aaee1d8625be..cbace39a475b36e914d968121f3103998875a65a 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQFile.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQFile.py
@@ -13,6 +13,7 @@ import mantid.simpleapi
 from mantid import config
 import os.path
 import numpy as np
+import re
 
 #--------- place to look for dictionary files
 
@@ -47,14 +48,20 @@ class LoadSINQFile(PythonAlgorithm):
             "HRPT":"hrpt.dic",
             "MARSI":"marsin.dic",
             "MARSE":"marse.dic",
+            "POLDI_legacy":"poldi_legacy.dic",
             "POLDI":"poldi.dic",
             "RITA-2":"rita.dic",
             "SANS":"sans.dic",
             "SANS2":"sans.dic",
             "TRICS":"trics.dic"\
         }
+
+        lookupInstrumentName = inst
+        if inst == 'POLDI':
+            lookupInstrumentName = self._getPoldiLookupName(fname, lookupInstrumentName)
+
         dictsearch = os.path.join(config['instrumentDefinition.directory'],"nexusdictionaries")
-        dicname = os.path.join(dictsearch, diclookup[inst])
+        dicname = os.path.join(dictsearch, diclookup[lookupInstrumentName])
         wname = "__tmp"
         ws = mantid.simpleapi.LoadFlexiNexus(fname,dicname,OutputWorkspace=wname)
 
@@ -62,11 +69,11 @@ class LoadSINQFile(PythonAlgorithm):
             if ws.getNumberHistograms() == 800:
                 ws.maskDetectors(SpectraList=range(0,800)[::2])
 
-            config.appendDataSearchDir(config['groupingFiles.directory'])
-            grp_file = "POLDI_Grouping_800to400.xml"
-            ws = mantid.simpleapi.GroupDetectors(InputWorkspace=ws,
-                                                 OutputWorkspace=wname,
-                                                 MapFile=grp_file, Behaviour="Sum")
+                config.appendDataSearchDir(config['groupingFiles.directory'])
+                grp_file = "POLDI_Grouping_800to400.xml"
+                ws = mantid.simpleapi.GroupDetectors(InputWorkspace=ws,
+                                                     OutputWorkspace=wname,
+                                                     MapFile=grp_file, Behaviour="Sum")
 
             # Reverse direction of POLDI data so that low index corresponds to low 2theta.
             histogramCount = ws.getNumberHistograms()
@@ -86,5 +93,19 @@ class LoadSINQFile(PythonAlgorithm):
         # delete temporary reference
         mantid.simpleapi.DeleteWorkspace(wname,EnableLogging=False)
 
+    def _getPoldiLookupName(self, fname, lookupInstrumentName):
+        year = self._extractYearFromFileName(fname)
+        if year < 2015:
+            return lookupInstrumentName + '_legacy'
+        # Otherwise, this is the current POLDI format.
+        return lookupInstrumentName
+
+    def _extractYearFromFileName(self, filename):
+        pureFileName = os.path.basename(filename)
+        pattern = re.compile(r'\w+(\d{4})n[\w\d\.]+')
+        matches = re.match(pattern, pureFileName)
+
+        return int(matches.group(1))
+
 #---------- register with Mantid
 AlgorithmFactory.subscribe(LoadSINQFile)
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskAngle.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskAngle.py
index 7cd1366266bd4243b24f958673bd8ad0f1a75fdd..91f2ae62b5b98b87d04b371d925c6cc27b065701 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskAngle.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskAngle.py
@@ -24,12 +24,16 @@ class MaskAngle(mantid.api.PythonAlgorithm):
         return "Algorithm to mask detectors with scattering angles in a given interval (in degrees)."
 
     def PyInit(self):
-        self.declareProperty(mantid.api.WorkspaceProperty("Workspace", "",direction=mantid.kernel.Direction.Input,validator=mantid.api.InstrumentValidator()), "Input workspace")
+        self.declareProperty(mantid.api.WorkspaceProperty("Workspace", "",direction=mantid.kernel.Direction.Input,
+                                                          validator=mantid.api.InstrumentValidator()), "Input workspace")
         angleValidator=mantid.kernel.FloatBoundedValidator()
         angleValidator.setBounds(0.,180.)
-        self.declareProperty(name="MinAngle", defaultValue=0.0, validator=angleValidator, direction=mantid.kernel.Direction.Input, doc="Angles above StartAngle are going to be masked")
-        self.declareProperty(name="MaxAngle", defaultValue=0.0, validator=angleValidator, direction=mantid.kernel.Direction.Input, doc="Angles above StartAngle are going to be masked")
-        self.declareProperty(mantid.kernel.IntArrayProperty(name="MaskedDetectors", direction=mantid.kernel.Direction.Output), doc="List of detector masked, with scatterin angles between MinAngle and MaxAngle")
+        self.declareProperty(name="MinAngle", defaultValue=0.0, validator=angleValidator,
+                             direction=mantid.kernel.Direction.Input, doc="Angles above StartAngle are going to be masked")
+        self.declareProperty(name="MaxAngle", defaultValue=0.0, validator=angleValidator,
+                             direction=mantid.kernel.Direction.Input, doc="Angles above StartAngle are going to be masked")
+        self.declareProperty(mantid.kernel.IntArrayProperty(name="MaskedDetectors", direction=mantid.kernel.Direction.Output),
+                             doc="List of detector masked, with scatterin angles between MinAngle and MaxAngle")
 
     def PyExec(self):
         ws = self.getProperty("Workspace").value
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiCreatePeaksFromFile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiCreatePeaksFromFile.py
index d68a14bfb2a65c2fcfcb370d2d4a651e66c59eca..947822554abdb1ed690646132a16c4b56e88ab9c 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiCreatePeaksFromFile.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiCreatePeaksFromFile.py
@@ -1,22 +1,19 @@
-# pylint: disable=no-init,invalid-name,too-few-public-methods
+# pylint: disable=no-init,invalid-name,too-few-public-methods,unused-import
 from mantid.kernel import *
 from mantid.simpleapi import *
 from mantid.api import *
 from mantid.geometry import *
 
-from pyparsing import *
-
 import os
 
 
 class PoldiCompound(object):
     """Small helper class to handle the results from PoldiCrystalFileParser."""
-    _name = ""
-    _spacegroup = ""
-    _atomString = ""
-    _cellDict = ""
 
     def __init__(self, name, elements):
+        self._spacegroup = ""
+        self._atomString = ""
+        self._cellDict = ""
         self._name = name
 
         self.assign(elements)
@@ -74,49 +71,51 @@ class PoldiCrystalFileParser(object):
     in the file. These are then processed by PoldiCreatePeaksFromFile to generate arguments
     for calling PoldiCreatePeaksFromCell.
     """
-    elementSymbol = Word(alphas, min=1, max=2).setFailAction(
-        lambda o, s, loc, token: raiseParseErrorException("Element symbol must be one or two characters."))
-    integerNumber = Word(nums)
-    decimalSeparator = Literal('.')
-    floatNumber = Combine(
-        integerNumber +
-        Optional(decimalSeparator + Optional(integerNumber))
-    )
 
-    whiteSpace = Suppress(White())
+    def __init__(self):
+        self.elementSymbol = Word(alphas, min=1, max=2).setFailAction(
+            lambda o, s, loc, token: raiseParseErrorException("Element symbol must be one or two characters."))
+        self.integerNumber = Word(nums)
+        self.decimalSeparator = Word('./', max=1)
+        self.floatNumber = Combine(
+            self.integerNumber +
+            Optional(self.decimalSeparator + Optional(self.integerNumber))
+        )
+
+        self.whiteSpace = Suppress(White())
 
-    atomLine = Combine(
-        elementSymbol + whiteSpace +
-        delimitedList(floatNumber, delim=White()),
-        joinString=' '
-    )
+        self.atomLine = Combine(
+            self.elementSymbol + self.whiteSpace +
+            delimitedList(self.floatNumber, delim=White()),
+            joinString=' '
+        )
 
-    keyValueSeparator = Suppress(Literal(":"))
+        self.keyValueSeparator = Suppress(Literal(":"))
 
-    groupOpener = Suppress(Literal('{'))
-    groupCloser = Suppress(Literal('}'))
+        self.groupOpener = Suppress(Literal('{'))
+        self.groupCloser = Suppress(Literal('}'))
 
-    atomsGroup = Group(CaselessLiteral("atoms") + keyValueSeparator +
-                       groupOpener + delimitedList(atomLine, delim=lineEnd) + groupCloser)
+        self.atomsGroup = Group(CaselessLiteral("atoms") + self.keyValueSeparator +
+                                self.groupOpener + delimitedList(self.atomLine, delim=lineEnd) + self.groupCloser)
 
-    unitCell = Group(CaselessLiteral("lattice") + keyValueSeparator + delimitedList(
-        floatNumber, delim=White()))
+        self.unitCell = Group(CaselessLiteral("lattice") + self.keyValueSeparator + delimitedList(
+            self.floatNumber, delim=White()))
 
-    spaceGroup = Group(CaselessLiteral("spacegroup") + keyValueSeparator + Word(
-        alphanums + "-" + ' '))
+        self.spaceGroup = Group(CaselessLiteral("spacegroup") + self.keyValueSeparator + Word(
+            alphanums + "-" + ' ' + '/'))
 
-    compoundContent = Each([atomsGroup, unitCell, spaceGroup]).setFailAction(
-        lambda o, s, loc, token: raiseParseErrorException(
-            "One of 'Lattice', 'SpaceGroup', 'Atoms' is missing or contains errors."))
+        self.compoundContent = Each([self.atomsGroup, self.unitCell, self.spaceGroup]).setFailAction(
+            lambda o, s, loc, token: raiseParseErrorException(
+                "One of 'Lattice', 'SpaceGroup', 'Atoms' is missing or contains errors."))
 
-    compoundName = Word(alphanums + '_')
+        self.compoundName = Word(alphanums + '_')
 
-    compound = Group(compoundName + Optional(whiteSpace) + \
-                     groupOpener + compoundContent + groupCloser)
+        self.compound = Group(self.compoundName + Optional(self.whiteSpace) + \
+                              self.groupOpener + self.compoundContent + self.groupCloser)
 
-    comment = Suppress(Literal('#') + restOfLine)
+        self.comment = Suppress(Literal('#') + restOfLine)
 
-    compounds = Optional(comment) + OneOrMore(compound).ignore(comment) + stringEnd
+        self.compounds = Optional(self.comment) + OneOrMore(self.compound).ignore(self.comment) + stringEnd
 
     def __call__(self, contentString):
         parsedContent = None
@@ -136,8 +135,6 @@ class PoldiCrystalFileParser(object):
 
 
 class PoldiCreatePeaksFromFile(PythonAlgorithm):
-    _parser = PoldiCrystalFileParser()
-
     def category(self):
         return "SINQ\\POLDI"
 
@@ -169,6 +166,7 @@ class PoldiCreatePeaksFromFile(PythonAlgorithm):
                               defaultValue="", direction=Direction.Output),
             doc="WorkspaceGroup with reflection tables.")
 
+        self._parser = PoldiCrystalFileParser()
 
     def PyExec(self):
         crystalFileName = self.getProperty("InputFile").value
@@ -214,4 +212,10 @@ class PoldiCreatePeaksFromFile(PythonAlgorithm):
         return compound.getName()
 
 
-AlgorithmFactory.subscribe(PoldiCreatePeaksFromFile)
+try:
+    from pyparsing import *
+
+    AlgorithmFactory.subscribe(PoldiCreatePeaksFromFile)
+except:
+    logger.debug('Failed to subscribe algorithm PoldiCreatePeaksFromFile; Python package pyparsing' \
+                 'may be missing (https://pypi.python.org/pypi/pyparsing)')
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiLoadRuns.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiLoadRuns.py
index 01bee48608109496344a479e6fdd5bc39a4a31e0..9c038eebc0151199f354c81c68812c3b75da7706 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiLoadRuns.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiLoadRuns.py
@@ -9,6 +9,8 @@ from datetime import date
 class PoldiLoadRuns(PythonAlgorithm):
     _nameTemplate = ""
     _mergeCheckEnabled = True
+    _autoMaskBadDetectors = True
+    _autoMaskThreshold = 3.0
 
     def category(self):
         return "SINQ\\Poldi"
@@ -45,6 +47,15 @@ class PoldiLoadRuns(PythonAlgorithm):
         self.declareProperty('EnableMergeCheck', True, direction=Direction.Input,
                              doc="Enable all the checks in PoldiMerge. Do not deactivate without very good reason.")
 
+        self.declareProperty('MaskBadDetectors', True, direction=Direction.Input,
+                             doc=('Automatically disable detectors with unusually small or large values, in addition'
+                                  ' to those masked in the instrument definition.'))
+
+        self.declareProperty('BadDetectorThreshold', 3.0, direction=Direction.Input,
+                             doc=('Detectors are masked based on how much their intensity (integrated over time) '
+                                  'deviates from the median calculated from all detectors. This parameter indicates '
+                                  'how many times bigger the intensity needs to be for a detector to be masked.'))
+
         self.declareProperty(WorkspaceProperty(name='OutputWorkspace',
                                                defaultValue='',
                                                direction=Direction.Output),
@@ -93,6 +104,10 @@ class PoldiLoadRuns(PythonAlgorithm):
         # PoldiMerge checks that instruments are compatible, but it can be disabled (calibration measurements)
         self._mergeCheckEnabled = self.getProperty('EnableMergeCheck').value
 
+        # The same for removing additional dead or misbehaving wires
+        self._autoMaskBadDetectors = self.getProperty('MaskBadDetectors').value
+        self._autoMaskThreshold = self.getProperty('BadDetectorThreshold').value
+
         # Get a list of output workspace names.
         outputWorkspaces = self.getLoadedWorkspaceNames(year, mergeRange, mergeWidth)
 
@@ -172,8 +187,13 @@ class PoldiLoadRuns(PythonAlgorithm):
                 for j in range(i, i + mergeWidth - 1):
                     DeleteWorkspace(self._nameTemplate + str(j))
 
-            # If the workspace is still valid (merging could have failed), it's appended to the output.
+            # If the workspace is still valid (merging could have failed), it's processed further
             if AnalysisDataService.doesExist(currentTotalWsName):
+                # If the option is enabled, mask detectors that are likely to be misbehaving
+                if self._autoMaskBadDetectors:
+                    self.log().information("Masking bad detectors automatically.")
+                    self.autoMaskBadDetectors(currentTotalWsName)
+
                 outputWorkspaces.append(currentTotalWsName)
 
         return outputWorkspaces
@@ -184,6 +204,19 @@ class PoldiLoadRuns(PythonAlgorithm):
         LoadInstrument(workspaceName, InstrumentName="POLDI")
         PoldiTruncateData(InputWorkspace=workspaceName, OutputWorkspace=workspaceName)
 
+    # Automatically determine bad detectors and mask them
+    def autoMaskBadDetectors(self, currentTotalWsName):
+        Integration(currentTotalWsName, OutputWorkspace='integrated')
+
+        MedianDetectorTest('integrated', SignificanceTest=3.0, HighThreshold=self._autoMaskThreshold, HighOutlier=200, \
+                           CorrectForSolidAngle=False, OutputWorkspace='maskWorkspace')
+
+        MaskDetectors(Workspace=AnalysisDataService.retrieve(currentTotalWsName), MaskedWorkspace='maskWorkspace')
+
+        # Clean up
+        DeleteWorkspace('integrated')
+        DeleteWorkspace('maskWorkspace')
+
     # Returns true if the supplied workspace is a WorkspaceGroup
     def isGroupWorkspace(self, workspace):
         return issubclass(type(workspace), WorkspaceGroup)
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiMerge.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiMerge.py
index 23d1aff8abbcd591d03f3be22c606bdabd19291f..bc2b80b31cc318335d6d0e3a43e63fef33ab7b40 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiMerge.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiMerge.py
@@ -69,6 +69,11 @@ class PoldiMerge(PythonAlgorithm):
         if not self.timingsMatch(leftWorkspace.dataX(0), rightWorkspace.dataX(0)):
             raise RuntimeError("Timings don't match")
 
+        # If this option is enabled, don't do any checks
+        if not self.checkInstruments:
+            self.log().warning('Instrument check has been disabled.')
+            return True
+
         leftRun = leftWorkspace.getRun()
         rightRun = rightWorkspace.getRun()
 
@@ -99,7 +104,7 @@ class PoldiMerge(PythonAlgorithm):
         leftInstrument = leftWorkspace.getInstrument()
         rightInstrument = rightWorkspace.getInstrument()
 
-        return (not self.checkInstruments) or self.instrumentParametersMatch(leftInstrument, rightInstrument)
+        return self.instrumentParametersMatch(leftInstrument, rightInstrument)
 
     def instrumentParametersMatch(self, leftInstrument, rightInstrument):
         if not leftInstrument.getDetector(0).getPos() == rightInstrument.getDetector(0).getPos():
@@ -119,8 +124,13 @@ class PoldiMerge(PythonAlgorithm):
 
     def propertiesMatch(self, leftRun, rightRun):
         for propertyName in self.comparedPropertyNames:
-            if abs(self.getPropertyValue(leftRun.getProperty(propertyName)) - self.getPropertyValue(rightRun.getProperty(propertyName))) > 5e-3:
-                raise RuntimeError("Property '%s' does not match" % (propertyName))
+            if leftRun.hasProperty(propertyName) and rightRun.hasProperty(propertyName):
+                leftProperty = leftRun.getProperty(propertyName)
+                rightProperty = rightRun.getProperty(propertyName)
+                if abs(self.getPropertyValue(leftProperty) - self.getPropertyValue(rightProperty)) > 5e-3:
+                    raise RuntimeError("Property '%s' does not match" % (propertyName))
+            else:
+                self.log().warning('Property ' + propertyName + ' is not present in data - skipping comparison.')
 
         return True
 
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/VisionLoadDetectorTable.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/VisionLoadDetectorTable.py
new file mode 100644
index 0000000000000000000000000000000000000000..531e4cc257992caf3274bfc44ac2eb99b7459813
--- /dev/null
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/VisionLoadDetectorTable.py
@@ -0,0 +1,47 @@
+#pylint: disable=no-init,invalid-name
+from mantid.api import *
+from mantid.simpleapi import *
+from mantid.kernel import *
+import numpy as np
+
+
+class VisionLoadDetectorTable(PythonAlgorithm):
+
+    def category(self):
+        return "Utility\\Development;PythonAlgorithms"
+
+    def summary(self):
+        return "Warning - This is under development - Algorithm to load detector parameters for VISION."
+
+    def PyInit(self):
+        self.declareProperty(WorkspaceProperty("OutputWorkspace", "", Direction.Output),
+                             doc="Name of Output Workspace")
+
+        self.declareProperty(FileProperty("DetectorFile", "", action=FileAction.Load, extensions=['csv']),
+                             doc="Name of detector file to load.")
+
+    def PyExec(self):
+        filename = self.getPropertyValue("DetectorFile")
+        output_ws_name = self.getPropertyValue("OutputWorkspace")
+
+        # Open File and read parameters
+        spectra,l1,l2,twotheta,efixed,emode = np.genfromtxt(filename, delimiter=',', unpack=True)
+
+        # Setup the output table
+        output_workspace = CreateEmptyTableWorkspace(OutputWorkspace=output_ws_name)
+        output_workspace.addColumn("int", "spectra")
+        output_workspace.addColumn("double", "l1")
+        output_workspace.addColumn("double", "l2")
+        output_workspace.addColumn("double", "twotheta")
+        output_workspace.addColumn("double", "efixed")
+        output_workspace.addColumn("int", "emode")
+
+        # Write the values
+        for i in range(len(spectra)):
+            output_workspace.addRow([int(spectra[i]),float(l1[i]),float(l2[i]),
+                                     float(twotheta[i]),float(efixed[i]),int(emode[i])])
+
+        # Set the output workspace
+        self.setProperty("OutputWorkspace", output_workspace)
+
+AlgorithmFactory.subscribe(VisionLoadDetectorTable)
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ApplyPaalmanPingsCorrection.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ApplyPaalmanPingsCorrection.py
index d37d518831a02d8268a2b68529381316ec9b503d..f12da8187ca3958927a4ae38fccadb689ae0ba4c 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ApplyPaalmanPingsCorrection.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ApplyPaalmanPingsCorrection.py
@@ -1,3 +1,4 @@
+#pylint: disable=no-init,too-many-instance-attributes
 from mantid.simpleapi import *
 from mantid.api import PythonAlgorithm, AlgorithmFactory, MatrixWorkspaceProperty, WorkspaceGroupProperty, \
                        PropertyMode, MatrixWorkspace
@@ -27,23 +28,21 @@ class ApplyPaalmanPingsCorrection(PythonAlgorithm):
 
 
     def PyInit(self):
-        self.declareProperty(MatrixWorkspaceProperty('SampleWorkspace', '',
-                             direction=Direction.Input),
+        self.declareProperty(MatrixWorkspaceProperty('SampleWorkspace', '', direction=Direction.Input),
                              doc='Name for the input Sample workspace.')
 
         self.declareProperty(WorkspaceGroupProperty('CorrectionsWorkspace', '',
-                             optional=PropertyMode.Optional, direction=Direction.Input),
+                                                    optional=PropertyMode.Optional, direction=Direction.Input),
                              doc='Name for the input Corrections workspace.')
 
         self.declareProperty(MatrixWorkspaceProperty('CanWorkspace', '',
-                             optional=PropertyMode.Optional, direction=Direction.Input),
+                                                     optional=PropertyMode.Optional, direction=Direction.Input),
                              doc='Name for the input Can workspace.')
 
         self.declareProperty(name='CanScaleFactor', defaultValue=1.0,
                              doc='Factor to scale the can data')
 
-        self.declareProperty(MatrixWorkspaceProperty('OutputWorkspace', '',
-                             direction=Direction.Output),
+        self.declareProperty(MatrixWorkspaceProperty('OutputWorkspace', '', direction=Direction.Output),
                              doc='The output corrections workspace.')
 
 
@@ -206,7 +205,8 @@ class ApplyPaalmanPingsCorrection(PythonAlgorithm):
                     efixed = 0.0
                 elif unit_id == 'DeltaE':
                     emode = 'Indirect'
-                    efixed = instrument.getNumberParameter('efixed-val')[0]
+                    from IndirectCommon import getEfixed
+                    efixed = getEfixed(mtd[self._sample_ws_name])
                 else:
                     raise ValueError('Unit %s in sample workspace is not supported' % unit_id)
 
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CreateMD.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CreateMD.py
index 5752dd82aa83d6ea1bb16dbdfcc447f05fa764d0..65cdb8e8c802b83290cb76a91a8348f0e4423e14 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CreateMD.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CreateMD.py
@@ -2,15 +2,23 @@
 from mantid.kernel import *
 from mantid.api import *
 from mantid.simpleapi import *
-import numpy as np
-import __builtin__
-
 
 class CreateMD(DataProcessorAlgorithm):
 
+    def version(self):
+        return 1
+
     def _possible_emodes(self):
         return ['Elastic', 'Direct', 'Indirect']
 
+    def _load_ws(self, filename, wsname):
+        load = self.createChildAlgorithm('Load')
+        load.setProperty('Filename', filename)
+        load.setPropertyValue('OutputWorkspace', wsname)
+        load.execute()
+        ws = load.getProperty('OutputWorkspace').value
+        return ws
+
     def _add_sample_log(self, workspace, log_name, log_number):
         add_log = self.createChildAlgorithm('AddSampleLog')
         add_log.setProperty('Workspace', workspace)
@@ -45,7 +53,7 @@ class CreateMD(DataProcessorAlgorithm):
         set_ub.setProperty('v', v)
         set_ub.execute()
 
-    def _convert_to_md(self, workspace, analysis_mode):
+    def _convert_to_md(self, workspace, analysis_mode, in_place, out_mdws=None):
 
         # Find the Min Max extents
         min_max_alg = self.createChildAlgorithm('ConvertToMDMinMaxGlobal')
@@ -59,12 +67,17 @@ class CreateMD(DataProcessorAlgorithm):
         # Convert to MD
         convert_alg = self.createChildAlgorithm('ConvertToMD')
         convert_alg.setProperty('InputWorkspace', workspace)
-        convert_alg.setPropertyValue('OutputWorkspace', 'dummy')
         convert_alg.setProperty('QDimensions', 'Q3D')
         convert_alg.setProperty('QConversionScales', 'HKL')
         convert_alg.setProperty('dEAnalysisMode', analysis_mode)
         convert_alg.setProperty('MinValues', min_values)
         convert_alg.setProperty('MaxValues', max_values)
+        convert_alg.setProperty("OverwriteExisting", not in_place)
+        if in_place:
+            convert_alg.setProperty("OutputWorkspace", out_mdws)
+        else:
+            convert_alg.setPropertyValue("OutputWorkspace", 'dummy')
+
         convert_alg.execute()
         return convert_alg.getProperty('OutputWorkspace').value
 
@@ -75,9 +88,7 @@ class CreateMD(DataProcessorAlgorithm):
         merge_alg.setPropertyValue('OutputWorkspace', 'dummy')
         merge_alg.execute()
         return merge_alg.getProperty('OutputWorkspace').value
-
-    def _single_run(self, input_workspace, emode,  psi, gl, gs, alatt=None, angdeg=None, u=None, v=None,):
-        import numpy as np
+    def _single_run(self, input_workspace, emode, efix, psi, gl, gs, in_place, alatt=None, angdeg=None, u=None, v=None, out_mdws=None):
         ub_params = map(any, [alatt, angdeg, u, v])
         goniometer_params = [psi, gl, gs]
         if any(ub_params) and not all(ub_params):
@@ -86,17 +97,21 @@ class CreateMD(DataProcessorAlgorithm):
             if input_workspace.sample().hasOrientedLattice():
                 logger.warning("Sample already has a UB. This will not be overwritten by %s. Use ClearUB and re-run."%self.name())
             else:
-                self._set_ub(workspace=input_workspace, a=alatt[0], b=alatt[1], c=alatt[2], alpha=angdeg[0], beta=angdeg[1], gamma=angdeg[2], u=u, v=v)
+                self._set_ub(workspace=input_workspace, a=alatt[0], b=alatt[1], c=alatt[2],
+                             alpha=angdeg[0], beta=angdeg[1], gamma=angdeg[2], u=u, v=v)
+
+        if efix > 0.0:
+            self._add_sample_log(workspace=input_workspace, log_name='Ei',log_number=efix)
 
         if any(goniometer_params):
             self._add_sample_log(workspace=input_workspace, log_name='gl', log_number=gl)
             self._add_sample_log(workspace=input_workspace, log_name='gs', log_number=gs)
             self._add_sample_log(workspace=input_workspace, log_name='psi', log_number=psi)
             self._set_goniometer(workspace=input_workspace)
-        
-        output_run = self._convert_to_md(workspace=input_workspace, analysis_mode=emode)
+
+        output_run = self._convert_to_md(workspace=input_workspace, analysis_mode=emode, in_place=in_place, out_mdws=out_mdws)
         return output_run
-    
+
 
     def category(self):
         return 'MDAlgorithms'
@@ -105,29 +120,46 @@ class CreateMD(DataProcessorAlgorithm):
         return 'Creates a mutlidimensional workspace by transforming and combining individual runs.'
 
     def PyInit(self):
-        self.declareProperty(StringArrayProperty('InputWorkspaces',  values=[], direction=Direction.Input, validator=StringArrayMandatoryValidator()),
-                             doc='Input workspaces to process')
+        self.declareProperty(StringArrayProperty('DataSources',  values=[], direction=Direction.Input,
+                             validator=StringArrayMandatoryValidator()),
+                             doc='Input workspaces to process, or filenames to load and process')
 
-        self.declareProperty('Emode', defaultValue='Direct', validator=StringListValidator(self._possible_emodes()), direction=Direction.Input, doc='Analysis mode ' + str(self._possible_emodes()) )
+        self.declareProperty(FloatArrayProperty('EFix', values=[], direction=Direction.Input),
+                             doc='datasource energy values in meV')
 
-        self.declareProperty(FloatArrayProperty('Alatt', values=[], validator=FloatArrayMandatoryValidator(), direction=Direction.Input ), doc='Lattice parameters' )
+        self.declareProperty('Emode', defaultValue='Direct',
+                             validator=StringListValidator(self._possible_emodes()), direction=Direction.Input,
+                             doc='Analysis mode ' + str(self._possible_emodes()) )
+ 
+        self.declareProperty(FloatArrayProperty('Alatt', values=[], validator=FloatArrayMandatoryValidator(),
+                                                direction=Direction.Input ), doc='Lattice parameters' )
 
-        self.declareProperty(FloatArrayProperty('Angdeg', values=[], validator=FloatArrayMandatoryValidator(), direction=Direction.Input ), doc='Lattice angles' )
+        self.declareProperty(FloatArrayProperty('Angdeg', values=[], validator=FloatArrayMandatoryValidator(),
+                                                direction=Direction.Input ), doc='Lattice angles' )
 
-        self.declareProperty(FloatArrayProperty('u', values=[], validator=FloatArrayMandatoryValidator(), direction=Direction.Input ), doc='Lattice vector parallel to neutron beam' )
+        self.declareProperty(FloatArrayProperty('u', values=[], validator=FloatArrayMandatoryValidator(),
+                                                direction=Direction.Input ), doc='Lattice vector parallel to neutron beam' )
 
-        self.declareProperty(FloatArrayProperty('v', values=[], validator=FloatArrayMandatoryValidator(), direction=Direction.Input ), doc='Lattice vector perpendicular to neutron beam in the horizontal plane' )
+        self.declareProperty(FloatArrayProperty('v', values=[], validator=FloatArrayMandatoryValidator(),
+                                                direction=Direction.Input ),
+                             doc='Lattice vector perpendicular to neutron beam in the horizontal plane' )
 
-        self.declareProperty(FloatArrayProperty('Psi', values=[], direction=Direction.Input), doc='Psi rotation in degrees. Optional or one entry per run.' )
+        self.declareProperty(FloatArrayProperty('Psi', values=[], direction=Direction.Input),
+                             doc='Psi rotation in degrees. Optional or one entry per run.' )
 
-        self.declareProperty(FloatArrayProperty('Gl', values=[], direction=Direction.Input), doc='gl rotation in degrees. Optional or one entry per run.' )
+        self.declareProperty(FloatArrayProperty('Gl', values=[], direction=Direction.Input),
+                             doc='gl rotation in degrees. Optional or one entry per run.' )
 
-        self.declareProperty(FloatArrayProperty('Gs', values=[], direction=Direction.Input), doc='gs rotation in degrees. Optional or one entry per run.' )
+        self.declareProperty(FloatArrayProperty('Gs', values=[], direction=Direction.Input),
+                             doc='gs rotation in degrees. Optional or one entry per run.' )
 
-        self.declareProperty(IMDWorkspaceProperty('OutputWorkspace', '', direction=Direction.Output ), doc='Output MDWorkspace')
+        self.declareProperty(IMDWorkspaceProperty('OutputWorkspace', '', direction=Direction.Output ),
+                             doc='Output MDWorkspace')
+
+        self.declareProperty('InPlace', defaultValue=False, direction=Direction.Input,
+                             doc="Execute conversions to MD and Merge in one-step. Less memory overhead.")
 
     def _validate_inputs(self):
-    
         emode = self.getProperty('Emode').value
         alatt = self.getProperty('Alatt').value
         angdeg = self.getProperty('Angdeg').value
@@ -135,40 +167,44 @@ class CreateMD(DataProcessorAlgorithm):
         v = self.getProperty('v').value
         psi = self.getProperty('Psi').value
         gl = self.getProperty('Gl').value
-        gs = self.getProperty('Gs').value        
+        gs = self.getProperty('Gs').value
+        efix = self.getProperty('EFix').value
+
+        input_workspaces = self.getProperty("DataSources").value
 
-        input_workspaces = self.getProperty("InputWorkspaces").value
-        
         ws_entries = len(input_workspaces)
-        
+
         if ws_entries < 1:
-            raise ValueError("Need one or more input workspace")
-            
+            raise ValueError("Need one or more input datasource")
+
         if len(u) != 3:
             raise ValueError("u must have 3 components")
-            
+
         if len(v) != 3:
             raise ValueError("v must have 3 components")
-            
+
         if len(alatt) != 3:
             raise ValueError("lattice parameters must have 3 components")
-            
+
         if len(angdeg) != 3:
             raise ValueError("Angle must have 3 components")
 
         if not emode in self._possible_emodes():
             raise ValueError("Unknown emode %s Allowed values are %s" % (emode, self._possible_emodes()))
-            
+
         if len(psi) > 0 and len(psi) != ws_entries:
-            raise ValueError("If Psi is given a entry should be provided for every input workspace")
-        
+            raise ValueError("If Psi is given a entry should be provided for every input datasource")
+
         if len(gl) > 0 and len(gl) != ws_entries:
-            raise ValueError("If Gl is given a entry should be provided for every input workspace")
-            
+            raise ValueError("If Gl is given a entry should be provided for every input datasource")
+
         if len(gs) > 0 and len(gs) != ws_entries:
-            raise ValueError("If Gs is given a entry should be provided for every input workspace")
-         
-            
+            raise ValueError("If Gs is given a entry should be provided for every input datasource")
+
+        if len(efix) > 1 and len(efix) != ws_entries:
+            raise ValueError("Either specify a single EFix value, or as many as there are input datasources")
+
+
     def PyExec(self):
 
         logger.warning('You are running algorithm %s that is the beta stage of development' % (self.name()))
@@ -180,53 +216,72 @@ class CreateMD(DataProcessorAlgorithm):
         v = self.getProperty('v').value
         psi = self.getProperty('Psi').value
         gl = self.getProperty('Gl').value
-        gs = self.getProperty('Gs').value        
-        
-        input_workspaces = self.getProperty("InputWorkspaces").value
-        
-        ws_entries = len(input_workspaces)
-        
+        gs = self.getProperty('Gs').value
+        efix = self.getProperty('EFix').value
+        in_place = self.getProperty('InPlace')
+
+        data_sources = self.getProperty("DataSources").value
+
+        entries = len(data_sources)
+
         self._validate_inputs()
-            
+
+        #pad out lists
         if len(psi) == 0:
-            psi = [0.0] * ws_entries
-            
+            psi = [0.0] * entries
+
         if len(gl) == 0:
-            gl = [0.0] * ws_entries
-            
+            gl = [0.0] * entries
+
         if len(gs) == 0:
-            gs = [0.0] * ws_entries
-        
+            gs = [0.0] * entries
+
+        if len(efix) == 0:
+            efix = [-1.0] * entries
+        elif len(efix) == 1:
+            efix = efix * entries
+
         output_workspace = None
         run_md = None
 
         to_merge_names = list()
-        
-        run_data = zip(input_workspaces, psi, gl, gs)
-        for run_entry in run_data:
-                ws_name, psi_entry, gl_entry, gs_entry = run_entry
-                ws = AnalysisDataService.retrieve(ws_name)
-                run_md = self._single_run(input_workspace=ws, emode=emode, alatt=alatt, angdeg=angdeg, u=u, v=v, psi=psi_entry, gl=gl_entry, gs=gs_entry)
-                to_merge_name = ws_name + "_md"
-                AnalysisDataService.addOrReplace(to_merge_name, run_md)
-                to_merge_names.append(to_merge_name)
-
-        if len(to_merge_names) > 1:
-            output_workspace = self._merge_runs(to_merge_names)
-        else:
-            output_workspace = AnalysisDataService.retrieve(to_merge_names[0])
 
-        # Clear out temporary workspaces.
-        for ws in to_merge_names:
-            DeleteWorkspace(ws)
+        run_data = zip(data_sources, psi, gl, gs, efix)
+        counter = 0
+        run_md = None
+        for run_entry in run_data:
+            data_source, psi_entry, gl_entry, gs_entry, efix_entry = run_entry
+            must_load = not AnalysisDataService.doesExist(data_source)
+            ws = None
+            if must_load:
+                # Strip off any file extensions, and call it _md_{n} where n avoids clashes in the dictionary
+                ws_name = "%s_md_%i" % ( os.path.splitext(data_source)[0] , counter )  
+                ws = self._load_ws(data_source, ws_name)
+                to_merge_name = ws_name
+            else:
+                ws = AnalysisDataService.retrieve(data_source)
+                to_merge_name = "%s_md" %  data_source
 
-        self.setProperty("OutputWorkspace", output_workspace)
+            do_in_place = in_place and counter > 0 # We cannot process in place until we have an output MDWorkspace to use.
+            run_md = self._single_run(input_workspace=ws if in_place else ws, emode=emode, efix=efix_entry,
+                alatt=alatt, angdeg=angdeg, u=u, v=v, psi=psi_entry, gl=gl_entry, gs=gs_entry, in_place=do_in_place, out_mdws=run_md)
                 
+                
+            to_merge_names.append(to_merge_name)
 
+            AnalysisDataService.addOrReplace(to_merge_name, run_md)
 
+            counter += 1
 
+        if len(to_merge_names) > 1 and not in_place:
+            output_workspace = self._merge_runs(to_merge_names)
+        else:
+            output_workspace = AnalysisDataService.retrieve(to_merge_names[0])
 
+        # Clear out temporary workspaces. This could be done in an eager fashion.
+        for mdws in to_merge_names:
+            DeleteWorkspace(mdws)
 
-
+        self.setProperty("OutputWorkspace", output_workspace)
 
 AlgorithmFactory.subscribe(CreateMD)
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DensityOfStates.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DensityOfStates.py
index 3722e26c75cdf9525ff876ccc9e2261c239d5b89..ad1ce52e9f9756d412860593395737826f8ba27b 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DensityOfStates.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DensityOfStates.py
@@ -1,4 +1,4 @@
-#pylint: disable=no-init,invalid-name
+#pylint: disable=no-init,invalid-name,anomalous-backslash-in-string
 from mantid.kernel import *
 from mantid.api import *
 from mantid.simpleapi import *
@@ -149,9 +149,7 @@ class DensityOfStates(PythonAlgorithm):
                 if k in self._ions:
                     partial_ions[k] = v
 
-            partial_workspaces, sum_workspace = self._compute_partial_ion_workflow(
-                                                    partial_ions, frequencies,
-                                                    eigenvectors, weights)
+            partial_workspaces, sum_workspace = self._compute_partial_ion_workflow(partial_ions, frequencies, eigenvectors, weights)
 
             if self._sum_contributions:
                 # Discard the partial workspaces
@@ -174,9 +172,7 @@ class DensityOfStates(PythonAlgorithm):
 
             eigenvectors = file_data[4]
 
-            partial_workspaces, sum_workspace = self._compute_partial_ion_workflow(
-                                                    self._ion_dict, frequencies,
-                                                    eigenvectors, weights)
+            partial_workspaces, sum_workspace = self._compute_partial_ion_workflow(self._ion_dict, frequencies, eigenvectors, weights)
 
             # Discard the partial workspaces
             for partial_ws in partial_workspaces:
@@ -459,7 +455,7 @@ class DensityOfStates(PythonAlgorithm):
         weights = weights[:self._num_branches]
 
         # Speed of light in vaccum in m/s
-        c = scipy.constants.c
+        #c = scipy.constants.c #unused for now
         # Wavelength of the laser
         laser_wavelength = 514.5e-9
         # Planck's constant
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py
index 537d76c3e484a58abd12dd3fa5486188bb8f664c..d98f568175e3981e77b9b1f52b611ee35f9420a1 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py
@@ -1,4 +1,4 @@
-#pylint: disable=no-init
+#pylint: disable=no-init,too-many-instance-attributes,too-many-branches
 from mantid.simpleapi import *
 from mantid.kernel import *
 from mantid.api import *
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/HFIRSANSReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/HFIRSANSReduction.py
index 901625ad06ca4cc010c47f3fccb5112c477c09a5..196b2efd97a91313849582f0a5245a2d92a6adeb 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/HFIRSANSReduction.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/HFIRSANSReduction.py
@@ -1,4 +1,4 @@
-#pylint: disable=no-init,invalid-name
+#pylint: disable=no-init,invalid-name,too-many-branches
 import mantid.simpleapi as api
 from mantid.api import *
 from mantid.kernel import *
@@ -59,7 +59,7 @@ class HFIRSANSReduction(PythonAlgorithm):
                 if i==0:
                     output_str += _load_data(data_file[i], workspace)
                     # Use the first file location as the default output directory
-                    head, tail = os.path.split(data_file[0])
+                    head, dummy_tail = os.path.split(data_file[0])
                     if os.path.isdir(head):
                         self.default_output_dir = head
                 else:
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ISISIndirectEnergyTransfer.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ISISIndirectEnergyTransfer.py
new file mode 100644
index 0000000000000000000000000000000000000000..419418d24e831de9b6ea2c0003b24f35b5d48cda
--- /dev/null
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ISISIndirectEnergyTransfer.py
@@ -0,0 +1,839 @@
+#pylint: disable=invalid-name,attribute-defined-outside-init,too-many-instance-attributes,too-many-branches
+from mantid.kernel import *
+from mantid.api import *
+from mantid.simpleapi import *
+import mantid
+import os
+import string
+import numpy as np
+
+
+_str_or_none = lambda s: s if s != '' else None
+_float_or_none = lambda i: float(i) if i != '' else None
+_elems_or_none = lambda l: l if len(l) != 0 else None
+
+
+class ISISIndirectEnergyTransfer(DataProcessorAlgorithm):
+
+    def category(self):
+        return 'Workflow\\Inelastic;PythonAlgorithms;Inelastic'
+
+
+    def summary(self):
+        return 'Runs an energy transfer reduction for an inelastic indirect geometry instrument.'
+
+
+    def PyInit(self):
+        # Input properties
+        self.declareProperty(StringArrayProperty(name='InputFiles'),
+                             doc='Comma separated list of input files')
+
+        self.declareProperty(name='SumFiles', defaultValue=False, doc='Toggle input file summing or sequential processing')
+
+        self.declareProperty(WorkspaceProperty('CalibrationWorkspace', '', direction=Direction.Input, optional=PropertyMode.Optional),
+                             doc='Workspace contining calibration data')
+
+        # Instrument configuration properties
+        self.declareProperty(name='Instrument', defaultValue='', doc='Instrument used during run.',
+                             validator=StringListValidator(['IRIS', 'OSIRIS', 'TOSCA', 'TFXA']))
+        self.declareProperty(name='Analyser', defaultValue='', doc='Analyser bank used during run.',
+                             validator=StringListValidator(['graphite', 'mica', 'fmica']))
+        self.declareProperty(name='Reflection', defaultValue='', doc='Reflection number for instrument setup during run.',
+                             validator=StringListValidator(['002', '004', '006']))
+
+        self.declareProperty(IntArrayProperty(name='SpectraRange', values=[0, 1],validator=IntArrayMandatoryValidator()),
+                             doc='Comma separated range of spectra number to use.')
+        self.declareProperty(FloatArrayProperty(name='BackgroundRange'),
+                             doc='Range of background to subtact from raw data in time of flight.')
+        self.declareProperty(name='RebinString', defaultValue='', doc='Rebin string parameters.')
+        self.declareProperty(name='DetailedBalance', defaultValue='', doc='')
+        self.declareProperty(name='ScaleFactor', defaultValue=1.0, doc='Factor by which to scale result.')
+        self.declareProperty(name='FoldMultipleFrames', defaultValue=True,
+                             doc='Folds multiple framed data sets into a single workspace.')
+
+        # Spectra grouping options
+        self.declareProperty(name='GroupingMethod', defaultValue='IPF',
+                             validator=StringListValidator(['Individual', 'All', 'File', 'Workspace', 'IPF']),
+                             doc='Method used to group spectra.')
+        self.declareProperty(WorkspaceProperty('GroupingWorkspace', '', direction=Direction.Input, optional=PropertyMode.Optional),
+                             doc='Workspace containing spectra grouping.')
+        self.declareProperty(FileProperty('MapFile', '', action=FileAction.OptionalLoad, extensions=['.map']),
+                             doc='Workspace containing spectra grouping.')
+
+        # Output properties
+        self.declareProperty(name='UnitX', defaultValue='DeltaE', doc='X axis units for the result workspace.',
+                             validator=StringListValidator(['DeltaE', 'DeltaE_inWavenumber']))
+        self.declareProperty(StringArrayProperty(name='SaveFormats'), doc='Comma seperated list of save formats')
+        self.declareProperty(name='Plot', defaultValue='None', doc='Type of plot to output after reduction.',
+                             validator=StringListValidator(['None', 'Spectra', 'Contour', 'Both']))
+
+        self.declareProperty(WorkspaceGroupProperty('OutputWorkspace', '', direction=Direction.Output),
+                             doc='Workspace group for the resulting workspaces.')
+
+
+    def PyExec(self):
+        self._setup()
+        self._load_files()
+
+        for c_ws_name in self._workspace_names:
+            is_multi_frame = isinstance(mtd[c_ws_name], WorkspaceGroup)
+
+            # Get list of workspaces
+            if is_multi_frame:
+                workspaces = mtd[c_ws_name].getNames()
+            else:
+                workspaces = [c_ws_name]
+
+            # Process rebinning for framed data
+            if self._rebin_string is not None and is_multi_frame:
+                rebin_string_comp = self._rebin_string.split(',')
+                if len(rebin_string_comp) >= 5:
+                    rebin_string_2 = ','.join(rebin_string_comp[2:])
+                else:
+                    rebin_string_2 = self._rebin_string
+
+                bin_counts = [mtd[ws].blocksize() for ws in mtd[c_ws_name].getNames()]
+                num_bins = np.amax(bin_counts)
+
+            masked_detectors = self._identify_bad_detectors(workspaces[0])
+
+            # Process workspaces
+            for ws_name in workspaces:
+                monitor_ws_name = ws_name + '_mon'
+
+                # Process monitor
+                if not self._unwrap_monitor(ws_name):
+                    ConvertUnits(InputWorkspace=monitor_ws_name, OutputWorkspace=monitor_ws_name, Target='Wavelength', EMode='Elastic')
+
+                self._process_monitor_efficiency(ws_name)
+                self._scale_monitor(ws_name)
+
+
+                # Do background removal if a range was provided
+                if self._background_range is not None:
+                    ConvertToDistribution(Workspace=ws_name)
+                    CalculateFlatBackground(InputWorkspace=ws_name, OutputWorkspace=ws_name,
+                                            StartX=self._background_range[0],
+                                            EndX=self._background_range[1],
+                                            Mode='Mean')
+                    ConvertFromDistribution(Workspace=ws_name)
+
+                # Divide by the calibration workspace if one was provided
+                if self._calibration_ws is not None:
+                    Divide(LHSWorkspace=ws_name,
+                           RHSWorkspace=self._calibration_ws,
+                           OutputWorkspace=ws_name)
+
+                # Scale detector data by monitor intensities
+                ConvertUnits(InputWorkspace=ws_name, OutputWorkspace=ws_name, Target='Wavelength', EMode='Indirect')
+                RebinToWorkspace(WorkspaceToRebin=ws_name, WorkspaceToMatch=monitor_ws_name, OutputWorkspace=ws_name)
+                Divide(LHSWorkspace=ws_name, RHSWorkspace=monitor_ws_name, OutputWorkspace=ws_name)
+
+                # Remove the no longer needed monitor workspace
+                DeleteWorkspace(monitor_ws_name)
+
+                # Convert to energy
+                ConvertUnits(InputWorkspace=ws_name, OutputWorkspace=ws_name, Target='DeltaE', EMode='Indirect')
+                CorrectKiKf(InputWorkspace=ws_name, OutputWorkspace=ws_name, EMode='Indirect')
+
+                # Handle rebinning
+                if self._rebin_string is not None:
+                    if is_multi_frame:
+                        # Mulit frame data
+                        if mtd[ws_name].blocksize() == num_bins:
+                            Rebin(InputWorkspace=ws_name, OutputWorkspace=ws_name, Params=self._rebin_string)
+                        else:
+                            Rebin(InputWorkspace=ws_name, OutputWorkspace=ws_name, Params=rebin_string_2)
+                    else:
+                        # Regular data
+                        Rebin(InputWorkspace=ws_name, OutputWorkspace=ws_name, Params=self._rebin_string)
+                else:
+                    try:
+                        # If user does not want to rebin then just ensure uniform binning across spectra
+                        RebinToWorkspace(WorkspaceToRebin=ws_name, WorkspaceToMatch=ws_name, OutputWorkspace=ws_name)
+                    except RuntimeError:
+                        logger.warning('Rebinning failed, will try to continue anyway.')
+
+                # Detailed balance
+                if self._detailed_balance is not None:
+                    corr_factor = 11.606 / (2 * self._detailed_balance)
+                    ExponentialCorrection(InputWorkspaces=ws_name, OutputWorkspace=ws_name,
+                                          C0=1.0, C1=corr_factor, Operation='Multiply')
+
+                # Scale
+                if self._scale_factor != 1.0:
+                    Scale(InputWorkspaces=ws_name, OutputWorkspace=ws_name,
+                          Factor=self._scale_factor, Operation='Multiply')
+
+                # Group spectra
+                self._group_spectra(ws_name, masked_detectors)
+
+            if self._fold_multiple_frames and is_multi_frame:
+                self._fold_chopped(c_ws_name)
+
+            # Convert to output units if needed
+            if self._output_x_units != 'DeltaE':
+                ConvertUnits(InputWorkspace=c_ws_name, OutputWorkspace=c_ws_name,
+                             EMode='Indirect', Target=self._output_x_units)
+
+        # Rename output workspaces
+        output_workspace_names = [self._rename_workspace(ws_name) for ws_name in self._workspace_names]
+
+        # Save result workspaces
+        if self._save_formats is not None:
+            self._save(output_workspace_names)
+
+        # Group result workspaces
+        GroupWorkspaces(InputWorkspaces=output_workspace_names, OutputWorkspace=self._output_ws)
+
+        self.setProperty('OutputWorkspace', self._output_ws)
+
+        # Plot result workspaces
+        if self._plot_type != 'None':
+            for ws_name in mtd[self._output_ws].getNames():
+                self._plot_workspace(ws_name)
+
+
+    def validateInputs(self):
+        """
+        Validates algorithm properties.
+        """
+        issues = dict()
+
+        # Validate the instrument configuration by checking if a parameter file exists
+        instrument_name = self.getPropertyValue('Instrument')
+        analyser = self.getPropertyValue('Analyser')
+        reflection = self.getPropertyValue('Reflection')
+
+        ipf_filename = os.path.join(config['instrumentDefinition.directory'],
+                                    instrument_name + '_' + analyser + '_' + reflection + '_Parameters.xml')
+
+        if not os.path.exists(ipf_filename):
+            error_message = 'Invalid instrument configuration'
+            issues['Instrument'] = error_message
+            issues['Analyser'] = error_message
+            issues['Reflection'] = error_message
+
+        # Validate spectra range
+        spectra_range = self.getProperty('SpectraRange').value
+        if len(spectra_range) != 2:
+            issues['SpectraRange'] = 'Range must contain exactly two items'
+        elif spectra_range[0] > spectra_range[1]:
+            issues['SpectraRange'] = 'Range must be in format: lower,upper'
+
+        # Validate background range
+        background_range = _elems_or_none(self.getProperty('BackgroundRange').value)
+        if background_range is not None:
+            if len(background_range) != 2:
+                issues['BackgroundRange'] = 'Range must contain exactly two items'
+            elif background_range[0] > background_range[1]:
+                issues['BackgroundRange'] = 'Range must be in format: lower,upper'
+
+        # Validate grouping method
+        grouping_method = self.getPropertyValue('GroupingMethod')
+        grouping_ws = _str_or_none(self.getPropertyValue('GroupingWorkspace'))
+
+        if grouping_method == 'Workspace' and grouping_ws is None:
+            issues['GroupingWorkspace'] = 'Must select a grouping workspace for current GroupingWorkspace'
+
+        # Validate save formats
+        save_formats = self.getProperty('SaveFormats').value
+        valid_formats = ['nxs', 'ascii', 'spe', 'nxspe', 'aclimax', 'davegrp']
+        for format_name in save_formats:
+            if format_name not in valid_formats:
+                issues['SaveFormats'] = '%s is not a valid save format' % format_name
+                break
+
+        return issues
+
+
+    def _setup(self):
+        """
+        Gets algorithm properties.
+        """
+
+        # Get properties
+        self._data_files = self.getProperty('InputFiles').value
+        self._sum_files = self.getProperty('SumFiles').value
+        self._calibration_ws = _str_or_none(self.getPropertyValue('CalibrationWorkspace'))
+
+        self._instrument_name = self.getPropertyValue('Instrument')
+        self._analyser = self.getPropertyValue('Analyser')
+        self._reflection = self.getPropertyValue('Reflection')
+
+        self._spectra_range = self.getProperty('SpectraRange').value
+        self._background_range = _elems_or_none(self.getProperty('BackgroundRange').value)
+        self._rebin_string = _str_or_none(self.getPropertyValue('RebinString'))
+        self._detailed_balance = _float_or_none(self.getPropertyValue('DetailedBalance'))
+        self._scale_factor = self.getProperty('ScaleFactor').value
+        self._fold_multiple_frames = self.getProperty('FoldMultipleFrames').value
+
+        self._grouping_method = self.getPropertyValue('GroupingMethod')
+        self._grouping_ws = _str_or_none(self.getPropertyValue('GroupingWorkspace'))
+        self._grouping_map_file = _str_or_none(self.getPropertyValue('MapFile'))
+
+        self._output_x_units = self.getPropertyValue('UnitX')
+        self._plot_type = self.getPropertyValue('Plot')
+        self._save_formats = _elems_or_none(self.getProperty('SaveFormats').value)
+
+        self._output_ws = self.getPropertyValue('OutputWorkspace')
+
+        # Disable sum files if there is only one file
+        if len(self._data_files) == 1:
+            if self._sum_files:
+                logger.warning('SumFiles disabled when only one input file is provided.')
+            self._sum_files = False
+
+        # Get the IPF filename
+        self._ipf_filename = os.path.join(config['instrumentDefinition.directory'],
+                                          self._instrument_name + '_' + self._analyser + '_' + self._reflection + '_Parameters.xml')
+        logger.information('Instrument parameter file: %s' % self._ipf_filename)
+
+        # Warn when grouping options are to be ignored
+        if self._grouping_method != 'Workspace' and self._grouping_ws is not None:
+            logger.warning('GroupingWorkspace will be ignored by selected GroupingMethod')
+
+        if self._grouping_method != 'File' and self._grouping_map_file is not None:
+            logger.warning('MapFile will be ignored by selected GroupingMethod')
+
+        # The list of workspaces being processed
+        self._workspace_names = []
+
+
+    def _load_files(self):
+        """
+        Loads a set of files and extracts just the spectra we care about (i.e. detector range and monitor).
+        """
+
+        for filename in self._data_files:
+            # The filename without path and extension will be the workspace name
+            ws_name = os.path.splitext(os.path.basename(filename))[0]
+            logger.debug('Loading file %s as workspace %s' % (filename, ws_name))
+
+            Load(Filename=filename, OutputWorkspace=ws_name)
+
+            # Load the instrument parameters
+            LoadParameterFile(Workspace=ws_name, Filename=self._ipf_filename)
+
+            # Add the workspace to the list of workspaces
+            self._workspace_names.append(ws_name)
+
+            # Get the spectrum number for the monitor
+            instrument = mtd[ws_name].getInstrument()
+            monitor_index = int(instrument.getNumberParameter('Workflow.Monitor1-SpectrumNumber')[0])
+            logger.debug('Workspace %s monitor 1 spectrum number :%d' % (ws_name, monitor_index))
+
+            # Chop data if required
+            try:
+                chop_threshold = mtd[ws_name].getInstrument().getNumberParameter('Workflow.ChopDataIfGreaterThan')[0]
+                x_max = mtd[ws_name].readX(0)[-1]
+                self._chopped_data =  x_max > chop_threshold
+            except IndexError:
+                self._chopped_data = False
+            logger.information('Workspace %s need data chop: %s' % (ws_name, str(self._chopped_data)))
+
+            workspaces = [ws_name]
+            if self._chopped_data:
+                ChopData(InputWorkspace=ws_name, OutputWorkspace=ws_name, MonitorWorkspaceIndex=monitor_index,
+                         IntegrationRangeLower=5000.0, IntegrationRangeUpper=10000.0, NChops=5)
+                workspaces = mtd[ws_name].getNames()
+
+            for chop_ws_name in workspaces:
+                # Get the monitor spectrum
+                monitor_ws_name = chop_ws_name + '_mon'
+                ExtractSingleSpectrum(InputWorkspace=chop_ws_name, OutputWorkspace=monitor_ws_name,
+                                      WorkspaceIndex=monitor_index)
+
+                # Crop to the detectors required
+                CropWorkspace(InputWorkspace=chop_ws_name, OutputWorkspace=chop_ws_name,
+                              StartWorkspaceIndex=int(self._spectra_range[0]) - 1,
+                              EndWorkspaceIndex=int(self._spectra_range[1]) - 1)
+
+        logger.information('Loaded workspace names: %s' % (str(self._workspace_names)))
+        logger.information('Chopped data: %s' % (str(self._chopped_data)))
+
+        # Sum files if needed
+        if self._sum_files:
+            if self._chopped_data:
+                self._sum_chopped_runs()
+            else:
+                self._sum_regular_runs()
+
+        logger.information('Summed workspace names: %s' % (str(self._workspace_names)))
+
+
+    def _sum_regular_runs(self):
+        """
+        Sum runs with single workspace data.
+        """
+
+        # Use the first workspace name as the result of summation
+        summed_detector_ws_name = self._workspace_names[0]
+        summed_monitor_ws_name = self._workspace_names[0] + '_mon'
+
+        # Get a list of the run numbers for the original data
+        run_numbers = ','.join([str(mtd[ws_name].getRunNumber()) for ws_name in self._workspace_names])
+
+        # Generate lists of the detector and monitor workspaces
+        detector_workspaces = ','.join(self._workspace_names)
+        monitor_workspaces = ','.join([ws_name + '_mon' for ws_name in self._workspace_names])
+
+        # Merge the raw workspaces
+        MergeRuns(InputWorkspaces=detector_workspaces, OutputWorkspace=summed_detector_ws_name)
+        MergeRuns(InputWorkspaces=monitor_workspaces, OutputWorkspace=summed_monitor_ws_name)
+
+        # Delete old workspaces
+        for idx in range(1, len(self._workspace_names)):
+            DeleteWorkspace(self._workspace_names[idx])
+            DeleteWorkspace(self._workspace_names[idx] + '_mon')
+
+        # Derive the scale factor based on number of merged workspaces
+        scale_factor = 1.0 / len(self._workspace_names)
+        logger.information('Scale factor for summed workspaces: %f' % scale_factor)
+
+        # Scale the new detector and monitor workspaces
+        Scale(InputWorkspace=summed_detector_ws_name, OutputWorkspace=summed_detector_ws_name,
+              Factor=scale_factor)
+        Scale(InputWorkspace=summed_monitor_ws_name, OutputWorkspace=summed_monitor_ws_name,
+              Factor=scale_factor)
+
+        # Add the list of run numbers to the result workspace as a sample log
+        AddSampleLog(Workspace=summed_detector_ws_name, LogName='multi_run_numbers',
+                     LogType='String', LogText=run_numbers)
+
+        # Only have the one workspace now
+        self._workspace_names = [summed_detector_ws_name]
+
+
+    def _sum_chopped_runs(self):
+        """
+        Sum runs with chopped data.
+        """
+
+        try:
+            num_merges = len(mtd[self._workspace_names[0]].getNames())
+        except:
+            raise RuntimeError('Not all runs have been chapped, cannot sum.')
+
+        merges = list()
+
+        # Generate a list of workspaces to be merged
+        for idx in range(0, num_merges):
+            merges.append({'detector':list(), 'monitor':list()})
+
+            for ws_name in self._workspace_names:
+                detector_ws_name = mtd[ws_name].getNames()[idx]
+                monitor_ws_name = detector_ws_name + '_mon'
+
+                merges[idx]['detector'].append(detector_ws_name)
+                merges[idx]['monitor'].append(monitor_ws_name)
+
+        for merge in merges:
+            # Merge the chopped run segments
+            MergeRuns(InputWorkspaces=','.join(merge['detector']), OutputWorkspace=merge['detector'][0])
+            MergeRuns(InputWorkspaces=','.join(merge['monitor']), OutputWorkspace=merge['monitor'][0])
+
+            # Scale the merged runs
+            merge_size = len(merge['detector'])
+            factor = 1.0 / merge_size
+            Scale(InputWorkspace=merge['detector'][0], OutputWorkspace=merge['detector'][0], Factor=factor, Operation='Multiply')
+            Scale(InputWorkspace=merge['monitor'][0], OutputWorkspace=merge['monitor'][0], Factor=factor, Operation='Multiply')
+
+            # Remove the old workspaces
+            for idx in range(1, merge_size):
+                DeleteWorkspace(merge['detector'][idx])
+                DeleteWorkspace(merge['monitor'][idx])
+
+        # Only have the one workspace now
+        self._workspace_names = [self._workspace_names[0]]
+
+
+    def _identify_bad_detectors(self, ws_name):
+        """
+        Identify detectors which should be masked
+
+        @param ws_name Name of worksapce to use ot get masking detectors
+        """
+
+        instrument = mtd[ws_name].getInstrument()
+
+        try:
+            masking_type = instrument.getStringParameter('Workflow.Masking')[0]
+        except IndexError:
+            masking_type = 'None'
+
+        logger.information('Masking type: %s' % (masking_type))
+
+        masked_spec = list()
+
+        if masking_type == 'IdentifyNoisyDetectors':
+            ws_mask = '__workspace_mask'
+            IdentifyNoisyDetectors(InputWorkspace=ws_name, OutputWorkspace=ws_mask)
+
+            # Convert workspace to a list of spectra
+            num_spec = mtd[ws_mask].getNumberHistograms()
+            masked_spec = [spec for spec in range(0, num_spec) if mtd[ws_mask].readY(spec)[0] == 0.0]
+
+            # Remove the temporary masking workspace
+            DeleteWorkspace(ws_mask)
+
+        logger.debug('Masked specta for workspace %s: %s' % (ws_name, str(masked_spec)))
+
+        return masked_spec
+
+
+    def _unwrap_monitor(self, ws_name):
+        """
+        Unwrap monitor if required based on value of Workflow.UnwrapMonitor parameter
+
+        @param ws_name Name of workspace
+        @return True if the monitor was unwrapped
+        """
+
+        monitor_ws_name = ws_name + '_mon'
+        instrument = mtd[monitor_ws_name].getInstrument()
+
+        # Determine if the monitor should be unwrapped
+        try:
+            unwrap = instrument.getStringParameter('Workflow.UnwrapMonitor')[0]
+
+            if unwrap == 'Always':
+                should_unwrap = True
+            elif unwrap == 'BaseOnTimeRegime':
+                mon_time = mtd[monitor_ws_name].readX(0)[0]
+                det_time = mtd[ws_name].readX(0)[0]
+                logger.notice(str(mon_time) + " " + str(det_time))
+                should_unwrap = mon_time == det_time
+            else:
+                should_unwrap = False
+
+        except IndexError:
+            should_unwrap = False
+
+        logger.debug('Need to unwrap monitor for %s: %s' % (ws_name, str(should_unwrap)))
+
+        if should_unwrap:
+            sample = instrument.getSample()
+            sample_to_source = sample.getPos() - instrument.getSource().getPos()
+            radius = mtd[ws_name].getDetector(0).getDistance(sample)
+            z_dist = sample_to_source.getZ()
+            l_ref = z_dist + radius
+
+            logger.debug('For workspace %s: radius=%d, z_dist=%d, l_ref=%d' %
+                         (ws_name, radius, z_dist, l_ref))
+
+            _, join = UnwrapMonitor(InputWorkspace=monitor_ws_name,
+                                    OutputWorkspace=monitor_ws_name, LRef=l_ref)
+
+            RemoveBins(InputWorkspace=monitor_ws_name, OutputWorkspace=monitor_ws_name,
+                       XMin=join - 0.001, XMax=join + 0.001,
+                       Interpolation='Linear')
+
+            try:
+                FFTSmooth(InputWorkspace=monitor_ws_name, OutputWorkspace=monitor_ws_name, WorkspaceIndex=0)
+            except ValueError:
+                raise ValueError('Uneven bin widths are not supported.')
+
+        return should_unwrap
+
+
+    def _process_monitor_efficiency(self, ws_name):
+        """
+        Process monitor efficiency for a given workspace.
+
+        @param ws_name Name of workspace to process monitor for
+        """
+
+        monitor_ws_name = ws_name + '_mon'
+        instrument = mtd[ws_name].getInstrument()
+
+        try:
+            area = instrument.getNumberParameter('Workflow.Monitor1-Area')[0]
+            thickness = instrument.getNumberParameter('Workflow.Monitor1-Thickness')[0]
+            attenuation = instrument.getNumberParameter('Workflow.Monitor1-Attenuation')[0]
+        except IndexError:
+            raise ValueError('Cannot get monitor details form parameter file')
+
+        if area == -1 or thickness == -1 or attenuation == -1:
+            logger.information('For workspace %s, skipping monitor efficiency' % (ws_name))
+            return
+
+        OneMinusExponentialCor(InputWorkspace=monitor_ws_name, OutputWorkspace=monitor_ws_name,
+                               C=attenuation * thickness, C1=area)
+
+
+    def _scale_monitor(self, ws_name):
+        """
+        Scale monitor intensity by a factor given as the Workflow.MonitorScalingFactor parameter.
+
+        @param ws_name Name of workspace to process monitor for
+        """
+
+        monitor_ws_name = ws_name + '_mon'
+        instrument = mtd[ws_name].getInstrument()
+
+        try:
+            scale_factor = instrument.getNumberParameter('Workflow.Monitor1-ScalingFactor')[0]
+        except IndexError:
+            logger.information('No monitor scaling factor found for workspace %s' % ws_name)
+            return
+
+        if scale_factor != 1.0:
+            Scale(InputWorkspace=monitor_ws_name, OutputWorkspace=monitor_ws_name,
+                  Factor=1.0 / scale_factor, Operation='Multiply')
+
+
+    def _group_spectra(self, ws_name, masked_detectors):
+        """
+        Groups spectra in a given workspace according to the Workflow.GroupingMethod and
+        Workflow.GroupingFile parameters and GrpupingPolicy property.
+
+        @param ws_name Name of workspace to group spectra of
+        @param masked_detectors List of spectra numbers to mask
+        """
+
+        instrument = mtd[ws_name].getInstrument()
+
+        # If grouping as per he IPF is desired
+        if self._grouping_method == 'IPF':
+            # Get the grouping method from the parameter file
+            try:
+                grouping_method = instrument.getStringParameter('Workflow.GroupingMethod')[0]
+            except IndexError:
+                grouping_method = 'Individual'
+
+        else:
+            # Otherwise use the value of GroupingPolicy
+            grouping_method = self._grouping_method
+
+        logger.information('Grouping method for workspace %s is %s' % (ws_name, grouping_method))
+
+        if grouping_method == 'Individual':
+            # Nothing to do here
+            return
+
+        elif grouping_method == 'All':
+            # Get a list of all spectra minus those which are masked
+            num_spec = mtd[ws_name].getNumberHistograms()
+            spectra_list = [spec for spec in range(0, num_spec) if spec not in masked_detectors]
+
+            # Apply the grouping
+            GroupDetectors(InputWorkspace=ws_name, OutputWorkspace=ws_name, Behaviour='Average',
+                           WorkspaceIndexList=spectra_list)
+
+        elif grouping_method == 'File':
+            # Get the filename for the grouping file
+            if self._grouping_map_file is not None:
+                grouping_file = self._grouping_map_file
+            else:
+                try:
+                    grouping_file = instrument.getStringParameter('Workflow.GroupingFile')[0]
+                except IndexError:
+                    raise RuntimeError('Cannot get grouping file from properties or IPF.')
+
+            # If the file is not found assume it is in the grouping files directory
+            if not os.path.isfile(grouping_file):
+                grouping_file = os.path.join(config.getString('groupingFiles.directory'), grouping_file)
+
+            # If it is still not found just give up
+            if not os.path.isfile(grouping_file):
+                raise RuntimeError('Cannot find grouping file: %s' % (grouping_file))
+
+            # Mask detectors if required
+            if len(masked_detectors) > 0:
+                MaskDetectors(Workspace=ws_name, WorkspaceIndexList=masked_detectors)
+
+            # Apply the grouping
+            GroupDetectors(InputWorkspace=ws_name, OutputWorkspace=ws_name, Behaviour='Average',
+                           MapFile=grouping_file)
+
+        elif grouping_method == 'Workspace':
+            # Apply the grouping
+            GroupDetectors(InputWorkspace=ws_name, OutputWorkspace=ws_name, Behaviour='Average',
+                           CopyGroupingFromWorkspace=self._grouping_ws)
+
+        else:
+            raise RuntimeError('Invalid grouping method %s for workspace %s' % (grouping_method, ws_name))
+
+
+    def _fold_chopped(self, ws_name):
+        """
+        Folds multiple frames of a data set into one workspace.
+
+        @param ws_name Name of the group to fold
+        """
+
+        workspaces = mtd[ws_name].getNames()
+        merged_ws = ws_name + '_merged'
+        MergeRuns(InputWorkspaces=','.join(workspaces), OutputWorkspace=merged_ws)
+
+        scaling_ws = '__scaling_ws'
+        unit = mtd[ws_name].getItem(0).getAxis(0).getUnit().unitID()
+
+        ranges = []
+        for ws in mtd[ws_name].getNames():
+            x_min = mtd[ws].dataX(0)[0]
+            x_max = mtd[ws].dataX(0)[-1]
+            ranges.append((x_min, x_max))
+            DeleteWorkspace(Workspace=ws)
+
+        data_x = mtd[merged_ws].readX(0)
+        data_y = []
+        data_e = []
+
+        for i in range(0, mtd[merged_ws].blocksize()):
+            y_val = 0.0
+            for rng in ranges:
+                if data_x[i] >= rng[0] and data_x[i] <= rng[1]:
+                    y_val += 1.0
+
+            data_y.append(y_val)
+            data_e.append(0.0)
+
+        CreateWorkspace(OutputWorkspace=scaling_ws, DataX=data_x, DataY=data_y, DataE=data_e, UnitX=unit)
+
+        Divide(LHSWorkspace=merged_ws, RHSWorkspace=scaling_ws, OutputWorkspace=ws_name)
+        DeleteWorkspace(Workspace=merged_ws)
+        DeleteWorkspace(Workspace=scaling_ws)
+
+    def _rename_workspace(self, ws_name):
+        """
+        Renames a worksapce according to the naming policy in the Workflow.NamingConvention parameter.
+
+        @param ws_name Name of workspace
+        @return New name of workspace
+        """
+
+        is_multi_frame = isinstance(mtd[ws_name], WorkspaceGroup)
+
+        # Get the instrument
+        if is_multi_frame:
+            instrument = mtd[ws_name].getItem(0).getInstrument()
+        else:
+            instrument = mtd[ws_name].getInstrument()
+
+        # Get the naming convention parameter form the parameter file
+        try:
+            convention = instrument.getStringParameter('Workflow.NamingConvention')[0]
+        except IndexError:
+            # Defualt to run title if naming convention parameter not set
+            convention = 'RunTitle'
+        logger.information('Naming convention for workspace %s is %s' % (ws_name, convention))
+
+        # Get run number
+        if is_multi_frame:
+            run_number = mtd[ws_name].getItem(0).getRun()['run_number'].value
+        else:
+            run_number = mtd[ws_name].getRun()['run_number'].value
+        logger.information('Run number for workspace %s is %s' % (ws_name, run_number))
+
+        inst_name = instrument.getName()
+        for facility in config.getFacilities():
+            try:
+                short_inst_name = facility.instrument(inst_name).shortName()
+                break
+            except:
+                pass
+        logger.information('Short name for instrument %s is %s' % (inst_name, short_inst_name))
+
+        # Get run title
+        if is_multi_frame:
+            run_title = mtd[ws_name].getItem(0).getRun()['run_title'].value.strip()
+        else:
+            run_title = mtd[ws_name].getRun()['run_title'].value.strip()
+        logger.information('Run title for workspace %s is %s' % (ws_name, run_title))
+
+        if self._sum_files:
+            multi_run_marker = '_multi'
+        else:
+            multi_run_marker = ''
+
+        if convention == 'None':
+            new_name = ws_name
+
+        elif convention == 'RunTitle':
+            valid = "-_.() %s%s" % (string.ascii_letters, string.digits)
+            formatted_title = ''.join([c for c in run_title if c in valid])
+            new_name = '%s%s%s-%s' % (short_inst_name.lower(), run_number, multi_run_marker, formatted_title)
+
+        elif convention == 'AnalyserReflection':
+            analyser = instrument.getStringParameter('analyser')[0]
+            reflection = instrument.getStringParameter('reflection')[0]
+            new_name = '%s%s%s_%s%s_red' % (short_inst_name.upper(), run_number, multi_run_marker,
+                                            analyser, reflection)
+
+        else:
+            raise RuntimeError('No valid naming convention for workspace %s' % ws_name)
+
+        logger.information('New name for %s workspace: %s' % (ws_name, new_name))
+
+        RenameWorkspace(InputWorkspace=ws_name, OutputWorkspace=new_name)
+        return new_name
+
+
+    def _plot_workspace(self, ws_name):
+        """
+        Plot a given workspace based on the Plot property.
+
+        @param ws_name Name of workspace to plot
+        """
+
+        if self._plot_type == 'Spectra' or self._plot_type == 'Both':
+            from mantidplot import plotSpectrum
+            num_spectra = mtd[ws_name].getNumberHistograms()
+            try:
+                plotSpectrum(ws_name, range(0, num_spectra))
+            except RuntimeError:
+                logger.notice('Spectrum plotting canceled by user')
+
+        can_plot_contour = mtd[ws_name].getNumberHistograms() > 1
+        if (self._plot_type == 'Contour' or self._plot_type == 'Both') and can_plot_contour:
+            from mantidplot import importMatrixWorkspace
+            plot_workspace = importMatrixWorkspace(ws_name)
+            plot_workspace.plotGraph2D()
+
+
+    def _save(self, worksspace_names):
+        """
+        Saves the workspaces to the default save directory.
+
+        @param worksspace_names List of workspace names to save
+        """
+
+        for ws_name in worksspace_names:
+            if 'spe' in self._save_formats:
+                SaveSPE(InputWorkspace=ws_name, Filename=ws_name + '.spe')
+
+            if 'nxs' in self._save_formats:
+                SaveNexusProcessed(InputWorkspace=ws_name, Filename=ws_name + '.nxs')
+
+            if 'nxspe' in self._save_formats:
+                SaveNXSPE(InputWorkspace=ws_name, Filename=ws_name + '.nxspe')
+
+            if 'ascii' in self._save_formats:
+                # Version 1 of SaveASCII produces output that works better with excel/origin
+                # For some reason this has to be done with an algorithm object, using the function
+                # wrapper with Version did not change the version that was run
+                saveAsciiAlg = mantid.api.AlgorithmManager.createUnmanaged('SaveAscii', 1)
+                saveAsciiAlg.initialize()
+                saveAsciiAlg.setProperty('InputWorkspace', ws_name)
+                saveAsciiAlg.setProperty('Filename', ws_name + '.dat')
+                saveAsciiAlg.execute()
+
+            if 'aclimax' in self._save_formats:
+                if self._output_x_units == 'DeltaE_inWavenumber':
+                    bins = '24, -0.005, 4000' #cm-1
+                else:
+                    bins = '3, -0.005, 500' #meV
+                Rebin(InputWorkspace=ws_name,OutputWorkspace= ws_name + '_aclimax_save_temp', Params=bins)
+                SaveAscii(InputWorkspace=ws_name + '_aclimax_save_temp', Filename=ws_name + '_aclimax.dat', Separator='Tab')
+                DeleteWorkspace(Workspace=ws_name + '_aclimax_save_temp')
+
+            if 'davegrp' in self._save_formats:
+                ConvertSpectrumAxis(InputWorkspace=ws_name, OutputWorkspace=ws_name + '_davegrp_save_temp', Target='ElasticQ', EMode='Indirect')
+                SaveDaveGrp(InputWorkspace=ws_name + '_davegrp_save_temp', Filename=ws_name + '.grp')
+                DeleteWorkspace(Workspace=ws_name + '_davegrp_save_temp')
+
+
+# Register algorithm with Mantid
+AlgorithmFactory.subscribe(ISISIndirectEnergyTransfer)
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectCalibration.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectCalibration.py
index 316d12877b0f512c79da826ec4437c7e67c8c642..e0b2ddb9cf82e0e26278a0310464c70db097232f 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectCalibration.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectCalibration.py
@@ -29,26 +29,28 @@ class IndirectCalibration(DataProcessorAlgorithm):
         self.declareProperty(StringArrayProperty(name='InputFiles'),
                              doc='Comma separated list of input files')
 
-        self.declareProperty(WorkspaceProperty('OutputWorkspace', '',\
-                             direction=Direction.Output),
-                             doc='Output workspace for calibration data')
-
         self.declareProperty(IntArrayProperty(name='DetectorRange', values=[0, 1],\
                              validator=IntArrayMandatoryValidator()),
-                             doc='Range of detectors')
+                             doc='Range of detectors.')
 
         self.declareProperty(FloatArrayProperty(name='PeakRange', values=[0.0, 100.0],\
                              validator=FloatArrayMandatoryValidator()),
-                             doc='')
+                             doc='Time of flight range over the peak.')
 
         self.declareProperty(FloatArrayProperty(name='BackgroundRange', values=[0.0, 1000.0],\
                              validator=FloatArrayMandatoryValidator()),
-                             doc='')
+                             doc='Time of flight range over the background.')
 
         self.declareProperty(name='ScaleFactor', defaultValue=1.0,
-                             doc='')
+                             doc='Factor by which to scale the result.')
+
+        self.declareProperty(name='Plot', defaultValue=False,
+                             doc='Plot the calibration data as a spectra plot.')
+
+        self.declareProperty(WorkspaceProperty('OutputWorkspace', '',
+                             direction=Direction.Output),
+                             doc='Output workspace for calibration data.')
 
-        self.declareProperty(name='Plot', defaultValue=False, doc='Plot the calibration data')
 
 
     def validateInputs(self):
@@ -107,14 +109,25 @@ class IndirectCalibration(DataProcessorAlgorithm):
         else:
             calib_ws_name = runs[0]
 
-        CalculateFlatBackground(InputWorkspace=calib_ws_name, OutputWorkspace=calib_ws_name,\
-                StartX=self._back_range[0], EndX=self._back_range[1], Mode='Mean')
+        CalculateFlatBackground(InputWorkspace=calib_ws_name, OutputWorkspace=calib_ws_name,
+                                StartX=self._back_range[0], EndX=self._back_range[1], Mode='Mean')
+
+        number_historgrams = mtd[calib_ws_name].getNumberHistograms()
+        ws_mask, num_zero_spectra = FindDetectorsOutsideLimits(InputWorkspace=calib_ws_name, OutputWorkspace='__temp_ws_mask')
+        DeleteWorkspace(ws_mask)
+
+        Integration(InputWorkspace=calib_ws_name, OutputWorkspace=calib_ws_name,
+                    RangeLower=self._peak_range[0], RangeUpper=self._peak_range[1])
+
+        temp_sum = SumSpectra(InputWorkspace=calib_ws_name, OutputWorkspace='__temp_sum')
+        total = temp_sum.readY(0)[0]
+        DeleteWorkspace(temp_sum)
+
+        if self._intensity_scale is None:
+            self._intensity_scale = 1 / (total / (number_historgrams - num_zero_spectra))
 
-        from inelastic_indirect_reduction_steps import NormaliseToUnityStep
-        ntu = NormaliseToUnityStep()
-        ntu.set_factor(self._intensity_scale)
-        ntu.set_peak_range(self._peak_range[0], self._peak_range[1])
-        ntu.execute(None, calib_ws_name)
+        Scale(InputWorkspace=calib_ws_name, OutputWorkspace=calib_ws_name,
+              Factor=self._intensity_scale, Operation='Multiply')
 
         RenameWorkspace(InputWorkspace=calib_ws_name, OutputWorkspace=self._out_ws)
 
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectFlatPlateAbsorption.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectFlatPlateAbsorption.py
index 4651084b326a647d8b49c97c2de61c46865b40cb..3034d13f565467cdd277e285d1f12f913ef6e8ea 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectFlatPlateAbsorption.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectFlatPlateAbsorption.py
@@ -1,3 +1,4 @@
+#pylint: disable=no-init,too-many-instance-attributes,too-many-branches
 from mantid.simpleapi import *
 from mantid.api import DataProcessorAlgorithm, AlgorithmFactory, MatrixWorkspaceProperty, PropertyMode, Progress, WorkspaceGroupProperty
 from mantid.kernel import StringMandatoryValidator, Direction, logger, FloatBoundedValidator
@@ -139,14 +140,14 @@ class IndirectFlatPlateAbsorption(DataProcessorAlgorithm):
 
                 SetSampleMaterial(can_wave_ws, ChemicalFormula=self._can_chemical_formula, SampleNumberDensity=self._can_number_density)
                 FlatPlateAbsorption(InputWorkspace=can_wave_ws,
-                                OutputWorkspace=self._acc_ws,
-                                SampleHeight=self._sample_height,
-                                SampleWidth=self._sample_width,
-                                SampleThickness=self._can_front_thickness + self._can_back_thickness,
-                                ElementSize=self._element_size,
-                                EMode='Indirect',
-                                EFixed=efixed,
-                                NumberOfWavelengthPoints=10)
+                                    OutputWorkspace=self._acc_ws,
+                                    SampleHeight=self._sample_height,
+                                    SampleWidth=self._sample_width,
+                                    SampleThickness=self._can_front_thickness + self._can_back_thickness,
+                                    ElementSize=self._element_size,
+                                    EMode='Indirect',
+                                    EFixed=efixed,
+                                    NumberOfWavelengthPoints=10)
 
                 Divide(LHSWorkspace=can_wave_ws, RHSWorkspace=self._acc_ws, OutputWorkspace=can_wave_ws)
                 Minus(LHSWorkspace=sample_wave_ws, RHSWorkspace=can_wave_ws, OutputWorkspace=sample_wave_ws)
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py
index 1e3ccff2bcb72750d5385da98525dce03f355f14..4e44f558bbffd3a82cbdae85be954ca21d09d833 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py
@@ -22,62 +22,59 @@ class IndirectResolution(DataProcessorAlgorithm):
     def category(self):
         return 'Workflow\\Inelastic;PythonAlgorithms;Inelastic'
 
+
     def summary(self):
-        return 'Creates a resolution workspace'
+        return 'Creates a resolution workspace for an indirect inelastic instrument.'
+
 
     def PyInit(self):
         self.declareProperty(StringArrayProperty(name='InputFiles'),
                              doc='Comma seperated list if input files')
 
-        self.declareProperty(WorkspaceProperty('OutputWorkspace', '',\
-                             optional=PropertyMode.Optional,\
-                             direction=Direction.Output),
-                             doc='Output resolution workspace (if left blank a name will '
-                                 'be gernerated automatically)')
-
         self.declareProperty(name='Instrument', defaultValue='',
                              validator=StringListValidator(['IRIS', 'OSIRIS', 'TOSCA']),
-                             doc='Instrument used during run')
+                             doc='Instrument used during run.')
         self.declareProperty(name='Analyser', defaultValue='',
                              validator=StringListValidator(['graphite', 'mica', 'fmica']),
-                             doc='Analyser used during run')
+                             doc='Analyser used during run.')
         self.declareProperty(name='Reflection', defaultValue='',
                              validator=StringListValidator(['002', '004', '006']),
-                             doc='Reflection used during run')
+                             doc='Reflection used during run.')
 
         self.declareProperty(IntArrayProperty(name='DetectorRange', values=[0, 1]),
-                             doc='Range of detetcors to use in resolution calculation')
+                             doc='Range of detetcors to use in resolution calculation.')
         self.declareProperty(FloatArrayProperty(name='BackgroundRange', values=[0.0, 0.0]),
-                             doc='Energy range to use as background')
+                             doc='Energy range to use as background.')
+
 
         self.declareProperty(name='RebinParam', defaultValue='',
                              doc='Rebinning parameters (min,width,max)')
         self.declareProperty(name='ScaleFactor', defaultValue=1.0,
                              doc='Factor to scale resolution curve by')
 
+
         self.declareProperty(name='Plot', defaultValue=False, doc='Plot resolution curve')
         self.declareProperty(name='Save', defaultValue=False,
                              doc='Save resolution workspace as a Nexus file')
 
+        self.declareProperty(WorkspaceProperty('OutputWorkspace', '',
+                             direction=Direction.Output),
+                             doc='Output resolution workspace.')
 
     def PyExec(self):
         from IndirectCommon import getWSprefix
-
         self._setup()
 
-        InelasticIndirectReduction(Instrument=self._instrument,
+        ISISIndirectEnergyTransfer(Instrument=self._instrument,
                                    Analyser=self._analyser,
                                    Reflection=self._reflection,
-                                   Grouping='All',
+                                   GroupingMethod='All',
                                    SumFiles=True,
                                    InputFiles=self._input_files,
-                                   DetectorRange=self._detector_range,
-                                   OutputWorkspace='__icon_ws_group')
-
-        icon_ws = mtd['__icon_ws_group'].getItem(0).getName()
+                                   SpectraRange=self._detector_range,
+                                   OutputWorkspace='__et_ws_group')
 
-        if self._out_ws == "":
-            self._out_ws = getWSprefix(icon_ws) + 'res'
+        icon_ws = mtd['__et_ws_group'].getItem(0).getName()
 
         if self._scale_factor != 1.0:
             Scale(InputWorkspace=icon_ws, OutputWorkspace=icon_ws, Factor=self._scale_factor)
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/InelasticIndirectReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/InelasticIndirectReduction.py
deleted file mode 100644
index 39070394a695e4f5815bd9135966038d838d16d4..0000000000000000000000000000000000000000
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/InelasticIndirectReduction.py
+++ /dev/null
@@ -1,246 +0,0 @@
-#pylint: disable=no-init
-from mantid.kernel import *
-from mantid.api import *
-from mantid.simpleapi import *
-
-
-class InelasticIndirectReduction(DataProcessorAlgorithm):
-
-    _out_ws_group = None
-    _data_files = None
-    _instrument = None
-    _analyser = None
-    _reflection = None
-    _param_file = None
-    _detector_range = None
-    _background_range = None
-    _calib_ws_name = None
-    _detailed_balance = None
-    _rebin_string = None
-    _scale_factor = None
-    _sum_files = None
-    _map_file = None
-    _save_formats = None
-    _plot_type = None
-    _use_calib_ws = None
-    _use_detailed_balance = None
-    _use_scale_factor = None
-    _plot_ws = None
-
-    def category(self):
-        return 'Workflow\\Inelastic;PythonAlgorithms;Inelastic'
-
-
-    def summary(self):
-        return 'Runs a reduction for an inelastic indirect geometry instrument.'
-
-
-    def PyInit(self):
-        self.declareProperty(StringArrayProperty(name='InputFiles'),
-                             doc='Comma separated list of input files')
-
-        self.declareProperty(WorkspaceGroupProperty('OutputWorkspace', '',\
-                             direction=Direction.Output),
-                             doc='Workspace group for the resulting workspaces')
-
-        self.declareProperty(name='SumFiles', defaultValue=False, doc='Toggle input file summing or sequential processing')
-        self.declareProperty(name='LoadLogs', defaultValue=False, doc='Load sample logs from input files')
-
-        self.declareProperty(name='Instrument', defaultValue='', doc='Instrument used during run',
-                             validator=StringListValidator(['IRIS', 'OSIRIS', 'TOSCA', 'TFXA', 'BASIS', 'VISION']))
-        self.declareProperty(name='Analyser', defaultValue='', doc='Analyser used during run',
-                             validator=StringListValidator(['graphite', 'mica', 'fmica', 'silicon']))
-        self.declareProperty(name='Reflection', defaultValue='', doc='Reflection used during run',
-                             validator=StringListValidator(['002', '004', '006', '111']))
-
-        self.declareProperty(WorkspaceProperty('CalibrationWorkspace', '',\
-                             direction=Direction.Input, optional=PropertyMode.Optional), doc='Workspace contining calibration data')
-
-        self.declareProperty(IntArrayProperty(name='DetectorRange', values=[0, 1],\
-                             validator=IntArrayMandatoryValidator()),
-                             doc='Comma separated range of detectors to use')
-        self.declareProperty(FloatArrayProperty(name='BackgroundRange'),
-                             doc='')
-
-        self.declareProperty(name='RebinString', defaultValue='', doc='Rebin string parameters')
-        self.declareProperty(name='DetailedBalance', defaultValue=-1.0, doc='')
-        self.declareProperty(name='ScaleFactor', defaultValue=1.0, doc='')
-        self.declareProperty(name='Grouping', defaultValue='',
-                             doc='Method used to group spectra, can be either: Individual, All, a .map filename or a group workspace name')
-        self.declareProperty(name='Fold', defaultValue=False, doc='')
-        self.declareProperty(name='SaveCM1', defaultValue=False, doc='')
-        self.declareProperty(StringArrayProperty(name='SaveFormats'), doc='Comma separated list of save formats')
-
-        self.declareProperty(name='Plot', defaultValue='none', doc='Type of plot to output after reduction',
-                             validator=StringListValidator(['none', 'spectra', 'contour']))
-
-
-    def PyExec(self):
-        from mantid import config, logger
-        import inelastic_indirect_reducer
-
-        self._setup()
-
-        # Setup reducer
-        reducer = inelastic_indirect_reducer.IndirectReducer()
-
-        reducer.set_rename(True)
-
-        reducer.set_instrument_name(self._instrument)
-        reducer.set_parameter_file(self._param_file)
-        try:
-            reducer.set_output_path(config["defaultsave.directory"])
-        except RuntimeError:
-            pass # Use default
-
-        for data_file in self._data_files:
-            reducer.append_data_file(data_file)
-
-        reducer.set_sum_files(self._sum_files)
-
-        reducer.set_detector_range(int(self._detector_range[0]) - 1, int(self._detector_range[1]) - 1)
-
-        self._use_calib_ws = self._calib_ws_name != ''
-        if self._use_calib_ws:
-            logger.information('Using calibration workspace: %s' % self._calib_ws_name)
-            reducer.set_calibration_workspace(self._calib_ws_name)
-
-        if len(self._background_range) == 2:
-            logger.debug('Using background range: ' + str(self._background_range))
-            reducer.set_background(float(self._background_range[0]), float(self._background_range[1]))
-
-        # TODO: There should be a better way to do this
-        self._use_detailed_balance = self._detailed_balance != -1.0
-        if self._use_detailed_balance:
-            logger.debug('Using detailed balance: ' + str(self._detailed_balance))
-            reducer.set_detailed_balance(self._detailed_balance)
-
-        if self._rebin_string != '':
-            logger.debug('Using rebin string: ' + self._rebin_string)
-            reducer.set_rebin_string(self._rebin_string)
-
-        self._use_scale_factor = self._scale_factor != 1.0
-        if self._use_scale_factor:
-            logger.debug('Using scale factor: ' + str(self._scale_factor))
-            reducer.set_scale_factor(self._scale_factor)
-
-        if self._map_file != '':
-            logger.debug('Using mapping file: ' + str(self._map_file))
-            reducer.set_grouping_policy(self._map_file)
-
-        reducer.set_fold_multiple_frames(self.getProperty('Fold').value)
-        reducer.set_save_to_cm_1(self.getProperty('SaveCM1').value)
-        reducer.set_save_formats(self._save_formats)
-
-        # Do reduction and get result workspaces
-        reducer.reduce()
-        ws_list = reducer.get_result_workspaces()
-
-        self._plot_ws = ws_list[0]
-
-        if len(ws_list) < 1:
-            logger.error('Failed to complete reduction')
-            return
-
-        # Add sample logs to output workspace(s)
-        for workspace in ws_list:
-            self._add_ws_logs(workspace)
-
-        # Group output workspaces
-        GroupWorkspaces(InputWorkspaces=ws_list, OutputWorkspace=self._out_ws_group)
-        self.setProperty('OutputWorkspace', self._out_ws_group)
-
-        # Do plotting
-        if self._plot_type != 'none':
-            self._plot()
-
-
-    def validateInputs(self):
-        """
-        Validates algorithm properties.
-        """
-        issues = dict()
-
-        # Validate save format string
-        save_formats = self.getProperty('SaveFormats').value
-        valid_formats = ['nxs', 'spe', 'nxspe', 'ascii', 'aclimax', 'davegrp']
-        invalid_formats = list()
-        for save_format in save_formats:
-            if save_format not in valid_formats:
-                invalid_formats.append(save_format)
-        if len(invalid_formats) > 0:
-            issues['SaveFormats'] = 'The following save formats are not valid: ' + ','.join(invalid_formats)
-
-        return issues
-
-
-    def _setup(self):
-        """
-        Gets and algorithm properties.
-        """
-
-        # Get parameter values
-        self._out_ws_group = self.getPropertyValue('OutputWorkspace')
-        self._data_files = self.getProperty('InputFiles').value
-
-        self._instrument = self.getPropertyValue('Instrument')
-        self._analyser = self.getPropertyValue('Analyser')
-        self._reflection = self.getPropertyValue('Reflection')
-
-        self._param_file = config['instrumentDefinition.directory'] + self._instrument + '_' + self._analyser + '_' + self._reflection + '_Parameters.xml'
-
-        self._detector_range = self.getProperty('DetectorRange').value
-        self._background_range = self.getProperty('BackgroundRange').value
-
-        self._calib_ws_name = self.getPropertyValue('CalibrationWorkspace')
-
-        self._detailed_balance = self.getProperty('DetailedBalance').value
-        self._rebin_string = self.getPropertyValue('RebinString')
-        self._scale_factor = self.getProperty('ScaleFactor').value
-        self._sum_files = self.getProperty('SumFiles').value
-
-        self._map_file = self.getPropertyValue('Grouping')
-
-        self._save_formats = self.getProperty('SaveFormats').value
-        self._plot_type = self.getPropertyValue('Plot')
-
-
-    def _add_ws_logs(self, workspace_name):
-        """
-        Adds sample logs to a given output workspace.
-        """
-
-        AddSampleLog(Workspace=workspace_name, LogName='use_calib_wokspace', LogType='String', LogText=str(self._use_calib_ws))
-        if self._use_calib_ws:
-            AddSampleLog(Workspace=workspace_name, LogName='calib_workspace_name', LogType='String', LogText=str(self._calib_ws_name))
-
-        AddSampleLog(Workspace=workspace_name, LogName='use_detailed_balance', LogType='String', LogText=str(self._use_detailed_balance))
-        if self._use_detailed_balance:
-            AddSampleLog(Workspace=workspace_name, LogName='detailed_balance', LogType='Number', LogText=str(self._detailed_balance))
-
-        AddSampleLog(Workspace=workspace_name, LogName='use_scale_factor', LogType='String', LogText=str(self._use_scale_factor))
-        if self._use_scale_factor:
-            AddSampleLog(Workspace=workspace_name, LogName='scale_factor', LogType='Number', LogText=str(self._scale_factor))
-
-
-    def _plot(self):
-        """
-        Plots results.
-        """
-
-        if self._plot_type == 'spectra':
-            from mantidplot import plotSpectrum
-            num_spectra = mtd[self._plot_ws].getNumberHistograms()
-            try:
-                plotSpectrum(self._plot_ws, range(0, num_spectra))
-            except RuntimeError:
-                logger.notice('Spectrum plotting canceled by user')
-
-        if self._plot_type == 'contour':
-            from mantidplot import importMatrixWorkspace
-            plot_workspace = importMatrixWorkspace(self._plot_ws)
-            plot_workspace.plotGraph2D()
-
-
-# Register algorithm with Mantid
-AlgorithmFactory.subscribe(InelasticIndirectReduction)
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py
index af5b458c3459c8c4719eef3db62fb007eeedeeb4..2f674cd327d652c6ac3174dde6cfda3c87a59075 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py
@@ -121,8 +121,8 @@ def getIntersectionsOfRanges(rangeList):
     at the same point.  Also, all ranges should obey range[0] <= range[1].
     """
     # Sanity check.
-    for range in rangeList:
-        assert len(range) == 2, "Unable to find the intersection of a malformed range."
+    for myrange in rangeList:
+        assert len(myrange) == 2, "Unable to find the intersection of a malformed range."
 
     # Find all combinations of ranges, and see where they intersect.
     rangeCombos = list(itertools.combinations(rangeList, 2))
@@ -137,8 +137,8 @@ def getIntersectionsOfRanges(rangeList):
     return intersections
 
 def isInRanges(rangeList, n):
-    for range in rangeList:
-        if range[0] < n < range[1]:
+    for myrange in rangeList:
+        if myrange[0] < n < myrange[1]:
             return True
     return False
 
@@ -157,18 +157,21 @@ class OSIRISDiffractionReduction(PythonAlgorithm):
         return 'Diffraction;PythonAlgorithms'
 
     def summary(self):
-        return "This Python algorithm performs the operations necessary for the reduction of diffraction data from the Osiris instrument at ISIS \
-              into dSpacing, by correcting for the monitor and linking the various d-ranges together."
+        return "This Python algorithm performs the operations necessary for the reduction of diffraction data "+\
+                "from the Osiris instrument at ISIS "+\
+                "into dSpacing, by correcting for the monitor and linking the various d-ranges together."
 
     def PyInit(self):
-        runs_desc='The list of run numbers that are part of the sample run. \
-                   There should be five of these in most cases. Enter them as comma separated values.'
+        runs_desc='The list of run numbers that are part of the sample run. '+\
+                  'There should be five of these in most cases. Enter them as comma separated values.'
         self.declareProperty('Sample', '', doc=runs_desc)
         self.declareProperty('Vanadium', '', doc=runs_desc)
         self.declareProperty(FileProperty('CalFile', '', action=FileAction.Load),
-                             doc='Filename of the .cal file to use in the [[AlignDetectors]] and [[DiffractionFocussing]] child algorithms.')
+                             doc='Filename of the .cal file to use in the [[AlignDetectors]] and '+\
+                                 '[[DiffractionFocussing]] child algorithms.')
         self.declareProperty(MatrixWorkspaceProperty('OutputWorkspace', '', Direction.Output),
-                             doc="Name to give the output workspace. If no name is provided, one will be generated based on the run numbers.")
+                             doc="Name to give the output workspace. If no name is provided, "+\
+                                 "one will be generated based on the run numbers.")
 
         self._cal = None
         self._outputWsName = None
@@ -196,8 +199,8 @@ class OSIRISDiffractionReduction(PythonAlgorithm):
         self._vans = self.findRuns(self.getPropertyValue("Vanadium"))
 
         # Load all sample and vanadium files, and add the resulting workspaces to the DRangeToWsMaps.
-        for file in self._sams + self._vans:
-            Load(Filename=file, OutputWorkspace=file, SpectrumMin=3, SpectrumMax=962)
+        for fileName in self._sams + self._vans:
+            Load(Filename=fileName, OutputWorkspace=fileName, SpectrumMin=3, SpectrumMax=962)
         for sam in self._sams:
             self._samMap.addWs(sam)
         for van in self._vans:
@@ -255,13 +258,16 @@ class OSIRISDiffractionReduction(PythonAlgorithm):
         intersections = getIntersectionsOfRanges(self._samMap.getMap().keys())
 
         dataX = result.dataX(0)
-        dataY = []; dataE = []
+        dataY = []
+        dataE = []
         for i in range(0, len(dataX)-1):
             x = ( dataX[i] + dataX[i+1] ) / 2.0
             if isInRanges(intersections, x):
-                dataY.append(2); dataE.append(2)
+                dataY.append(2)
+                dataE.append(2)
             else:
-                dataY.append(1); dataE.append(1)
+                dataY.append(1)
+                dataE.append(1)
 
         # apply scalar data to result workspace
         for i in range(0, result.getNumberHistograms()):
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/PoldiDataAnalysis.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/PoldiDataAnalysis.py
new file mode 100644
index 0000000000000000000000000000000000000000..23ab9ab8221a60f7b8620715a6cee25dc76fb7a4
--- /dev/null
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/PoldiDataAnalysis.py
@@ -0,0 +1,230 @@
+# pylint: disable=no-init,invalid-name,attribute-defined-outside-init
+from mantid.simpleapi import *
+from mantid.api import *
+from mantid.kernel import *
+
+class PoldiDataAnalysis(PythonAlgorithm):
+    """
+    This workflow algorithm uses all of the POLDI specific algorithms to perform a complete data analysis,
+    starting from the correlation method and preliminary 1D-fits, proceeding with either one or two passses
+    of 2D-fitting.
+
+    All resulting workspaces are grouped together at the end so that they are all in one place.
+    """
+
+    def category(self):
+        return "SINQ\\Poldi"
+
+    def name(self):
+        return "PoldiDataAnalysis"
+
+    def summary(self):
+        return "Run all necessary steps for a complete analysis of POLDI data."
+
+    def checkGroups(self):
+        return False
+
+    def PyInit(self):
+        self.declareProperty(WorkspaceProperty(name="InputWorkspace", defaultValue="", direction=Direction.Input),
+                             doc='MatrixWorkspace with 2D POLDI data and valid POLDI instrument.')
+
+        self.declareProperty("MaximumPeakNumber", 10, direction=Direction.Input,
+                             doc='Maximum number of peaks to process in the analysis.')
+
+        self.declareProperty("MinimumPeakSeparation", 10, direction=Direction.Input,
+                             doc='Minimum number of points between neighboring peaks.')
+
+        self.declareProperty(WorkspaceProperty("ExpectedPeaks", defaultValue="", direction=Direction.Input),
+                             doc='TableWorkspace or WorkspaceGroup with expected peaks used for indexing.')
+
+        allowedProfileFunctions = StringListValidator(["Gaussian", "Lorentzian", "PseudoVoigt", "Voigt"])
+        self.declareProperty("ProfileFunction", "Gaussian", validator=allowedProfileFunctions,
+                             direction=Direction.Input)
+
+        self.declareProperty("PawleyFit", False, direction=Direction.Input,
+                             doc='Should the 2D-fit determine lattice parameters?')
+
+        self.declareProperty("MultipleRuns", False, direction=Direction.Input,
+                             doc=('If this is activated, peaks are searched again in the'
+                                  'residuals and the 1D- and 2D-fit is repeated '
+                                  'with these data.'))
+
+        self.declareProperty("PlotResult", True, direction=Direction.Input,
+                             doc=('If this is activated, plot the sum of residuals and calculated spectrum together '
+                                  'with the theoretical spectrum and the residuals.'))
+
+        self.declareProperty(WorkspaceProperty(name="OutputWorkspace", defaultValue="", direction=Direction.Output),
+                             doc='WorkspaceGroup with result data from all processing steps.')
+
+    def PyExec(self):
+        self.outputWorkspaces = []
+
+        self.baseName = self.getProperty("InputWorkspace").valueAsStr
+        self.inputWorkspace = self.getProperty("InputWorkspace").value
+        self.expectedPeaks = self.getProperty("ExpectedPeaks").value
+        self.profileFunction = self.getProperty("ProfileFunction").value
+
+        correlationSpectrum = self.runCorrelation()
+        self.outputWorkspaces.append(correlationSpectrum)
+
+        self.numberOfExecutions = 0
+        self.outputWorkspaces += self.runMainAnalysis(correlationSpectrum)
+
+        outputWs = GroupWorkspaces(self.outputWorkspaces[0])
+
+        for ws in self.outputWorkspaces[1:]:
+            outputWs.add(ws.getName())
+
+        RenameWorkspace(outputWs, self.getProperty("OutputWorkspace").valueAsStr)
+
+        self.setProperty("OutputWorkspace", outputWs)
+
+    def runCorrelation(self):
+        correlationName = self.baseName + "_correlation"
+        PoldiAutoCorrelation(self.inputWorkspace, OutputWorkspace=correlationName)
+
+        return AnalysisDataService.retrieve(correlationName)
+
+    def runMainAnalysis(self, correlationSpectrum):
+        self.numberOfExecutions += 1
+        outputWorkspaces = []
+
+        rawPeaks = self.runPeakSearch(correlationSpectrum)
+        outputWorkspaces.append(rawPeaks)
+
+        refinedPeaks, fitPlots = self.runPeakFit1D(correlationSpectrum, rawPeaks)
+        outputWorkspaces.append(refinedPeaks)
+        outputWorkspaces.append(fitPlots)
+
+        indexedPeaks, unindexedPeaks = self.runIndex(refinedPeaks)
+        outputWorkspaces.append(indexedPeaks)
+
+        pawleyFit = self.getProperty('PawleyFit').value
+        if pawleyFit:
+            outputWorkspaces.append(unindexedPeaks)
+
+        fitPeaks2DResult = self.runPeakFit2D(indexedPeaks)
+        outputWorkspaces += fitPeaks2DResult
+
+        spectrum2D = fitPeaks2DResult[0]
+        spectrum1D = fitPeaks2DResult[1]
+
+        residuals = self.runResidualAnalysis(spectrum2D)
+        outputWorkspaces.append(residuals)
+
+        totalName = self.baseName + "_sum"
+        Plus(LHSWorkspace=spectrum1D, RHSWorkspace=residuals, OutputWorkspace=totalName)
+        total = AnalysisDataService.retrieve(totalName)
+        outputWorkspaces.append(total)
+
+        if self.numberOfExecutions == 1:
+            self._plotResult(total, spectrum1D, residuals)
+
+        runTwice = self.getProperty('MultipleRuns').value
+        if runTwice and self.numberOfExecutions == 1:
+            return self.runMainAnalysis(total)
+        else:
+            return outputWorkspaces
+
+    def runPeakSearch(self, correlationWorkspace):
+        peaksName = self.baseName + "_peaks_raw"
+
+        PoldiPeakSearch(InputWorkspace=correlationWorkspace,
+                        MaximumPeakNumber=self.getProperty('MaximumPeakNumber').value,
+                        MinimumPeakSeparation=self.getProperty('MinimumPeakSeparation').value,
+                        OutputWorkspace=peaksName)
+
+        return AnalysisDataService.retrieve(peaksName)
+
+    def runPeakFit1D(self, correlationWorkspace, rawPeaks):
+        refinedPeaksName = self.baseName + "_peaks_refined_1d"
+        plotNames = self.baseName + "_fit_plots"
+
+        PoldiFitPeaks1D(InputWorkspace=correlationWorkspace,
+                        PoldiPeakTable=rawPeaks,
+                        PeakFunction=self.profileFunction,
+                        OutputWorkspace=refinedPeaksName,
+                        FitPlotsWorkspace=plotNames)
+
+        return AnalysisDataService.retrieve(refinedPeaksName), AnalysisDataService.retrieve(plotNames)
+
+
+    def runIndex(self, peaks):
+        indexedPeaksName = self.baseName + "_indexed"
+
+        PoldiIndexKnownCompounds(InputWorkspace=peaks,
+                                 CompoundWorkspaces=self.expectedPeaks,
+                                 OutputWorkspace=indexedPeaksName)
+
+        indexedPeaks = AnalysisDataService.retrieve(indexedPeaksName)
+
+        # Remove unindexed peaks from group for pawley fit
+        unindexedPeaks = indexedPeaks.getItem(indexedPeaks.getNumberOfEntries() - 1)
+        pawleyFit = self.getProperty('PawleyFit').value
+        if pawleyFit:
+            indexedPeaks.remove(unindexedPeaks.getName())
+
+        self._removeEmptyTablesFromGroup(indexedPeaks)
+
+        return indexedPeaks, unindexedPeaks
+
+    def runPeakFit2D(self, peaks):
+        spectrum2DName = self.baseName + "_fit2d"
+        spectrum1DName = self.baseName + "_fit1d"
+        refinedPeaksName = self.baseName + "_peaks_refined_2d"
+        refinedCellName = self.baseName + "_cell_refined"
+
+        pawleyFit = self.getProperty('PawleyFit').value
+
+        PoldiFitPeaks2D(InputWorkspace=self.inputWorkspace,
+                        PoldiPeakWorkspace=peaks,
+                        PeakProfileFunction=self.profileFunction,
+                        PawleyFit=pawleyFit,
+                        MaximumIterations=100,
+                        OutputWorkspace=spectrum2DName,
+                        Calculated1DSpectrum=spectrum1DName,
+                        RefinedPoldiPeakWorkspace=refinedPeaksName,
+                        RefinedCellParameters=refinedCellName)
+
+        workspaces = [AnalysisDataService.retrieve(spectrum2DName),
+                      AnalysisDataService.retrieve(spectrum1DName),
+                      AnalysisDataService.retrieve(refinedPeaksName)]
+        if AnalysisDataService.doesExist(refinedCellName):
+            workspaces.append(AnalysisDataService.retrieve(refinedCellName))
+
+        return workspaces
+
+    def runResidualAnalysis(self, calculated2DSpectrum):
+        residualName = self.baseName + "_residuals"
+
+        PoldiAnalyseResiduals(MeasuredCountData=self.inputWorkspace,
+                              FittedCountData=calculated2DSpectrum,
+                              MaxIterations=5,
+                              OutputWorkspace=residualName)
+
+        return AnalysisDataService.retrieve(residualName)
+
+    def _removeEmptyTablesFromGroup(self, groupWorkspace):
+        deleteNames = []
+        for i in range(groupWorkspace.getNumberOfEntries()):
+            ws = groupWorkspace.getItem(i)
+            if ws.rowCount() == 0:
+                deleteNames.append(ws.getName())
+        for name in deleteNames:
+            DeleteWorkspace(name)
+
+    def _plotResult(self, total, spectrum1D, residuals):
+        plotResults = self.getProperty('PlotResult').value
+
+        if plotResults:
+            from IndirectImport import import_mantidplot
+            plot = import_mantidplot()
+
+            plotWindow = plot.plotSpectrum(total, 0, type=1)
+            plotWindow = plot.plotSpectrum(spectrum1D, 0, type=0, window=plotWindow)
+            plotWindow = plot.plotSpectrum(residuals, 0, type=0, window=plotWindow)
+            plotWindow.activeLayer().setTitle('Fit result for ' + self.baseName)
+            plotWindow.activeLayer().removeLegend()
+
+
+AlgorithmFactory.subscribe(PoldiDataAnalysis())
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/QLines.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/QLines.py
index 0d8c34b1def5f952f361ddbc07af8c30def559c7..d7c02fa003d9e27f00f4bccf2dff930c69befb2d 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/QLines.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/QLines.py
@@ -14,18 +14,25 @@ class QLines(PythonAlgorithm):
         return "The program estimates the quasielastic components of each of the groups of spectra and requires the resolution file (.RES file) and optionally the normalisation file created by ResNorm."
 
     def PyInit(self):
-        self.declareProperty(name='InputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of data input - File (.nxs) or Workspace')
-        self.declareProperty(name='Instrument',defaultValue='iris',validator=StringListValidator(['irs','iris','osi','osiris']), doc='Instrument')
-        self.declareProperty(name='Analyser',defaultValue='graphite002',validator=StringListValidator(['graphite002','graphite004']), doc='Analyser & reflection')
+        self.declareProperty(name='InputType',defaultValue='File',validator=StringListValidator(['File','Workspace']),
+                             doc='Origin of data input - File (.nxs) or Workspace')
+        self.declareProperty(name='Instrument',defaultValue='iris',validator=StringListValidator(['irs','iris','osi','osiris']),
+                             doc='Instrument')
+        self.declareProperty(name='Analyser',defaultValue='graphite002',validator=StringListValidator(['graphite002','graphite004']),
+                             doc='Analyser & reflection')
         self.declareProperty(name='Program',defaultValue='QL',validator=StringListValidator(['QL','QSe']), doc='Name of program to run')
         self.declareProperty(name='SamNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample run number')
-        self.declareProperty(name='ResInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of res input - File (_res.nxs) or Workspace')
-        self.declareProperty(name='ResType',defaultValue='Res',validator=StringListValidator(['Res','Data']), doc='Format of Resolution file')
+        self.declareProperty(name='ResInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']),
+                             doc='Origin of res input - File (_res.nxs) or Workspace')
+        self.declareProperty(name='ResType',defaultValue='Res',validator=StringListValidator(['Res','Data']),
+                             doc='Format of Resolution file')
         self.declareProperty(name='ResNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Resolution run number')
         self.declareProperty(name='ResNorm',defaultValue=False, doc='Use ResNorm output file')
-        self.declareProperty(name='ResNormInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of ResNorm input - File (_red.nxs) or Workspace')
+        self.declareProperty(name='ResNormInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']),
+                             doc='Origin of ResNorm input - File (_red.nxs) or Workspace')
         self.declareProperty(name='ResNormNumber',defaultValue='', doc='ResNorm run number')
-        self.declareProperty(name='BackgroundOption',defaultValue='Sloping',validator=StringListValidator(['Sloping','Flat','Zero']), doc='Form of background to fit')
+        self.declareProperty(name='BackgroundOption',defaultValue='Sloping',validator=StringListValidator(['Sloping','Flat','Zero']),
+                             doc='Form of background to fit')
         self.declareProperty(name='ElasticOption',defaultValue=True, doc='Include elastic peak in fit')
         self.declareProperty(name='FixWidth',defaultValue=False, doc='Fix one of the widths')
         self.declareProperty(name='WidthFile', defaultValue='', doc='Name of file containing fixed width values')
@@ -34,10 +41,12 @@ class QLines(PythonAlgorithm):
         self.declareProperty(name='SamBinning', defaultValue=1, doc='Binning value (integer) for sample. Default=1')
         self.declareProperty(name='ResBinning', defaultValue=1, doc='Binning value (integer) for resolution - QLd only. Default=1')
         self.declareProperty(name='Sequence',defaultValue=True, doc='Switch Sequence Off/On')
-        self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','ProbBeta','Intensity','FwHm','Fit','All']), doc='Plot options')
+        self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','ProbBeta','Intensity','FwHm','Fit','All']),
+                             doc='Plot options')
         self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On')
         self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On')
 
+    #pylint: disable=too-many-locals
     def PyExec(self):
         from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform
 
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReactorSANSResolution.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReactorSANSResolution.py
index 2ba70394d509ab67ac7739067a6a03a85960e6cd..2f61d9affc97e83beec7f32990fdea31cba5fd50 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReactorSANSResolution.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReactorSANSResolution.py
@@ -65,7 +65,8 @@ class ReactorSANSResolution(PythonAlgorithm):
             and source_sample_distance is not None and sample_detector_distance is not None:
             k = 2.0*math.pi/wvl
             res_factor = math.pow(k*source_apert_radius/source_sample_distance, 2)
-            res_factor += (math.pow(k*sample_apert_radius*(source_sample_distance+sample_detector_distance)/(source_sample_distance*sample_detector_distance), 2)/4.0)
+            res_factor += (math.pow(k*sample_apert_radius*(source_sample_distance+sample_detector_distance)/
+                                    (source_sample_distance*sample_detector_distance), 2)/4.0)
             res_factor += math.pow(k*pixel_size_x/sample_detector_distance, 2)/12.0
 
             for i in range(len(input_ws.readX(0))):
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAzimuthalAverage1D.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAzimuthalAverage1D.py
index 88d7baf2b75ea81986419404c4b15584de63933e..b7963e100f1f0cf5e4061b66e318d824697f7613 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAzimuthalAverage1D.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAzimuthalAverage1D.py
@@ -1,4 +1,4 @@
-#pylint: disable=no-init,invalid-name
+#pylint: disable=no-init,invalid-name,too-many-locals,too-many-branches
 from mantid.api import *
 from mantid.kernel import *
 import math
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SavePlot1D.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SavePlot1D.py
index d2fdfd570aa743859e2a90f444975579143a12a0..f27c92fd462c9b590db148f13ce4117f56e392f8 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SavePlot1D.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SavePlot1D.py
@@ -37,7 +37,7 @@ class SavePlot1D(mantid.api.PythonAlgorithm):
             from distutils.version import LooseVersion
             if LooseVersion(matplotlib.__version__)<LooseVersion("1.2.0"):
                 ok2run='Wrong version of matplotlib. Required >= 1.2.0'
-        except:
+        except ImportError:
             ok2run='Problem importing matplotlib'
         if ok2run!='':
             raise RuntimeError(ok2run)
@@ -46,7 +46,7 @@ class SavePlot1D(mantid.api.PythonAlgorithm):
         import matplotlib.pyplot as plt
         self._wksp = self.getProperty("InputWorkspace").value
         plt.figure()
-        if type(self._wksp)==mantid.api._api.WorkspaceGroup:
+        if type(self._wksp)==mantid.api.WorkspaceGroup:
             for i in range(self._wksp.getNumberOfEntries()):
                 plt.subplot(self._wksp.getNumberOfEntries(),1,i+1)
                 self.DoPlot(self._wksp.getItem(i))
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransformToIqt.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransformToIqt.py
index d8ec5def96a9334a6c2330ae2ed9e83556a85ee0..125a598495d33f64476f15a5df451bb92348000b 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransformToIqt.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransformToIqt.py
@@ -1,4 +1,4 @@
-#pylint: disable=no-init
+#pylint: disable=no-init,too-many-instance-attributes
 from mantid.simpleapi import *
 from mantid.api import PythonAlgorithm, AlgorithmFactory, MatrixWorkspaceProperty, PropertyMode
 from mantid.kernel import Direction, logger
@@ -162,8 +162,7 @@ class TransformToIqt(PythonAlgorithm):
 
         except (AttributeError, IndexError):
             resolution = 0.0175
-            logger.warning('Could not get resolution from IPF, using default value: %f' % (
-                            resolution))
+            logger.warning('Could not get resolution from IPF, using default value: %f' % (resolution))
 
         resolution_bins = int(round((2 * resolution) / self._e_width))
 
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/dnsdata.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/dnsdata.py
index 6ecc991aefa652c136c4c011281249c80a09ae31..347425c13bfc40292eed0bc7007a3cde9f8bc981 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/dnsdata.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/dnsdata.py
@@ -1,7 +1,8 @@
+#pylint: disable=invalid-name,too-many-instance-attributes,too-few-public-methods,anomalous-backslash-in-string
 import sys, re
 import datetime
 
-class DNSdata:
+class DNSdata(object):
     """
     class which describes the DNS data structure
     will be used for data read-in and write-out routines
@@ -195,7 +196,7 @@ class DNSdata:
             except ValueError:
                 # if start and end time are not given, let them empty
                 pass
-                
+
 
 def parse_header(h):
     """
diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/CMakeLists.txt b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/CMakeLists.txt
index 77b67b9edc8f9142c083ae3d3004f4ffe577537f..75f3cedd49aeeec003a368e1a0cde62debaa9677 100644
--- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/CMakeLists.txt
+++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/CMakeLists.txt
@@ -10,6 +10,7 @@ set ( TEST_PY_FILES
   ConjoinSpectraTest.py
   CorrectLogTimesTest.py
   CreateLeBailFitInputTest.py
+  CreateMDTest.py
   IndirectCalibrationTest.py
   CreateWorkspaceTest.py
   CylinderPaalmanPingsCorrectionTest.py
@@ -24,9 +25,9 @@ set ( TEST_PY_FILES
   IndirectCylinderAbsorptionTest.py
   IndirectFlatPlateAbsorptionTest.py
   IndirectILLReductionTest.py
-  InelasticIndirectReductionTest.py
   IndirectTransmissionTest.py
   IndirectTransmissionMonitorTest.py
+  ISISIndirectEnergyTransferTest.py
   LoadDNSLegacyTest.py
   LoadFullprofFileTest.py
   LoadLiveDataTest.py
diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/CreateMDTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/CreateMDTest.py
index 956a403cbc20c915352c84b3f13c5a85af40a59e..951370b1b28ffe6329734b745a8f29a4afd953e1 100644
--- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/CreateMDTest.py
+++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/CreateMDTest.py
@@ -15,7 +15,7 @@ class CreateMDTest(unittest.TestCase):
         alg = AlgorithmManager.create("CreateMD")
         alg.setRethrows(True)
         alg.initialize()
-        self.assertRaises(ValueError, alg.setProperty, "InputWorkspaces", [])
+        self.assertRaises(ValueError, alg.setProperty, "DataSources", [])
 
     def test_set_up_madatory(self):
 
@@ -23,7 +23,7 @@ class CreateMDTest(unittest.TestCase):
         alg.setRethrows(True)
         alg.initialize()
         alg.setPropertyValue("OutputWorkspace", "mdworkspace")
-        alg.setProperty("InputWorkspaces", ['a', 'b'])
+        alg.setProperty("DataSources", ['a', 'b'])
         alg.setProperty("Emode", "Direct")
         alg.setProperty("Alatt", [1,1,1])
         alg.setProperty("Angdeg", [90,90,90])
@@ -33,16 +33,16 @@ class CreateMDTest(unittest.TestCase):
     def test_psi_right_size(self):
     
         input_workspace = CreateSampleWorkspace(NumBanks=1, BinWidth=2000)
-        AddSampleLog(input_workspace, LogName='Ei', LogText='12.0', LogType='Number')
         
         alg = AlgorithmManager.create("CreateMD")
         alg.setRethrows(True)
         alg.initialize()
         alg.setPropertyValue("OutputWorkspace", "mdworkspace")
-        alg.setProperty("InputWorkspaces", ['input_workspace'])
+        alg.setProperty("DataSources", ['input_workspace'])
         alg.setProperty("Emode", "Direct")
         alg.setProperty("Alatt", [1,1,1])
         alg.setProperty("Angdeg", [90,90,90])
+        alg.setProperty("Efix", 12.0)
         alg.setProperty("u", [0,0,1])
         alg.setProperty("v", [1,0,0])
         alg.setProperty("Psi", [0, 0, 0]) # Too large
@@ -54,16 +54,16 @@ class CreateMDTest(unittest.TestCase):
     def test_gl_right_size(self):
     
         input_workspace = CreateSampleWorkspace(NumBanks=1, BinWidth=2000)
-        AddSampleLog(input_workspace, LogName='Ei', LogText='12.0', LogType='Number')
         
         alg = AlgorithmManager.create("CreateMD")
         alg.setRethrows(True)
         alg.initialize()
         alg.setPropertyValue("OutputWorkspace", "mdworkspace")
-        alg.setProperty("InputWorkspaces", ['input_workspace'])
+        alg.setProperty("DataSources", ['input_workspace'])
         alg.setProperty("Emode", "Direct")
         alg.setProperty("Alatt", [1,1,1])
         alg.setProperty("Angdeg", [90,90,90])
+        alg.setProperty("Efix", 12.0)
         alg.setProperty("u", [0,0,1])
         alg.setProperty("v", [1,0,0])
         alg.setProperty("Psi", [0]) # Right size
@@ -75,16 +75,16 @@ class CreateMDTest(unittest.TestCase):
     def test_gs_right_size(self):
     
         input_workspace = CreateSampleWorkspace(NumBanks=1, BinWidth=2000)
-        AddSampleLog(input_workspace, LogName='Ei', LogText='12.0', LogType='Number')
         
         alg = AlgorithmManager.create("CreateMD")
         alg.setRethrows(True)
         alg.initialize()
         alg.setPropertyValue("OutputWorkspace", "mdworkspace")
-        alg.setProperty("InputWorkspaces", ['input_workspace'])
+        alg.setProperty("DataSources", ['input_workspace'])
         alg.setProperty("Emode", "Direct")
         alg.setProperty("Alatt", [1,1,1])
         alg.setProperty("Angdeg", [90,90,90])
+        alg.setProperty("Efix", 12.0)
         alg.setProperty("u", [0,0,1])
         alg.setProperty("v", [1,0,0])
         alg.setProperty("Psi", [0]) # Right size
@@ -97,15 +97,15 @@ class CreateMDTest(unittest.TestCase):
     def test_execute_single_workspace(self):
         
         input_workspace = CreateSampleWorkspace(NumBanks=1, BinWidth=2000)
-        AddSampleLog(input_workspace, LogName='Ei', LogText='12.0', LogType='Number')
-
+        
         alg = AlgorithmManager.create("CreateMD")
         alg.setRethrows(True)
         alg.initialize()
         alg.setPropertyValue("OutputWorkspace", "mdworkspace")
-        alg.setProperty("InputWorkspaces", ['input_workspace'])
+        alg.setProperty("DataSources", ['input_workspace'])
         alg.setProperty("Alatt", [1,1,1])
         alg.setProperty("Angdeg", [90,90,90])
+        alg.setProperty("Efix", 12.0)
         alg.setProperty("u", [0,0,1])
         alg.setProperty("v", [1,0,0])
         alg.execute()
@@ -114,6 +114,24 @@ class CreateMDTest(unittest.TestCase):
         self.assertTrue(isinstance(out_ws, IMDEventWorkspace), "Expected an MDEventWorkspace back")
         DeleteWorkspace(input_workspace)
 
+    def test_execute_multi_file(self):
+        alg = AlgorithmManager.create("CreateMD")
+        alg.setRethrows(True)
+        alg.initialize()
+        alg.setPropertyValue("OutputWorkspace", "mdworkspace")
+        alg.setProperty("DataSources", ['CNCS_7860_event.nxs', 'CNCS_7860_event.nxs'])
+        alg.setProperty("Alatt", [1,1,1])
+        alg.setProperty("Angdeg", [90,90,90])
+        alg.setProperty("EFix", [12.0, 13.0])
+        alg.setProperty("u", [0,0,1])
+        alg.setProperty("v", [1,0,0])
+        alg.execute()
+        out_ws = AnalysisDataService.retrieve("mdworkspace")
+
+        self.assertTrue(isinstance(out_ws, IMDEventWorkspace), "Expected an MDEventWorkspace back")
+        
+
+
 
 
 
diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/ISISIndirectEnergyTransferTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/ISISIndirectEnergyTransferTest.py
new file mode 100644
index 0000000000000000000000000000000000000000..04e4ef43c3a2a576e67062bcae5f426e4a1dbdbb
--- /dev/null
+++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/ISISIndirectEnergyTransferTest.py
@@ -0,0 +1,56 @@
+import unittest
+from mantid.simpleapi import *
+from mantid.api import *
+
+
+class ISISIndirectEnergyTransferTest(unittest.TestCase):
+
+    def test_basic_reduction_completes(self):
+        """
+        Sanity test to ensure the most basic reduction actually completes.
+        """
+
+        ws = ISISIndirectEnergyTransfer(InputFiles=['IRS26176.RAW'],
+                                        Instrument='IRIS',
+                                        Analyser='graphite',
+                                        Reflection='002',
+                                        SpectraRange=[3, 53])
+
+        self.assertTrue(isinstance(ws, WorkspaceGroup), 'Result workspace should be a workspace group.')
+        self.assertEqual(ws.getNames()[0], 'IRS26176_graphite002_red')
+
+
+    def test_instrument_validation_failure(self):
+        """
+        Tests that an invalid instrument configuration causes the validation to fail.
+        """
+
+        self.assertRaises(RuntimeError,
+                          ISISIndirectEnergyTransfer,
+                          OutputWorkspace='__ISISIndirectEnergyTransferTest_ws',
+                          InputFiles=['IRS26176.RAW'],
+                          Instrument='IRIS',
+                          Analyser='graphite',
+                          Reflection='006',
+                          SpectraRange=[3, 53])
+
+
+    def test_group_workspace_validation_failure(self):
+        """
+        Tests that validation fails when Workspace is selected as the GroupingMethod
+        but no workspace is provided.
+        """
+
+        self.assertRaises(RuntimeError,
+                          ISISIndirectEnergyTransfer,
+                          OutputWorkspace='__ISISIndirectEnergyTransferTest_ws',
+                          InputFiles=['IRS26176.RAW'],
+                          Instrument='IRIS',
+                          Analyser='graphite',
+                          Reflection='002',
+                          SpectraRange=[3, 53],
+                          GroupingMethod='Workspace')
+
+
+if __name__ == '__main__':
+    unittest.main()
diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/InelasticIndirectReductionTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/InelasticIndirectReductionTest.py
deleted file mode 100644
index ef51954f33eb75801cbdd116de8c1f1f37c8e997..0000000000000000000000000000000000000000
--- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/InelasticIndirectReductionTest.py
+++ /dev/null
@@ -1,21 +0,0 @@
-import unittest
-from mantid import mtd
-from mantid.simpleapi import InelasticIndirectReduction
-
-
-class InelasticIndirectReductionTest(unittest.TestCase):
-
-    def test_basic(self):
-        InelasticIndirectReduction(InputFiles='IRS26176.RAW',
-                                   OutputWorkspace='IndirectReductions',
-                                   Instrument='IRIS',
-                                   Analyser='graphite',
-                                   Reflection='002',
-                                   DetectorRange=[3, 53])
-
-        reduction_workspace = mtd['IndirectReductions'].getItem(0)
-        self.assertEquals(reduction_workspace.getName(), 'irs26176_graphite002_red')
-
-
-if __name__ == "__main__":
-    unittest.main()
diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/PoldiCreatePeaksFromFileTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/PoldiCreatePeaksFromFileTest.py
index 0e994d3f140e0746368a030d1676474d967ff8ac..4a5746eeb4c1973ace6e1004cff7c251271ce4d2 100644
--- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/PoldiCreatePeaksFromFileTest.py
+++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/PoldiCreatePeaksFromFileTest.py
@@ -63,10 +63,10 @@ class PoldiCreatePeaksFromFileTest(unittest.TestCase):
         self._cleanWorkspaces([ws, ws_expected])
 
     def test_FileTwoCompounds(self):
-        # It's the same structure and the same reflections, just the structure factors are different
+        # Using two imaginary structures to check that two compounds are parsed correctly as well
         fileHelper = TemporaryFileHelper("""SiliconCarbon {
-                                                Lattice: 5.43 5.43 5.43 90.0 90.0 90.0
-                                                Spacegroup: F d -3 m
+                                                Lattice: 5.43 5.43 5.43 90.0 90.0 120.0
+                                                Spacegroup: P 63/m m c
                                                 Atoms: {
                                                     Si 0 0 0 0.9 0.05
                                                     C 0 0 0 0.1 0.05
@@ -76,7 +76,7 @@ class PoldiCreatePeaksFromFileTest(unittest.TestCase):
                                                 Lattice: 5.43 5.43 5.43 90.0 90.0 90.0
                                                 Spacegroup: F d -3 m
                                                 Atoms: {
-                                                    Si 0 0 0 1.0 0.05
+                                                    Si 1/2 1/2 0 1.0 0.05
                                                 }
                                             }""")
         ws = PoldiCreatePeaksFromFile(fileHelper.getName(), 0.7, 10.0)
@@ -170,4 +170,6 @@ class PoldiCreatePeaksFromFileTest(unittest.TestCase):
 
 
 if __name__ == '__main__':
-    unittest.main()
+    # Only test if algorithm is registered (pyparsing dependency).
+    if AlgorithmFactory.exists("PoldiCreatePeaksFromFile"):
+        unittest.main()
diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/PoldiMergeTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/PoldiMergeTest.py
index d139c7d894b10b89e7142ee08ccfdddbace9a967..431b0c870ace5b12c41bde34017ed6e33496b5de 100644
--- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/PoldiMergeTest.py
+++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/PoldiMergeTest.py
@@ -6,6 +6,7 @@ from mantid.simpleapi import *
 
 import numpy as np
 
+
 class PoldiMergeTest(unittest.TestCase):
     def __init__(self, *args):
         unittest.TestCase.__init__(self, *args)
@@ -38,8 +39,9 @@ class PoldiMergeTest(unittest.TestCase):
 
             self.goodTimingBadProperties.getRun().addProperty(p, badProperty, True)
 
-    def __runMerge__(self, workspaceNames):
-        return PoldiMerge(WorkspaceNames=workspaceNames, OutputWorkspace="PoldiMergeOutput", CheckInstruments=False)
+    def __runMerge__(self, workspaceNames, checkInstruments=False):
+        return PoldiMerge(WorkspaceNames=workspaceNames, OutputWorkspace="PoldiMergeOutput",
+                          CheckInstruments=checkInstruments)
 
     def test_happyCase(self):
         output = self.__runMerge__("Base,GoodTiming")
@@ -84,12 +86,13 @@ class PoldiMergeTest(unittest.TestCase):
         self.assertFalse(AnalysisDataService.doesExist("PoldiMergeOutput"))
 
     def test_badProperties(self):
-        self.assertRaises(RuntimeError, lambda: self.__runMerge__("Base,GoodTimingBadProperties"))
+        self.assertRaises(RuntimeError, lambda: self.__runMerge__("Base,GoodTimingBadProperties", True))
         self.assertFalse(AnalysisDataService.doesExist("PoldiMergeOutput"))
 
     def test_badName(self):
         self.assertRaises(RuntimeError, lambda: self.__runMerge__("Base,NotExisting"))
         self.assertFalse(AnalysisDataService.doesExist("PoldiMergeOutput"))
 
+
 if __name__ == '__main__':
     unittest.main()
\ No newline at end of file
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/CMakeLists.txt b/Code/Mantid/Framework/RemoteAlgorithms/CMakeLists.txt
index 32c83a098f58e4bfb7f63cfa5544feb6b76d6e56..eed4f815c2fae3349aaf50f080296ca9e80314d7 100644
--- a/Code/Mantid/Framework/RemoteAlgorithms/CMakeLists.txt
+++ b/Code/Mantid/Framework/RemoteAlgorithms/CMakeLists.txt
@@ -1,46 +1,76 @@
 set( SRC_FILES
   src/AbortRemoteJob.cpp
+  src/AbortRemoteJob2.cpp
   src/Authenticate.cpp
+  src/Authenticate2.cpp
   src/DownloadRemoteFile.cpp
+  src/DownloadRemoteFile2.cpp
   src/QueryAllRemoteJobs.cpp
+  src/QueryAllRemoteJobs2.cpp
   src/QueryRemoteFile.cpp
+  src/QueryRemoteFile2.cpp
   src/QueryRemoteJob.cpp
+  src/QueryRemoteJob2.cpp
   src/SCARFTomoReconstruction.cpp
   src/SimpleJSON.cpp
   src/StartRemoteTransaction.cpp
+  src/StartRemoteTransaction2.cpp
   src/StopRemoteTransaction.cpp
+  src/StopRemoteTransaction2.cpp
   src/SubmitRemoteJob.cpp
+  src/SubmitRemoteJob2.cpp
   src/UploadRemoteFile.cpp
+  src/UploadRemoteFile2.cpp
 )
 
 set( INC_FILES
   inc/MantidRemoteAlgorithms/AbortRemoteJob.h
+  inc/MantidRemoteAlgorithms/AbortRemoteJob2.h
   inc/MantidRemoteAlgorithms/Authenticate.h
+  inc/MantidRemoteAlgorithms/Authenticate2.h
   inc/MantidRemoteAlgorithms/DownloadRemoteFile.h
+  inc/MantidRemoteAlgorithms/DownloadRemoteFile2.h
   inc/MantidRemoteAlgorithms/QueryAllRemoteJobs.h
-  inc/MantidRemoteAlgorithms/QueryRemoteJob.h
+  inc/MantidRemoteAlgorithms/QueryAllRemoteJobs2.h
   inc/MantidRemoteAlgorithms/QueryRemoteFile.h
+  inc/MantidRemoteAlgorithms/QueryRemoteFile2.h
+  inc/MantidRemoteAlgorithms/QueryRemoteJob.h
+  inc/MantidRemoteAlgorithms/QueryRemoteJob2.h
   inc/MantidRemoteAlgorithms/SCARFTomoReconstruction.h
   inc/MantidRemoteAlgorithms/SimpleJSON.h
   inc/MantidRemoteAlgorithms/StartRemoteTransaction.h
+  inc/MantidRemoteAlgorithms/StartRemoteTransaction2.h
   inc/MantidRemoteAlgorithms/StopRemoteTransaction.h
+  inc/MantidRemoteAlgorithms/StopRemoteTransaction2.h
   inc/MantidRemoteAlgorithms/SubmitRemoteJob.h
+  inc/MantidRemoteAlgorithms/SubmitRemoteJob2.h
   inc/MantidRemoteAlgorithms/UploadRemoteFile.h
+  inc/MantidRemoteAlgorithms/UploadRemoteFile2.h
 )
 
 set ( TEST_FILES
   AbortRemoteJobTest.h
+  AbortRemoteJob2Test.h
   AuthenticateTest.h
+  Authenticate2Test.h
   DownloadRemoteFileTest.h
+  DownloadRemoteFile2Test.h
   QueryAllRemoteJobsTest.h
-  QueryRemoteJobTest.h
+  QueryAllRemoteJobs2Test.h
   QueryRemoteFileTest.h
+  QueryRemoteFile2Test.h
+  QueryRemoteJobTest.h
+  QueryRemoteJob2Test.h
   SCARFTomoReconstructionTest.h
   SimpleJSONTest.h
   StartRemoteTransactionTest.h
+  StartRemoteTransaction2Test.h
   StopRemoteTransactionTest.h
+  StopRemoteTransaction2Test.h
   SubmitRemoteJobTest.h
+  SubmitRemoteJob2Test.h
   UploadRemoteFileTest.h
+  UploadRemoteFile2Test.h
 )
 
 #set ( TEST_PY_FILES
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/AbortRemoteJob2.h b/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/AbortRemoteJob2.h
new file mode 100644
index 0000000000000000000000000000000000000000..18731a49c6030b9cd43a20df9508a8c7edc189d6
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/AbortRemoteJob2.h
@@ -0,0 +1,60 @@
+#ifndef ABORTREMOTEJOB2_H_
+#define ABORTREMOTEJOB2_H_
+
+#include "MantidAPI/Algorithm.h"
+
+namespace Mantid {
+namespace RemoteAlgorithms {
+
+/**
+Abort/cancel/kill a job running on a remote compute resource.
+
+Copyright &copy; 2015 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid 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 General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>.
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport AbortRemoteJob2 : public Mantid::API::Algorithm {
+public:
+  /// (Empty) Constructor
+  AbortRemoteJob2() : Mantid::API::Algorithm() {}
+  /// Virtual destructor
+  virtual ~AbortRemoteJob2() {}
+  /// Algorithm's name
+  virtual const std::string name() const { return "AbortRemoteJob"; }
+  /// Summary of algorithms purpose
+  virtual const std::string summary() const {
+    return "Abort a previously submitted job.";
+  }
+
+  /// Algorithm's version
+  virtual int version() const { return (2); }
+  /// Algorithm's category for identification
+  virtual const std::string category() const { return "Remote"; }
+
+private:
+  void init();
+  /// Execution code
+  void exec();
+};
+
+} // end namespace RemoteAlgorithms
+} // end namespace Mantid
+
+#endif /*ABORTREMOTEJOB2_H_*/
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/Authenticate2.h b/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/Authenticate2.h
new file mode 100644
index 0000000000000000000000000000000000000000..58626d273230f6110b1ea52c1ba8b51efc994de0
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/Authenticate2.h
@@ -0,0 +1,60 @@
+#ifndef AUTHENTICATE2_H_
+#define AUTHENTICATE2_H_
+
+#include "MantidAPI/Algorithm.h"
+
+namespace Mantid {
+namespace RemoteAlgorithms {
+
+/**
+Authenticate to the remote compute resource.
+
+Copyright &copy; 2015 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid 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 General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>.
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport Authenticate2 : public Mantid::API::Algorithm {
+public:
+  /// (Empty) Constructor
+  Authenticate2() : Mantid::API::Algorithm() {}
+  /// Virtual destructor
+  virtual ~Authenticate2() {}
+  /// Algorithm's name
+  virtual const std::string name() const { return "Authenticate"; }
+  /// Summary of algorithms purpose
+  virtual const std::string summary() const {
+    return "Authenticate to the remote compute resource.";
+  }
+
+  /// Algorithm's version
+  virtual int version() const { return (2); }
+  /// Algorithm's category for identification
+  virtual const std::string category() const { return "Remote"; }
+
+private:
+  void init();
+  /// Execution code
+  void exec();
+};
+
+} // end namespace RemoteAlgorithms
+} // end namespace Mantid
+
+#endif /*AUTHENTICATE2_H_*/
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/DownloadRemoteFile2.h b/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/DownloadRemoteFile2.h
new file mode 100644
index 0000000000000000000000000000000000000000..3c09b928883fd44930573b4302235baebbdfcadb
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/DownloadRemoteFile2.h
@@ -0,0 +1,60 @@
+#ifndef DOWNLOADREMOTEFILE2_H_
+#define DOWNLOADREMOTEFILE2_H_
+
+#include "MantidAPI/Algorithm.h"
+
+namespace Mantid {
+namespace RemoteAlgorithms {
+
+/**
+Download a file from a remote compute resource.
+
+Copyright &copy; 2015 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid 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 General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>.
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport DownloadRemoteFile2 : public Mantid::API::Algorithm {
+public:
+  /// (Empty) Constructor
+  DownloadRemoteFile2() : Mantid::API::Algorithm() {}
+  /// Virtual destructor
+  virtual ~DownloadRemoteFile2() {}
+  /// Algorithm's name
+  virtual const std::string name() const { return "DownloadRemoteFile"; }
+  /// Summary of algorithms purpose
+  virtual const std::string summary() const {
+    return "Download a file from a remote compute resource.";
+  }
+
+  /// Algorithm's version
+  virtual int version() const { return (2); }
+  /// Algorithm's category for identification
+  virtual const std::string category() const { return "Remote"; }
+
+private:
+  void init();
+  /// Execution code
+  void exec();
+};
+
+} // end namespace RemoteAlgorithms
+} // end namespace Mantid
+
+#endif /*DOWNLOADREMOTEFILE2_H_*/
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/QueryAllRemoteJobs2.h b/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/QueryAllRemoteJobs2.h
new file mode 100644
index 0000000000000000000000000000000000000000..dccdcbaca1fbba9a3a87708015771fe0a835e89d
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/QueryAllRemoteJobs2.h
@@ -0,0 +1,62 @@
+#ifndef QUERYALLREMOTEJOBS2_H_
+#define QUERYALLREMOTEJOBS2_H_
+
+#include "MantidAPI/Algorithm.h"
+
+namespace Mantid {
+namespace RemoteAlgorithms {
+
+/**
+Query status information about all jobs running on a (remote) compute
+resource.
+
+Copyright &copy; 2015 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid 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 General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>.
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport QueryAllRemoteJobs2 : public Mantid::API::Algorithm {
+public:
+  /// (Empty) Constructor
+  QueryAllRemoteJobs2() : Mantid::API::Algorithm() {}
+  /// Virtual destructor
+  virtual ~QueryAllRemoteJobs2() {}
+  /// Algorithm's name
+  virtual const std::string name() const { return "QueryAllRemoteJobs"; }
+  /// Summary of algorithms purpose
+  virtual const std::string summary() const {
+    return "Query a remote compute resource for all jobs the user has "
+           "submitted.";
+  }
+
+  /// Algorithm's version
+  virtual int version() const { return (2); }
+  /// Algorithm's category for identification
+  virtual const std::string category() const { return "Remote"; }
+
+private:
+  void init();
+  /// Execution code
+  void exec();
+};
+
+} // end namespace RemoteAlgorithms
+} // end namespace Mantid
+
+#endif /*QUERYALLREMOTEJOBS2_H_*/
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/QueryRemoteFile2.h b/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/QueryRemoteFile2.h
new file mode 100644
index 0000000000000000000000000000000000000000..b58f8d6387ce7bb04fdc07bbb38efc35f2d802b0
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/QueryRemoteFile2.h
@@ -0,0 +1,60 @@
+#ifndef QUERYREMOTEFILE2_H_
+#define QUERYREMOTEFILE2_H_
+
+#include "MantidAPI/Algorithm.h"
+
+namespace Mantid {
+namespace RemoteAlgorithms {
+
+/**
+Retrieve the list of files available from a remote compute resource.
+
+Copyright &copy; 2015 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid 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 General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>.
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport QueryRemoteFile2 : public Mantid::API::Algorithm {
+public:
+  /// (Empty) Constructor
+  QueryRemoteFile2() : Mantid::API::Algorithm() {}
+  /// Virtual destructor
+  virtual ~QueryRemoteFile2() {}
+  /// Algorithm's name
+  virtual const std::string name() const { return "QueryRemoteFile"; }
+  /// Summary of algorithms purpose
+  virtual const std::string summary() const {
+    return "Retrieve a list of the files from a remote compute resource.";
+  }
+
+  /// Algorithm's version
+  virtual int version() const { return (2); }
+  /// Algorithm's category for identification
+  virtual const std::string category() const { return "Remote"; }
+
+private:
+  void init();
+  /// Execution code
+  void exec();
+};
+
+} // end namespace RemoteAlgorithms
+} // end namespace Mantid
+
+#endif /*QUERYREMOTEFILE2_H_*/
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/QueryRemoteJob2.h b/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/QueryRemoteJob2.h
new file mode 100644
index 0000000000000000000000000000000000000000..58f2fad70dd7d13aab657ca90b9f718adc88ae6a
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/QueryRemoteJob2.h
@@ -0,0 +1,60 @@
+#ifndef QUERYREMOTEJOB2_H_
+#define QUERYREMOTEJOB2_H_
+
+#include "MantidAPI/Algorithm.h"
+
+namespace Mantid {
+namespace RemoteAlgorithms {
+
+/**
+Query staus information about a job on a remote compute resource.
+
+Copyright &copy; 2015 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid 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 General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>.
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport QueryRemoteJob2 : public Mantid::API::Algorithm {
+public:
+  /// (Empty) Constructor
+  QueryRemoteJob2() : Mantid::API::Algorithm() {}
+  /// Virtual destructor
+  virtual ~QueryRemoteJob2() {}
+  /// Algorithm's name
+  virtual const std::string name() const { return "QueryRemoteJob"; }
+  /// Summary of algorithms purpose
+  virtual const std::string summary() const {
+    return "Query staus information about a job on a remote compute resource";
+  }
+
+  /// Algorithm's version
+  virtual int version() const { return (2); }
+  /// Algorithm's category for identification
+  virtual const std::string category() const { return "Remote"; }
+
+private:
+  void init();
+  /// Execution code
+  void exec();
+};
+
+} // end namespace RemoteAlgorithms
+} // end namespace Mantid
+
+#endif /*QUERYREMOTEJOB2_H_*/
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/SCARFTomoReconstruction.h b/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/SCARFTomoReconstruction.h
index cf586c0d3fc05e21b1c39fec87fc770d74bf9f4b..9c91628758c629d06d91afeebdc13037b53343fc 100644
--- a/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/SCARFTomoReconstruction.h
+++ b/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/SCARFTomoReconstruction.h
@@ -95,7 +95,8 @@ private:
   std::string buildSubmitBody(const std::string &appName,
                               const std::string &boundary,
                               const std::string &inputFiles,
-                              const std::string &inputArgs);
+                              const std::string &inputArgs,
+                              const std::string &jobName);
 
   /// lower level helper to encode parameters
   void encodeParam(std::string &body, const std::string &boundary,
@@ -110,6 +111,9 @@ private:
   void genOutputStatusInfo(const std::string &resp, const std::string &jobID =
                            std::string());
 
+  /// Job sequence number (from here, nothing to do with the job id on the cluster)
+  int jobSeqNo();
+
   // cookie obtained after logging in
   struct Token {
     Token(std::string& u, std::string& t): m_url(u), m_token_str(t) {};
@@ -160,6 +164,9 @@ private:
 
   // store for username-token pairs
   static std::map<std::string, Token> m_tokenStash;
+
+  // just to generate a sequence number for jobs started using this alg.
+  static int m_jobSeq;
 };
 
 } // end namespace RemoteAlgorithms
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/StartRemoteTransaction2.h b/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/StartRemoteTransaction2.h
new file mode 100644
index 0000000000000000000000000000000000000000..99418192a8be54c4d7d5046d049a77ae0ad500cf
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/StartRemoteTransaction2.h
@@ -0,0 +1,60 @@
+#ifndef STARTREMOTETRANSACTION2_H_
+#define STARTREMOTETRANSACTION2_H_
+
+#include "MantidAPI/Algorithm.h"
+
+namespace Mantid {
+namespace RemoteAlgorithms {
+
+/**
+Start a (new) transaction on a remote compute resource.
+
+Copyright &copy; 2015 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid 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 General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>.
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport StartRemoteTransaction2 : public Mantid::API::Algorithm {
+public:
+  /// (Empty) Constructor
+  StartRemoteTransaction2() : Mantid::API::Algorithm() {}
+  /// Virtual destructor
+  virtual ~StartRemoteTransaction2() {}
+  /// Algorithm's name
+  virtual const std::string name() const { return "StartRemoteTransaction"; }
+  /// Summary of algorithms purpose
+  virtual const std::string summary() const {
+    return "Start a (new) transaction on a remote compute resource.";
+  }
+
+  /// Algorithm's version
+  virtual int version() const { return (2); }
+  /// Algorithm's category for identification
+  virtual const std::string category() const { return "Remote"; }
+
+private:
+  void init();
+  /// Execution code
+  void exec();
+};
+
+} // end namespace RemoteAlgorithms
+} // end namespace Mantid
+
+#endif /*STARTREMOTETRANSACTION2_H_*/
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/StopRemoteTransaction2.h b/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/StopRemoteTransaction2.h
new file mode 100644
index 0000000000000000000000000000000000000000..a3c7996b4d67a4be28cb1e85753cb44cd3beffcd
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/StopRemoteTransaction2.h
@@ -0,0 +1,60 @@
+#ifndef STOPREMOTETRANSACTION2_H_
+#define STOPREMOTETRANSACTION2_H_
+
+#include "MantidAPI/Algorithm.h"
+
+namespace Mantid {
+namespace RemoteAlgorithms {
+
+/**
+Stop (cancel/kill) a transaction on a (remote) compute resource.
+
+Copyright &copy; 2015 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid 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 General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>.
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport StopRemoteTransaction2 : public Mantid::API::Algorithm {
+public:
+  /// (Empty) Constructor
+  StopRemoteTransaction2() : Mantid::API::Algorithm() {}
+  /// Virtual destructor
+  virtual ~StopRemoteTransaction2() {}
+  /// Algorithm's name
+  virtual const std::string name() const { return "StopRemoteTransaction"; }
+  /// Summary of algorithms purpose
+  virtual const std::string summary() const {
+    return "Stop a job transaction on a (remote) compute resource.";
+  }
+
+  /// Algorithm's version
+  virtual int version() const { return (2); }
+  /// Algorithm's category for identification
+  virtual const std::string category() const { return "Remote"; }
+
+private:
+  void init();
+  /// Execution code
+  void exec();
+};
+
+} // end namespace RemoteAlgorithms
+} // end namespace Mantid
+
+#endif /*STOPREMOTETRANSACTION2_H_*/
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/SubmitRemoteJob2.h b/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/SubmitRemoteJob2.h
new file mode 100644
index 0000000000000000000000000000000000000000..6a87661a6293cd122d9a9f80fb152350f12214b1
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/SubmitRemoteJob2.h
@@ -0,0 +1,61 @@
+#ifndef SUBMITREMOTEJOB2_H_
+#define SUBMITREMOTEJOB2_H_
+
+#include "MantidAPI/Algorithm.h"
+
+namespace Mantid {
+namespace RemoteAlgorithms {
+
+/**
+ Submit a job to be executed on a (remote) compute resource
+
+Copyright &copy; 2015 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid 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 General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>.
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport SubmitRemoteJob2 : public Mantid::API::Algorithm {
+public:
+  /// (Empty) Constructor
+  SubmitRemoteJob2() : Mantid::API::Algorithm() {}
+  /// Virtual destructor
+  virtual ~SubmitRemoteJob2() {}
+  /// Algorithm's name
+  virtual const std::string name() const { return "SubmitRemoteJob"; }
+  /// Summary of algorithms purpose
+  virtual const std::string summary() const {
+    return "Submit a job to be executed on the specified remote compute "
+           "resource.";
+  }
+
+  /// Algorithm's version
+  virtual int version() const { return (2); }
+  /// Algorithm's category for identification
+  virtual const std::string category() const { return "Remote"; }
+
+private:
+  void init();
+  /// Execution code
+  void exec();
+};
+
+} // end namespace RemoteAlgorithms
+} // end namespace Mantid
+
+#endif /*SUBMITREMOTEJOB2_H_*/
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/UploadRemoteFile2.h b/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/UploadRemoteFile2.h
new file mode 100644
index 0000000000000000000000000000000000000000..1da4f6691fc1f82cbc464b2cd7ed72dce26e9158
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/inc/MantidRemoteAlgorithms/UploadRemoteFile2.h
@@ -0,0 +1,59 @@
+#ifndef UPLOADREMOTEFILE2_H_
+#define UPLOADREMOTEFILE2_H_
+
+#include "MantidAPI/Algorithm.h"
+namespace Mantid {
+namespace RemoteAlgorithms {
+
+/**
+Transer/upload a file to a (remote) compute resource
+
+Copyright &copy; 2015 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid 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 General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>.
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport UploadRemoteFile2 : public API::Algorithm {
+public:
+  /// (Empty) Constructor
+  UploadRemoteFile2() : Mantid::API::Algorithm() {}
+  /// Virtual destructor
+  virtual ~UploadRemoteFile2() {}
+  /// Algorithm's name
+  virtual const std::string name() const { return "UploadRemoteFile"; }
+  /// Summary of algorithms purpose
+  virtual const std::string summary() const {
+    return "Transfers/uploads a file to the specified compute resource.";
+  }
+
+  /// Algorithm's version
+  virtual int version() const { return (2); }
+  /// Algorithm's category for identification
+  virtual const std::string category() const { return "Remote"; }
+
+private:
+  void init();
+  /// Execution code
+  void exec();
+};
+
+} // end namespace RemoteAlgorithms
+} // end namespace Mantid
+
+#endif /*UPLOADREMOTEFILE2_H_*/
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/src/AbortRemoteJob2.cpp b/Code/Mantid/Framework/RemoteAlgorithms/src/AbortRemoteJob2.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..92c5e35d03240393d7dff43ff2a8347ef4e0a123
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/src/AbortRemoteJob2.cpp
@@ -0,0 +1,52 @@
+#include "MantidAPI/RemoteJobManagerFactory.h"
+#include "MantidKernel/FacilityInfo.h"
+#include "MantidKernel/ListValidator.h"
+#include "MantidKernel/MandatoryValidator.h"
+#include "MantidKernel/NullValidator.h"
+#include "MantidRemoteAlgorithms/AbortRemoteJob2.h"
+
+namespace Mantid {
+namespace RemoteAlgorithms {
+
+// Register the algorithm into the Algorithm Factory
+DECLARE_ALGORITHM(AbortRemoteJob2)
+
+using namespace Mantid::Kernel;
+using namespace Mantid::API;
+using namespace Mantid::Geometry;
+
+// A reference to the logger is provided by the base class, it is called g_log.
+
+void AbortRemoteJob2::init() {
+  // Unlike most algorithms, this one doesn't deal with workspaces....
+
+  auto requireValue = boost::make_shared<MandatoryValidator<std::string>>();
+  auto nullValidator = boost::make_shared<NullValidator>();
+
+  // Compute Resources
+  std::vector<std::string> computes = Mantid::Kernel::ConfigService::Instance()
+                                          .getFacility()
+                                          .computeResources();
+  declareProperty(
+      "ComputeResource", "", boost::make_shared<StringListValidator>(computes),
+      "The remote computer where the job is running", Direction::Input);
+
+  // The ID of the job we want to Abort
+  declareProperty("JobID", "", requireValue, "The ID of the job to abort",
+                  Direction::Input);
+}
+
+void AbortRemoteJob2::exec() {
+
+  const std::string comp = getPropertyValue("ComputeResource");
+  Mantid::API::IRemoteJobManager_sptr jobManager =
+      Mantid::API::RemoteJobManagerFactory::Instance().create(comp);
+
+  std::string jid = getPropertyValue("JobID");
+  jobManager->abortRemoteJob(jid);
+  g_log.information() << "Aborted job with ID " << jid
+                      << " on the compute resource" << comp << std::endl;
+}
+
+} // namespace RemoteAlgorithms
+} // namespace Mantid
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/src/Authenticate2.cpp b/Code/Mantid/Framework/RemoteAlgorithms/src/Authenticate2.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..dcda38881c072049ff3da8f2f8bd79ec356dcc24
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/src/Authenticate2.cpp
@@ -0,0 +1,57 @@
+#include "MantidAPI/RemoteJobManagerFactory.h"
+#include "MantidKernel/FacilityInfo.h"
+#include "MantidKernel/ListValidator.h"
+#include "MantidKernel/MandatoryValidator.h"
+#include "MantidKernel/MaskedProperty.h"
+#include "MantidRemoteAlgorithms/Authenticate2.h"
+
+namespace Mantid {
+namespace RemoteAlgorithms {
+
+// Register the algorithm into the Algorithm Factory
+DECLARE_ALGORITHM(Authenticate2)
+
+using namespace Mantid::Kernel;
+// using namespace Mantid::API;
+// using namespace Mantid::Geometry;
+
+// A reference to the logger is provided by the base class, it is called g_log.
+
+void Authenticate2::init() {
+  // Unlike most algorithms, this wone doesn't deal with workspaces....
+
+  auto requireValue = boost::make_shared<MandatoryValidator<std::string>>();
+
+  // Compute Resources
+  std::vector<std::string> computes = Mantid::Kernel::ConfigService::Instance()
+                                          .getFacility()
+                                          .computeResources();
+  declareProperty("ComputeResource", "",
+                  boost::make_shared<StringListValidator>(computes),
+                  "The remote computer to authenticate to", Direction::Input);
+
+  // Say who we are (or at least, who we want to execute the remote python code)
+  declareProperty("UserName", "", requireValue,
+                  "Name of the user to authenticate as", Direction::Input);
+
+  // Password doesn't get echoed to the screen...
+  declareProperty(new MaskedProperty<std::string>("Password", "", requireValue,
+                                                  Direction::Input),
+                  "The password associated with the specified user");
+}
+
+void Authenticate2::exec() {
+
+  const std::string comp = getPropertyValue("ComputeResource");
+  Mantid::API::IRemoteJobManager_sptr jobManager =
+      Mantid::API::RemoteJobManagerFactory::Instance().create(comp);
+
+  const std::string user = getPropertyValue("UserName");
+  jobManager->authenticate(user, getPropertyValue("Password"));
+
+  g_log.information() << "Authenticate as user " << user
+                      << " in the compute resource " << comp << std::endl;
+}
+
+} // end namespace RemoteAlgorithms
+} // end namespace Mantid
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/src/DownloadRemoteFile2.cpp b/Code/Mantid/Framework/RemoteAlgorithms/src/DownloadRemoteFile2.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..5a9976a8004d1c8b9cfc1666e79715b3a4e8377e
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/src/DownloadRemoteFile2.cpp
@@ -0,0 +1,67 @@
+#include "MantidAPI/RemoteJobManagerFactory.h"
+#include "MantidKernel/MandatoryValidator.h"
+#include "MantidKernel/FacilityInfo.h"
+#include "MantidKernel/ListValidator.h"
+#include "MantidKernel/MaskedProperty.h"
+#include "MantidRemoteAlgorithms/DownloadRemoteFile2.h"
+
+namespace Mantid {
+namespace RemoteAlgorithms {
+
+// Register the algorithm into the AlgorithmFactory
+DECLARE_ALGORITHM(DownloadRemoteFile2)
+
+using namespace Mantid::Kernel;
+using namespace Mantid::API;
+using namespace Mantid::Geometry;
+
+// A reference to the logger is provided by the base class, it is called g_log.
+
+void DownloadRemoteFile2::init() {
+  // Unlike most algorithms, this one doesn't deal with workspaces....
+
+  auto requireValue = boost::make_shared<MandatoryValidator<std::string>>();
+
+  // Compute Resources
+  std::vector<std::string> computes = Mantid::Kernel::ConfigService::Instance()
+                                          .getFacility()
+                                          .computeResources();
+  declareProperty(
+      "ComputeResource", "", boost::make_shared<StringListValidator>(computes),
+      "The name of the remote computer holding the file", Direction::Input);
+
+  // The transaction ID comes from the StartRemoteTransaction algortithm
+  declareProperty("TransactionID", "", requireValue,
+                  "The ID of the transaction that owns the file",
+                  Direction::Input);
+  declareProperty(
+      "RemoteFileName", "", requireValue,
+      "The name of the file on the remote machine. (Filename only; no path)",
+      Direction::Input);
+  declareProperty("LocalFileName", "", requireValue,
+                  "The full pathname on the local machine where the downloaded "
+                  "file should be saved.",
+                  Direction::Input);
+  // Note: 'RemoteFileName' is just the name.  The remote server figures out the
+  // full path
+  // from the transaction ID.  'LocalFileName' *IS* the full pathname (on the
+  // local machine)
+}
+
+void DownloadRemoteFile2::exec() {
+
+  Mantid::API::IRemoteJobManager_sptr jobManager =
+      Mantid::API::RemoteJobManagerFactory::Instance().create(
+          getPropertyValue("ComputeResource"));
+
+  const std::string tid = getPropertyValue("TransactionID");
+  const std::string remote = getPropertyValue("RemoteFileName");
+  const std::string local = getPropertyValue("LocalFileName");
+  jobManager->downloadRemoteFile(tid, remote, local);
+
+  g_log.information() << "Downloaded '" << remote << "' to '" << local << "'"
+                      << std::endl;
+}
+
+} // end namespace RemoteAlgorithms
+} // end namespace Mantid
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/src/QueryAllRemoteJobs2.cpp b/Code/Mantid/Framework/RemoteAlgorithms/src/QueryAllRemoteJobs2.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..4ee0ffafd978e9369616ae56a8bef2d5b18efab2
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/src/QueryAllRemoteJobs2.cpp
@@ -0,0 +1,102 @@
+#include "MantidAPI/RemoteJobManagerFactory.h"
+#include "MantidKernel/ArrayProperty.h"
+#include "MantidKernel/FacilityInfo.h"
+#include "MantidKernel/ListValidator.h"
+#include "MantidKernel/NullValidator.h"
+#include "MantidRemoteAlgorithms/QueryAllRemoteJobs2.h"
+
+namespace Mantid {
+namespace RemoteAlgorithms {
+
+// Register the algorithm into the AlgorithmFactory
+DECLARE_ALGORITHM(QueryAllRemoteJobs2)
+
+using namespace Mantid::Kernel;
+
+// A reference to the logger is provided by the base class, it is called g_log.
+
+void QueryAllRemoteJobs2::init() {
+  // Unlike most algorithms, this one doesn't deal with workspaces....
+
+  auto nullValidator = boost::make_shared<NullValidator>();
+
+  // Compute Resources
+  std::vector<std::string> computes = Mantid::Kernel::ConfigService::Instance()
+                                          .getFacility()
+                                          .computeResources();
+  declareProperty("ComputeResource", "",
+                  boost::make_shared<StringListValidator>(computes),
+                  "The name of the remote computer to query", Direction::Input);
+
+  // Mantid can't store arbitrary structs in its properties, so we're going to
+  // declare several array properties for different pieces of data.  Values from
+  // the same array index are for the same job.
+  declareProperty(
+      new ArrayProperty<std::string>("JobId", nullValidator, Direction::Output),
+      "ID string for the job");
+  declareProperty(new ArrayProperty<std::string>(
+                      "JobStatusString", nullValidator, Direction::Output),
+                  "Description of the job's current status (Queued, Running, "
+                  "Complete, etc..)");
+  declareProperty(new ArrayProperty<std::string>("JobName", nullValidator,
+                                                 Direction::Output),
+                  "Name of the job (specified when the job was submitted)");
+  declareProperty(new ArrayProperty<std::string>("ScriptName", nullValidator,
+                                                 Direction::Output),
+                  "The name of the script (python, etc.) or other type of "
+                  "executable that the job runs");
+  declareProperty(new ArrayProperty<std::string>("TransID", nullValidator,
+                                                 Direction::Output),
+                  "The ID of the transaction that owns the job");
+
+  // Times for job submit, job start and job complete (may be empty depending
+  // on the server-side implementation)
+  declareProperty(new ArrayProperty<std::string>("SubmitDate", nullValidator,
+                                                 Direction::Output),
+                  "The date & time the job was submitted");
+  declareProperty(new ArrayProperty<std::string>("StartDate", nullValidator,
+                                                 Direction::Output),
+                  "The date & time the job actually started executing");
+  declareProperty(new ArrayProperty<std::string>(
+                      "CompletionDate", nullValidator, Direction::Output),
+                  "The date & time the job finished");
+}
+
+void QueryAllRemoteJobs2::exec() {
+  Mantid::API::IRemoteJobManager_sptr jm =
+      Mantid::API::RemoteJobManagerFactory::Instance().create(
+          getPropertyValue("ComputeResource"));
+
+  std::vector<Mantid::API::IRemoteJobManager::RemoteJobInfo> infos =
+      jm->queryAllRemoteJobs();
+
+  std::vector<std::string> jobIds;
+  std::vector<std::string> jobStatusStrs;
+  std::vector<std::string> jobNames;
+  std::vector<std::string> runNames;
+  std::vector<std::string> transIds;
+  std::vector<std::string> submitDates;
+  std::vector<std::string> startDates;
+  std::vector<std::string> completionDates;
+  for (size_t j = 0; j < infos.size(); ++j) {
+    jobIds.push_back(infos[j].id);
+    jobNames.push_back(infos[j].name);
+    jobStatusStrs.push_back(infos[j].status);
+    transIds.push_back(infos[j].transactionID);
+    runNames.push_back(infos[j].runnableName);
+    submitDates.push_back(infos[j].submitDate.toISO8601String());
+    startDates.push_back(infos[j].startDate.toISO8601String());
+    completionDates.push_back(infos[j].completionTime.toISO8601String());
+  }
+  setProperty("JobId", jobIds);
+  setProperty("JobStatusString", jobStatusStrs);
+  setProperty("JobName", jobNames);
+  setProperty("ScriptName", runNames);
+  setProperty("TransID", transIds);
+  setProperty("SubmitDate", submitDates);
+  setProperty("StartDate", startDates);
+  setProperty("CompletionDate", completionDates);
+}
+
+} // end namespace RemoteAlgorithms
+} // end namespace Mantid
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/src/QueryRemoteFile2.cpp b/Code/Mantid/Framework/RemoteAlgorithms/src/QueryRemoteFile2.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..09f1213203aa0d2c0520de823ce4e5e40ecfc2fb
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/src/QueryRemoteFile2.cpp
@@ -0,0 +1,56 @@
+#include "MantidAPI/RemoteJobManagerFactory.h"
+#include "MantidKernel/ArrayProperty.h"
+#include "MantidKernel/FacilityInfo.h"
+#include "MantidKernel/ListValidator.h"
+#include "MantidKernel/MandatoryValidator.h"
+#include "MantidRemoteAlgorithms/QueryRemoteFile2.h"
+
+namespace Mantid {
+namespace RemoteAlgorithms {
+
+// Register the algorithm into the AlgorithmFactory
+DECLARE_ALGORITHM(QueryRemoteFile2)
+
+using namespace Mantid::Kernel;
+using namespace Mantid::API;
+using namespace Mantid::Geometry;
+
+// A reference to the logger is provided by the base class, it is called g_log.
+
+void QueryRemoteFile2::init() {
+  // Unlike most algorithms, this one doesn't deal with workspaces....
+
+  auto requireValue = boost::make_shared<MandatoryValidator<std::string>>();
+
+  // Compute Resources
+  std::vector<std::string> computes = Mantid::Kernel::ConfigService::Instance()
+                                          .getFacility()
+                                          .computeResources();
+  declareProperty("ComputeResource", "",
+                  boost::make_shared<StringListValidator>(computes),
+                  "The name of the remote computer to query", Direction::Input);
+
+  // The transaction ID comes from the StartRemoteTransaction algortithm
+  declareProperty("TransactionID", "", requireValue,
+                  "The ID of the transaction who's files we want to list",
+                  Direction::Input);
+
+  declareProperty(
+      new ArrayProperty<std::string>("FileNames", Direction::Output),
+      "The names of all the files that were found");
+}
+
+void QueryRemoteFile2::exec() {
+
+  Mantid::API::IRemoteJobManager_sptr jm =
+      Mantid::API::RemoteJobManagerFactory::Instance().create(
+          getPropertyValue("ComputeResource"));
+
+  std::string tid = getPropertyValue("TransactionID");
+  std::vector<std::string> names = jm->queryRemoteFile(tid);
+
+  setProperty("FileNames", names);
+}
+
+} // end namespace RemoteAlgorithms
+} // end namespace Mantid
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/src/QueryRemoteJob2.cpp b/Code/Mantid/Framework/RemoteAlgorithms/src/QueryRemoteJob2.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..3d6db94c551ed9f595ac5a957cf3c638297fba5c
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/src/QueryRemoteJob2.cpp
@@ -0,0 +1,94 @@
+#include "MantidAPI/RemoteJobManagerFactory.h"
+#include "MantidKernel/FacilityInfo.h"
+#include "MantidKernel/ListValidator.h"
+#include "MantidKernel/NullValidator.h"
+#include "MantidKernel/MandatoryValidator.h"
+#include "MantidRemoteAlgorithms/QueryRemoteJob2.h"
+
+namespace Mantid {
+namespace RemoteAlgorithms {
+
+// Register the algorithm into the Algorithm Factory
+DECLARE_ALGORITHM(QueryRemoteJob2)
+
+using namespace Mantid::Kernel;
+using namespace Mantid::API;
+using namespace Mantid::Geometry;
+
+// A reference to the logger is provided by the base class, it is called g_log.
+
+void QueryRemoteJob2::init() {
+  // Unlike most algorithms, this one doesn't deal with workspaces....
+
+  auto requireValue = boost::make_shared<MandatoryValidator<std::string>>();
+  auto nullValidator = boost::make_shared<NullValidator>();
+
+  // Compute Resources
+  std::vector<std::string> computes = Mantid::Kernel::ConfigService::Instance()
+                                          .getFacility()
+                                          .computeResources();
+  declareProperty(
+      "ComputeResource", "", boost::make_shared<StringListValidator>(computes),
+      "The name of the remote compute resource to query", Direction::Input);
+
+  // The ID of the job we want to query
+  declareProperty("JobID", "", requireValue, "The ID of the job to query",
+                  Direction::Input);
+
+  // Name given to the job
+  declareProperty("JobName", "", nullValidator, "The name of the job",
+                  Direction::Output);
+
+  // Name of the executable/python or other kind of script that was (or will be)
+  // run
+  declareProperty(
+      "ScriptName", "", nullValidator,
+      "The name of the script or executable that was (or will be) run",
+      Direction::Output);
+
+  // A human readable description of the job's status
+  declareProperty("JobStatusString", "", nullValidator,
+                  "The current status of the job (example: Queued, Running, "
+                  "Complete, etc..)",
+                  Direction::Output);
+
+  // Transaction ID this job is associated with
+  declareProperty("TransID", "", nullValidator,
+                  "The transaction ID this job was submitted under",
+                  Direction::Output);
+
+  // Dates and times for job submit, job start and job complete (may be empty
+  // depending on the server-side implementation)
+  declareProperty("SubmitDate", "", nullValidator,
+                  "The date & time the job was submitted (availability is "
+                  "optional and implementation dependent)",
+                  Direction::Output);
+  declareProperty("StartDate", "", nullValidator,
+                  "The date & time the job actually started executing "
+                  "(availability is optional and implementation dependent)",
+                  Direction::Output);
+  declareProperty("CompletionDate", "", nullValidator,
+                  "The date & time the job finished (availability is optional "
+                  "and implementation dependent)",
+                  Direction::Output);
+}
+
+void QueryRemoteJob2::exec() {
+  Mantid::API::IRemoteJobManager_sptr jm =
+      Mantid::API::RemoteJobManagerFactory::Instance().create(
+          getPropertyValue("ComputeResource"));
+
+  Mantid::API::IRemoteJobManager::RemoteJobInfo info =
+      jm->queryRemoteJob(getPropertyValue("JobID"));
+
+  setProperty("JobName", info.name);
+  setProperty("ScriptName", info.runnableName);
+  setProperty("JobStatusString", info.status);
+  setProperty("TransID", info.transactionID);
+  setProperty("SubmitDate", info.submitDate.toISO8601String());
+  setProperty("StartDate", info.startDate.toISO8601String());
+  setProperty("CompletionDate", info.completionTime.toISO8601String());
+}
+
+} // end namespace RemoteAlgorithms
+} // end namespace Mantid
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/src/SCARFTomoReconstruction.cpp b/Code/Mantid/Framework/RemoteAlgorithms/src/SCARFTomoReconstruction.cpp
index ef3b37f441c8cdda0fc35bff344a14704f543191..0fef04f905a7183cc887014649adf48e7c1b279f 100644
--- a/Code/Mantid/Framework/RemoteAlgorithms/src/SCARFTomoReconstruction.cpp
+++ b/Code/Mantid/Framework/RemoteAlgorithms/src/SCARFTomoReconstruction.cpp
@@ -38,6 +38,8 @@ std::string SCARFTomoReconstruction::m_acceptType =
 
 const std::string SCARFTomoReconstruction::m_SCARFComputeResource = "SCARF@STFC";
 
+int SCARFTomoReconstruction::m_jobSeq = 1;
+
 SCARFTomoReconstruction::SCARFTomoReconstruction():
   Mantid::API::Algorithm(), m_action()
 { }
@@ -94,6 +96,12 @@ void SCARFTomoReconstruction::init() {
   setPropertySettings("JobOptions",
                       new VisibleWhenProperty("Action", IS_EQUAL_TO, "SubmitJob"));
 
+  declareProperty("JobName", "", nullV, "Optional name for the job, if not given then a "
+                  "name will be generated internally or at the compute resource",
+                  Direction::Input);
+  setPropertySettings("JobName", new VisibleWhenProperty("Action", IS_EQUAL_TO,
+                                                         "SubmitJob"));
+
   // - Action: upload file
   declareProperty(new API::FileProperty("FileToUpload", "",
                                         API::FileProperty::OptionalLoad, "",
@@ -433,6 +441,13 @@ void SCARFTomoReconstruction::doSubmit(const std::string &username) {
     throw;
   }
 
+  std::string jobName = "";
+  try {
+    jobName = getPropertyValue("JobName");
+  } catch(std::runtime_error& /*e*/) {
+    jobName = "";
+  }
+
   progress(0, "Starting job...");
 
   // Job submit query, requires specific parameters for LSF submit
@@ -441,11 +456,22 @@ void SCARFTomoReconstruction::doSubmit(const std::string &username) {
   // /work/imat/webservice_test/tomopy/imat_recon_FBP.py;INPUT_ARGS=
   // /work/imat/scripts/test_;JOB_NAME=01_test_job;OUTPUT_FILE=%J.output;ERROR_FILE=
   // %J.error"
-  const std::string appName = "TOMOPY_0_0_3";
+
+  // Two applications are for now registered on SCARF:
+  //  TOMOPY_0_0_3, PYASTRATOOLBOX_1_1
+  std::string appName = "TOMOPY_0_0_3";
+  // Basic attempt at guessing the app that we might really need. This
+  // is not fixed/unstable at the moment
+  if (runnablePath.find("astra-2d-FBP") != std::string::npos
+      ||
+      runnablePath.find("astra-3d-SIRT3D") != std::string::npos ) {
+    appName = "PYASTRATOOLBOX_1_1";
+  }
+
   // this gets executed (for example via 'exec' or 'python', depending on the appName
   const std::string boundary = "bqJky99mlBWa-ZuqjC53mG6EzbmlxB";
   const std::string &body = buildSubmitBody(appName, boundary,
-                                            runnablePath, jobOptions);
+                                            runnablePath, jobOptions, jobName);
 
   // Job submit, needs these headers:
   // headers = {'Content-Type': 'multipart/mixed; boundary='+boundary,
@@ -884,9 +910,8 @@ void SCARFTomoReconstruction::encodeParam(std::string &body,
  * Tiny helper to generate an integer sequence number for the job
  * names.
  */
-int seqNo() {
-  static int s = 1;
-  return s++;
+int SCARFTomoReconstruction::jobSeqNo() {
+  return m_jobSeq++;
 }
 
 /**
@@ -897,13 +922,15 @@ int seqNo() {
  * @param boundary Boundary string between parts of the multi-part body
  * @param inputFile Input file parameter, this file will be run
  * @param inputArgs Arguments to the command (application specific)
+ * @param jobName Name passed by the user (can be empty == no preference)
  *
  * @return A string ready to be used as body of a 'job submit' HTTP request
  */
 std::string SCARFTomoReconstruction::buildSubmitBody(const std::string &appName,
                                                      const std::string &boundary,
                                                      const std::string &inputFile,
-                                                     const std::string &inputArgs) {
+                                                     const std::string &inputArgs,
+                                                     const std::string &jobName) {
   // BLOCK: start and encode app name like this:
   // --bqJky99mlBWa-ZuqjC53mG6EzbmlxB
   // Content-Disposition: form-data; name="AppName"
@@ -967,8 +994,14 @@ std::string SCARFTomoReconstruction::buildSubmitBody(const std::string &appName,
     // Content-Type: application/xml; charset=US-ASCII
     // Content-Transfer-Encoding: 8bit
     // <AppParam><id>JOB_NAME</id><value>foo</value><type></type></AppParam>
-    encodeParam(body, boundaryInner, "JOB_NAME", "Mantid_tomography_" +
-                boost::lexical_cast<std::string>(seqNo()));
+    std::string name;
+    if (jobName.empty()) {
+      name = "Mantid_tomography_" +
+        boost::lexical_cast<std::string>(jobSeqNo());
+    } else {
+      name = jobName;
+    }
+    encodeParam(body, boundaryInner, "JOB_NAME", name);
   }
   {
     // BLOCK: encode INPUT_FILE (this is what will be run,
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/src/StartRemoteTransaction2.cpp b/Code/Mantid/Framework/RemoteAlgorithms/src/StartRemoteTransaction2.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..459b6a74ea891476720bd5e8b7f236502041614c
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/src/StartRemoteTransaction2.cpp
@@ -0,0 +1,45 @@
+#include "MantidAPI/RemoteJobManagerFactory.h"
+#include "MantidKernel/FacilityInfo.h"
+#include "MantidKernel/ListValidator.h"
+#include "MantidRemoteAlgorithms/StartRemoteTransaction2.h"
+
+namespace Mantid {
+namespace RemoteAlgorithms {
+
+// Register the algorithm into the Algorithm Factory
+DECLARE_ALGORITHM(StartRemoteTransaction2)
+
+using namespace Mantid::Kernel;
+
+// A reference to the logger is provided by the base class, it is called g_log.
+
+void StartRemoteTransaction2::init() {
+  // Compute Resources
+  std::vector<std::string> computes = Mantid::Kernel::ConfigService::Instance()
+                                          .getFacility()
+                                          .computeResources();
+  declareProperty("ComputeResource", "",
+                  boost::make_shared<StringListValidator>(computes),
+                  "The name of the remote computer where the new transaction "
+                  "will be created",
+                  Direction::Input);
+
+  // output property
+  declareProperty("TransactionID", std::string(""),
+                  "The ID of the new transaction", Direction::Output);
+}
+
+void StartRemoteTransaction2::exec() {
+
+  Mantid::API::IRemoteJobManager_sptr jm =
+      Mantid::API::RemoteJobManagerFactory::Instance().create(
+          getPropertyValue("ComputeResource"));
+
+  std::string tid = jm->startRemoteTransaction();
+
+  setPropertyValue("TransactionID", tid);
+  g_log.information() << "Transaction ID " << tid << " started." << std::endl;
+}
+
+} // end namespace RemoteAlgorithms
+} // end namespace Mantid
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/src/StopRemoteTransaction2.cpp b/Code/Mantid/Framework/RemoteAlgorithms/src/StopRemoteTransaction2.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..176454920701e405334cb9e6f95bb881f763643b
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/src/StopRemoteTransaction2.cpp
@@ -0,0 +1,52 @@
+#include "MantidAPI/RemoteJobManagerFactory.h"
+#include "MantidRemoteAlgorithms/SimpleJSON.h"
+#include "MantidKernel/MandatoryValidator.h"
+#include "MantidKernel/FacilityInfo.h"
+#include "MantidKernel/ListValidator.h"
+#include "MantidRemoteAlgorithms/StopRemoteTransaction2.h"
+
+namespace Mantid {
+namespace RemoteAlgorithms {
+
+// Register the algorithm into the Algorithm Factory
+DECLARE_ALGORITHM(StopRemoteTransaction2)
+
+using namespace Mantid::Kernel;
+
+// A reference to the logger is provided by the base class, it is called g_log.
+
+void StopRemoteTransaction2::init() {
+  auto requireValue =
+      boost::make_shared<Mantid::Kernel::MandatoryValidator<std::string>>();
+
+  // Compute Resources
+  std::vector<std::string> computes = Mantid::Kernel::ConfigService::Instance()
+                                          .getFacility()
+                                          .computeResources();
+  declareProperty(
+      "ComputeResource", "", boost::make_shared<StringListValidator>(computes),
+      "The name of the remote computer where the transaction was created",
+      Direction::Input);
+
+  // The transaction ID comes from the StartRemoteTransaction algortithm
+  declareProperty("TransactionID", "", requireValue,
+                  "The ID string returned when the transaction was created",
+                  Mantid::Kernel::Direction::Input);
+}
+
+void StopRemoteTransaction2::exec() {
+
+  const std::string comp = getPropertyValue("ComputeResource");
+  Mantid::API::IRemoteJobManager_sptr jm =
+      Mantid::API::RemoteJobManagerFactory::Instance().create(comp);
+
+  std::string tid = getPropertyValue("TransactionID");
+  jm->stopRemoteTransaction(tid);
+
+  g_log.information() << "Transaction with ID " << tid
+                      << " stopped on the compute resource " << comp
+                      << std::endl;
+}
+
+} // end namespace RemoteAlgorithms
+} // end namespace Mantid
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/src/SubmitRemoteJob2.cpp b/Code/Mantid/Framework/RemoteAlgorithms/src/SubmitRemoteJob2.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..e07a810388c5b70675bd1ea49b214b4005a1b963
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/src/SubmitRemoteJob2.cpp
@@ -0,0 +1,95 @@
+#include "MantidAPI/RemoteJobManagerFactory.h"
+#include "MantidKernel/BoundedValidator.h"
+#include "MantidKernel/MandatoryValidator.h"
+#include "MantidKernel/FacilityInfo.h"
+#include "MantidKernel/ListValidator.h"
+#include "MantidRemoteAlgorithms/SubmitRemoteJob2.h"
+
+namespace Mantid {
+namespace RemoteAlgorithms {
+
+// Register the algorithm into the AlgorithmFactory
+DECLARE_ALGORITHM(SubmitRemoteJob2)
+
+using namespace Mantid::Kernel;
+
+void SubmitRemoteJob2::init() {
+  // Unlike most algorithms, this wone doesn't deal with workspaces....
+
+  auto mustBePositive = boost::make_shared<BoundedValidator<int>>();
+  mustBePositive->setLower(1);
+
+  auto requireValue = boost::make_shared<MandatoryValidator<std::string>>();
+
+  // Compute Resources
+  std::vector<std::string> computes = Mantid::Kernel::ConfigService::Instance()
+                                          .getFacility()
+                                          .computeResources();
+  declareProperty(
+      "ComputeResource", "", boost::make_shared<StringListValidator>(computes),
+      "The name of the remote computer to submit the job to", Direction::Input);
+
+  // Note: these 2 properties are 'implementation specific'.  We know that for
+  // example Fermi  needs them, and SCARF supports them, but we really
+  // ought to query the information URL before requiring them.
+  declareProperty("NumNodes", 1, mustBePositive,
+                  "The number of compute nodes the job requires",
+                  Direction::Input);
+  declareProperty("CoresPerNode", 1, mustBePositive,
+                  "The number of processes to start on each compute node",
+                  Direction::Input);
+  // Number of actual MPI processes will be (NumNodes * CoresPerNode)
+
+  // This is just an easy way to reference remote jobs (such as when we display
+  // a list of all the jobs the user has submitted recently...)
+  declareProperty("TaskName", std::string(""),
+                  "A short name for the job (optional).", Direction::Input);
+
+  // The transaction ID comes from the StartRemoteTransaction algortithm
+  declareProperty("TransactionID", "", requireValue,
+                  "The transaction ID to associate with this job",
+                  Direction::Input);
+
+  // Name of the python script to execute
+  declareProperty(
+      "ScriptName", "", requireValue,
+      "A name for the runnable/executable (for example a python script) "
+      "that will be executed",
+      Direction::Input);
+
+  // The actual python code
+  declareProperty(
+      "ScriptParams", "", requireValue,
+      "Parameters to pass to the runnable/script/executable - when running "
+      "python scripts through the the Mantid remote job submission "
+      "API this will be the actual python code to execute",
+      Direction::Input);
+
+  // Assuming the submission succeeded, this property will be set with a value
+  // we can use to track the job
+  declareProperty("JobID", std::string(""), "An ID string for this job",
+                  Direction::Output);
+}
+
+void SubmitRemoteJob2::exec() {
+  // Put the algorithm execution code here...
+  const std::string comp = getPropertyValue("ComputeResource");
+  Mantid::API::IRemoteJobManager_sptr jm =
+      Mantid::API::RemoteJobManagerFactory::Instance().create(
+          comp);
+
+  const std::string tid = getPropertyValue("TransactionID");
+  const std::string runnable = getPropertyValue("ScriptName");
+  const std::string params = getPropertyValue("ScriptParams");
+  const std::string displayName = getPropertyValue("TaskName");
+  const int nodes = getProperty("NumNodes");
+  const int cores = getProperty("CoresPerNode");
+  std::string jid = jm->submitRemoteJob(tid, runnable, params, displayName, nodes, cores);
+
+  setPropertyValue("JobID", jid);
+  g_log.information() << "Job submitted.  Job ID =  "
+                      << jid << " on (remote) compute resource " << comp << std::endl;
+}
+
+} // end namespace RemoteAlgorithms
+} // end namespace Mantid
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/src/UploadRemoteFile2.cpp b/Code/Mantid/Framework/RemoteAlgorithms/src/UploadRemoteFile2.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..300ad41eee152af55b29326d0543a6778696d354
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/src/UploadRemoteFile2.cpp
@@ -0,0 +1,69 @@
+#include "MantidAPI/RemoteJobManagerFactory.h"
+#include "MantidKernel/FacilityInfo.h"
+#include "MantidKernel/ListValidator.h"
+#include "MantidKernel/MandatoryValidator.h"
+#include "MantidRemoteAlgorithms/UploadRemoteFile2.h"
+
+namespace Mantid {
+namespace RemoteAlgorithms {
+
+// Register the algorithm into the AlgorithmFactory
+DECLARE_ALGORITHM(UploadRemoteFile2)
+
+using namespace Mantid::Kernel;
+using namespace Mantid::API;
+using namespace Mantid::Geometry;
+
+// A reference to the logger is provided by the base class, it is called g_log.
+
+void UploadRemoteFile2::init() {
+  // Unlike most algorithms, this one doesn't deal with workspaces....
+
+  auto requireValue = boost::make_shared<MandatoryValidator<std::string>>();
+
+  // Compute Resources
+  std::vector<std::string> computes = Mantid::Kernel::ConfigService::Instance()
+                                          .getFacility()
+                                          .computeResources();
+  declareProperty("ComputeResource", "",
+                  boost::make_shared<StringListValidator>(computes),
+                  "The name of the remote computer to upload the file to",
+                  Direction::Input);
+
+  // The transaction ID comes from the StartRemoteTransaction algortithm
+  declareProperty("TransactionID", "", requireValue,
+                  "The transaction the file will be associated with",
+                  Direction::Input);
+  declareProperty("RemoteFileName", "", requireValue,
+                  "The name to save the file as on the remote computer. "
+                  "(Filename only; no path information)",
+                  Direction::Input);
+  declareProperty(
+      "LocalFileName", "", requireValue,
+      "The full pathname (on the local machine) of the file to upload",
+      Direction::Input);
+  // Note: 'RemoteFileName' is just the name.  The remote server figures out the
+  // full path
+  // from the transaction ID.  'LocalFileName' *IS* the full pathname (on the
+  // local machine)
+}
+
+void UploadRemoteFile2::exec() {
+
+  const std::string comp = getPropertyValue("ComputeResource");
+  Mantid::API::IRemoteJobManager_sptr jobManager =
+      Mantid::API::RemoteJobManagerFactory::Instance().create(
+          comp);
+
+  const std::string tid = getPropertyValue("TransactionID");
+  const std::string remote = getPropertyValue("RemoteFileName");
+  const std::string local = getPropertyValue("LocalFileName");
+  jobManager->uploadRemoteFile(tid, remote, local);
+
+  g_log.information() << "Uploaded '" << getPropertyValue("RemoteFileName")
+                      << "' to '" << getPropertyValue("LocalFileName")
+                      << "'" << " on the compute resource " << comp << std::endl;
+}
+
+} // end namespace RemoteAlgorithms
+} // end namespace Mantid
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/test/AbortRemoteJob2Test.h b/Code/Mantid/Framework/RemoteAlgorithms/test/AbortRemoteJob2Test.h
new file mode 100644
index 0000000000000000000000000000000000000000..ec3e671caabd651e32ec435bb88a5123539f2029
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/test/AbortRemoteJob2Test.h
@@ -0,0 +1,128 @@
+#ifndef MANTID_REMOTEALGORITHMS_ABORTREMOTEJOB2TEST_H_
+#define MANTID_REMOTEALGORITHMS_ABORTREMOTEJOB2TEST_H_
+
+#include <cxxtest/TestSuite.h>
+
+#include "MantidAPI/AlgorithmManager.h"
+#include "MantidKernel/ConfigService.h"
+#include "MantidKernel/FacilityInfo.h"
+#include "MantidRemoteAlgorithms/AbortRemoteJob2.h"
+
+using namespace Mantid::RemoteAlgorithms;
+
+class AbortRemoteJob2Test : public CxxTest::TestSuite {
+public:
+  // This pair of boilerplate methods prevent the suite being created statically
+  // This means the constructor isn't called when running other tests
+  static AbortRemoteJob2Test *createSuite() {
+    return new AbortRemoteJob2Test();
+  }
+  static void destroySuite(AbortRemoteJob2Test *suite) { delete suite; }
+
+  void test_algorithm() {
+    testAlg = Mantid::API::AlgorithmManager::Instance().create("AbortRemoteJob"
+                                                               /*, 2*/);
+    TS_ASSERT(testAlg);
+    TS_ASSERT_EQUALS(testAlg->name(), "AbortRemoteJob");
+    TS_ASSERT_EQUALS(testAlg->version(), 2);
+  }
+
+  void test_castAlgorithm() {
+    // can create
+    boost::shared_ptr<AbortRemoteJob2> a;
+    TS_ASSERT(a = boost::make_shared<AbortRemoteJob2>());
+    // can cast to inherited interfaces and base classes
+
+    TS_ASSERT(
+        dynamic_cast<Mantid::RemoteAlgorithms::AbortRemoteJob2 *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::API::Algorithm *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::Kernel::PropertyManagerOwner *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::API::IAlgorithm *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::Kernel::IPropertyManager *>(a.get()));
+  }
+
+  void test_init() {
+    if (!testAlg->isInitialized())
+      TS_ASSERT_THROWS_NOTHING(testAlg->initialize());
+
+    TS_ASSERT(testAlg->isInitialized());
+
+    AbortRemoteJob2 auth;
+    TS_ASSERT_THROWS_NOTHING(auth.initialize());
+  }
+
+  // TODO: when we have a RemoteJobManager capable of creating
+  // algorithms for different types of compute resources (example:
+  // Fermi@SNS and SCARF@STFC), create different algorithms for them
+  void test_propertiesMissing() {
+    AbortRemoteJob2 alg1;
+    TS_ASSERT_THROWS_NOTHING(alg1.initialize());
+    // id missing
+    TS_ASSERT_THROWS(alg1.setPropertyValue("ComputeResource", "missing!"),
+                     std::invalid_argument);
+
+    TS_ASSERT_THROWS(alg1.execute(), std::runtime_error);
+    TS_ASSERT(!alg1.isExecuted());
+
+    AbortRemoteJob2 alg3;
+    TS_ASSERT_THROWS_NOTHING(alg3.initialize());
+    // compute resource missing
+    TS_ASSERT_THROWS_NOTHING(alg1.setPropertyValue("JobID", "john_missing"));
+
+    TS_ASSERT_THROWS(alg3.execute(), std::runtime_error);
+    TS_ASSERT(!alg3.isExecuted());
+  }
+
+  void test_wrongProperty() {
+    AbortRemoteJob2 ab;
+    TS_ASSERT_THROWS_NOTHING(ab.initialize();)
+    TS_ASSERT_THROWS(ab.setPropertyValue("ComputeRes", "anything"),
+                     std::runtime_error);
+    TS_ASSERT_THROWS(ab.setPropertyValue("username", "anything"),
+                     std::runtime_error);
+    TS_ASSERT_THROWS(ab.setPropertyValue("sername", "anything"),
+                     std::runtime_error);
+  }
+
+  void test_wrongResource() {
+    AbortRemoteJob2 ab;
+    TS_ASSERT_THROWS_NOTHING(ab.initialize());
+    // the compute resource given  does not exist:
+    TS_ASSERT_THROWS(ab.setPropertyValue("ComputeResource", "missing c r!"),
+                     std::invalid_argument);
+  }
+
+  void test_propertiesOK() {
+    testFacilities.push_back(std::make_pair("SNS", "Fermi"));
+    testFacilities.push_back(std::make_pair("ISIS", "SCARF@STFC"));
+
+    const Mantid::Kernel::FacilityInfo &prevFac =
+        Mantid::Kernel::ConfigService::Instance().getFacility();
+    for (size_t fi = 0; fi < testFacilities.size(); fi++) {
+      const std::string facName = testFacilities[fi].first;
+      const std::string compName = testFacilities[fi].second;
+
+      Mantid::Kernel::ConfigService::Instance().setFacility(facName);
+      AbortRemoteJob2 ab;
+      TS_ASSERT_THROWS_NOTHING(ab.initialize());
+      TS_ASSERT_THROWS_NOTHING(
+          ab.setPropertyValue("ComputeResource", compName));
+      TS_ASSERT_THROWS_NOTHING(ab.setPropertyValue("JobID", "000001"));
+      // TODO: this will run the algorithm and do a remote
+      // connection. uncomment only when/if we have a mock up for this
+      // TS_ASSERT_THROWS(ab.execute(), std::exception);
+      TS_ASSERT(!ab.isExecuted());
+    }
+    Mantid::Kernel::ConfigService::Instance().setFacility(prevFac.name());
+  }
+
+  // TODO: void test_runOK() - with a mock when we can add it.
+  // ideally, with different compute resources to check the remote job
+  // manager factory, etc.
+
+private:
+  Mantid::API::IAlgorithm_sptr testAlg;
+  std::vector<std::pair<std::string, std::string>> testFacilities;
+};
+
+#endif // MANTID_REMOTEALGORITHMS_ABORTREMOTEJOB2TEST_H_
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/test/AbortRemoteJobTest.h b/Code/Mantid/Framework/RemoteAlgorithms/test/AbortRemoteJobTest.h
index 331770bbf3d5cfde0fd8839db1d28835947ac259..2a5b8853ce242cedfef8da8ea01375f70490dc29 100644
--- a/Code/Mantid/Framework/RemoteAlgorithms/test/AbortRemoteJobTest.h
+++ b/Code/Mantid/Framework/RemoteAlgorithms/test/AbortRemoteJobTest.h
@@ -19,7 +19,7 @@ public:
 
   void test_algorithm() {
     testAlg = Mantid::API::AlgorithmManager::Instance().create(
-        "AbortRemoteJob" /*, 1*/);
+        "AbortRemoteJob", 1);
     TS_ASSERT(testAlg);
     TS_ASSERT_EQUALS(testAlg->name(), "AbortRemoteJob");
     TS_ASSERT_EQUALS(testAlg->version(), 1);
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/test/Authenticate2Test.h b/Code/Mantid/Framework/RemoteAlgorithms/test/Authenticate2Test.h
new file mode 100644
index 0000000000000000000000000000000000000000..0cd950ef372e1dc7b68f8527b9184258841467dc
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/test/Authenticate2Test.h
@@ -0,0 +1,131 @@
+#ifndef MANTID_REMOTEALGORITHMS_AUTHENTICATE2TEST_H_
+#define MANTID_REMOTEALGORITHMS_AUTHENTICATE2TEST_H_
+
+#include <cxxtest/TestSuite.h>
+
+#include "MantidAPI/AlgorithmManager.h"
+#include "MantidKernel/ConfigService.h"
+#include "MantidKernel/FacilityInfo.h"
+#include "MantidRemoteAlgorithms/Authenticate2.h"
+
+using namespace Mantid::RemoteAlgorithms;
+
+class Authenticate2Test : public CxxTest::TestSuite {
+public:
+  // This pair of boilerplate methods prevent the suite being created statically
+  // This means the constructor isn't called when running other tests
+  static Authenticate2Test *createSuite() { return new Authenticate2Test(); }
+  static void destroySuite(Authenticate2Test *suite) { delete suite; }
+
+  void test_algorithm() {
+    testAlg =
+        Mantid::API::AlgorithmManager::Instance().create("Authenticate", 2);
+    TS_ASSERT(testAlg);
+    TS_ASSERT_EQUALS(testAlg->name(), "Authenticate");
+    TS_ASSERT_EQUALS(testAlg->version(), 2);
+  }
+
+  void test_castAlgorithm() {
+    // can create
+    boost::shared_ptr<Authenticate2> a;
+    TS_ASSERT(a = boost::make_shared<Authenticate2>());
+    // can cast to inherited interfaces and base classes
+
+    TS_ASSERT(dynamic_cast<Mantid::RemoteAlgorithms::Authenticate2 *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::API::Algorithm *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::Kernel::PropertyManagerOwner *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::API::IAlgorithm *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::Kernel::IPropertyManager *>(a.get()));
+  }
+
+  void test_init() {
+    if (!testAlg->isInitialized())
+      TS_ASSERT_THROWS_NOTHING(testAlg->initialize());
+
+    TS_ASSERT(testAlg->isInitialized());
+
+    Authenticate2 auth;
+    TS_ASSERT_THROWS_NOTHING(auth.initialize());
+  }
+
+  // TODO: when we have a RemoteJobManager capable of creating
+  // algorithms for different types of compute resources (example:
+  // Fermi@SNS and SCARF@STFC), create different algorithms for them
+  void test_propertiesMissing() {
+    Authenticate2 alg1;
+    TS_ASSERT_THROWS_NOTHING(alg1.initialize());
+    // password missing
+    TS_ASSERT_THROWS_NOTHING(alg1.setPropertyValue("UserName", "john_missing"));
+    TS_ASSERT_THROWS(alg1.setPropertyValue("ComputeResource", "missing!"),
+                     std::invalid_argument);
+
+    TS_ASSERT_THROWS(alg1.execute(), std::runtime_error);
+    TS_ASSERT(!alg1.isExecuted());
+
+    Authenticate2 alg2;
+    TS_ASSERT_THROWS_NOTHING(alg2.initialize());
+    // username missing
+    TS_ASSERT_THROWS_NOTHING(alg2.setPropertyValue("Password", "LogIn"));
+    TS_ASSERT_THROWS(alg2.setPropertyValue("ComputeResource", "missing!"),
+                     std::invalid_argument);
+
+    TS_ASSERT_THROWS(alg2.execute(), std::runtime_error);
+    TS_ASSERT(!alg2.isExecuted());
+
+    Authenticate2 alg3;
+    TS_ASSERT_THROWS_NOTHING(alg3.initialize());
+    // compute resource missing
+    TS_ASSERT_THROWS_NOTHING(alg3.setPropertyValue("UserName", "john_missing"));
+    TS_ASSERT_THROWS_NOTHING(alg3.setPropertyValue("Password", "LogIn"));
+
+    TS_ASSERT_THROWS(alg3.execute(), std::runtime_error);
+    TS_ASSERT(!alg3.isExecuted());
+  }
+
+  void test_wrongProperty() {
+    Authenticate2 auth;
+    TS_ASSERT_THROWS_NOTHING(auth.initialize());
+    TS_ASSERT_THROWS(auth.setPropertyValue("usernam", "anything"),
+                     std::runtime_error);
+    TS_ASSERT_THROWS(auth.setPropertyValue("sername", "anything"),
+                     std::runtime_error);
+    TS_ASSERT_THROWS(auth.setPropertyValue("Passwo", "anything"),
+                     std::runtime_error);
+  }
+
+  void test_propertiesOK() {
+    testFacilities.push_back(std::make_pair("SNS", "Fermi"));
+    testFacilities.push_back(std::make_pair("ISIS", "SCARF@STFC"));
+
+    const Mantid::Kernel::FacilityInfo &prevFac =
+        Mantid::Kernel::ConfigService::Instance().getFacility();
+    for (size_t fi = 0; fi < testFacilities.size(); fi++) {
+      const std::string facName = testFacilities[fi].first;
+      const std::string compName = testFacilities[fi].second;
+
+      Mantid::Kernel::ConfigService::Instance().setFacility(facName);
+      Authenticate2 auth;
+      TS_ASSERT_THROWS_NOTHING(auth.initialize());
+      TS_ASSERT_THROWS_NOTHING(
+          auth.setPropertyValue("ComputeResource", compName));
+      TS_ASSERT_THROWS_NOTHING(
+          auth.setPropertyValue("UserName", "john_missing"));
+      TS_ASSERT_THROWS_NOTHING(auth.setPropertyValue("Password", "LogIn"));
+      // TODO: this would run the algorithm and do a remote
+      // connection. uncomment only when/if we have a mock up for this
+      // TS_ASSERT_THROWS(auth.execute(), std::exception);
+      TS_ASSERT(!auth.isExecuted());
+    }
+    Mantid::Kernel::ConfigService::Instance().setFacility(prevFac.name());
+  }
+
+  // TODO: void test_runOK() - with a mock when we can add it.
+  // ideally, with different compute resources to check the remote job
+  // manager factory, etc.
+
+private:
+  Mantid::API::IAlgorithm_sptr testAlg;
+  std::vector<std::pair<std::string, std::string>> testFacilities;
+};
+
+#endif // MANTID_REMOTEALGORITHMS_AUTHENTICATE2TEST_H_
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/test/AuthenticateTest.h b/Code/Mantid/Framework/RemoteAlgorithms/test/AuthenticateTest.h
index dc848cc4d5bdd6483697b8274e69af413de8444d..c604658982ace513ecb5e8e37f6f5098cdcf0734 100644
--- a/Code/Mantid/Framework/RemoteAlgorithms/test/AuthenticateTest.h
+++ b/Code/Mantid/Framework/RemoteAlgorithms/test/AuthenticateTest.h
@@ -18,8 +18,8 @@ public:
   static void destroySuite(AuthenticateTest *suite) { delete suite; }
 
   void test_algorithm() {
-    testAlg = Mantid::API::AlgorithmManager::Instance().create(
-        "Authenticate" /*, 1*/);
+    testAlg =
+        Mantid::API::AlgorithmManager::Instance().create("Authenticate", 1);
     TS_ASSERT(testAlg);
     TS_ASSERT_EQUALS(testAlg->name(), "Authenticate");
     TS_ASSERT_EQUALS(testAlg->version(), 1);
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/test/DownloadRemoteFile2Test.h b/Code/Mantid/Framework/RemoteAlgorithms/test/DownloadRemoteFile2Test.h
new file mode 100644
index 0000000000000000000000000000000000000000..182edc900072fa14bff8bd10d872f3095573bfe5
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/test/DownloadRemoteFile2Test.h
@@ -0,0 +1,137 @@
+#ifndef MANTID_REMOTEALGORITHMS_DOWNLOADREMOTEFILE2TEST_H_
+#define MANTID_REMOTEALGORITHMS_DOWNLOADREMOTEFILE2TEST_H_
+
+#include <cxxtest/TestSuite.h>
+
+#include "MantidAPI/AlgorithmManager.h"
+#include "MantidKernel/ConfigService.h"
+#include "MantidKernel/FacilityInfo.h"
+#include "MantidRemoteAlgorithms/DownloadRemoteFile2.h"
+
+using namespace Mantid::RemoteAlgorithms;
+
+class DownloadRemoteFile2Test : public CxxTest::TestSuite {
+public:
+  // This pair of boilerplate methods prevent the suite being created statically
+  // This means the constructor isn't called when running other tests
+  static DownloadRemoteFile2Test *createSuite() {
+    return new DownloadRemoteFile2Test();
+  }
+  static void destroySuite(DownloadRemoteFile2Test *suite) { delete suite; }
+
+  void test_algorithm() {
+    testAlg = Mantid::API::AlgorithmManager::Instance().create(
+        "DownloadRemoteFile" /*, 2*/);
+    TS_ASSERT(testAlg);
+    TS_ASSERT_EQUALS(testAlg->name(), "DownloadRemoteFile");
+    TS_ASSERT_EQUALS(testAlg->version(), 2);
+  }
+
+  void test_castAlgorithm() {
+    // can create
+    boost::shared_ptr<DownloadRemoteFile2> a;
+    TS_ASSERT(a = boost::make_shared<DownloadRemoteFile2>());
+
+    // can cast to inherited interfaces and base classes
+    TS_ASSERT(
+        dynamic_cast<Mantid::RemoteAlgorithms::DownloadRemoteFile2 *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::API::Algorithm *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::Kernel::PropertyManagerOwner *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::API::IAlgorithm *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::Kernel::IPropertyManager *>(a.get()));
+  }
+
+  void test_init() {
+    if (!testAlg->isInitialized())
+      TS_ASSERT_THROWS_NOTHING(testAlg->initialize());
+
+    TS_ASSERT(testAlg->isInitialized());
+
+    DownloadRemoteFile2 dl;
+    TS_ASSERT_THROWS_NOTHING(dl.initialize());
+  }
+
+  // TODO: when we have a RemoteJobManager capable of creating
+  // algorithms for different types of compute resources (example:
+  // Fermi@SNS and SCARF@STFC), create different algorithms for them
+  void test_propertiesMissing() {
+    DownloadRemoteFile2 alg1;
+    TS_ASSERT_THROWS_NOTHING(alg1.initialize());
+    // Transaction id missing
+    TS_ASSERT_THROWS(alg1.setPropertyValue("ComputeResource", "missing!"),
+                     std::invalid_argument);
+    TS_ASSERT_THROWS_NOTHING(
+        alg1.setPropertyValue("RemoteFileName", "file name"));
+
+    TS_ASSERT_THROWS(alg1.execute(), std::runtime_error);
+    TS_ASSERT(!alg1.isExecuted());
+
+    DownloadRemoteFile2 alg2;
+    TS_ASSERT_THROWS_NOTHING(alg2.initialize());
+    // file name missing
+    TS_ASSERT_THROWS(alg2.setPropertyValue("ComputeResource", "missing!"),
+                     std::invalid_argument);
+    TS_ASSERT_THROWS_NOTHING(alg2.setPropertyValue("TransactionID", "id001"));
+
+    TS_ASSERT_THROWS(alg2.execute(), std::runtime_error);
+    TS_ASSERT(!alg2.isExecuted());
+
+    DownloadRemoteFile2 alg3;
+    TS_ASSERT_THROWS_NOTHING(alg3.initialize());
+    // compute resource missing
+    TS_ASSERT_THROWS_NOTHING(
+        alg3.setPropertyValue("RemoteFileName", "file name"));
+    TS_ASSERT_THROWS_NOTHING(alg3.setPropertyValue("TransactionID", "id001"));
+
+    TS_ASSERT_THROWS(alg3.execute(), std::runtime_error);
+    TS_ASSERT(!alg3.isExecuted());
+  }
+
+  void test_wrongProperty() {
+    DownloadRemoteFile2 dl;
+    TS_ASSERT_THROWS_NOTHING(dl.initialize();)
+    TS_ASSERT_THROWS(dl.setPropertyValue("Compute", "anything"),
+                     std::runtime_error);
+    TS_ASSERT_THROWS(dl.setPropertyValue("TransID", "anything"),
+                     std::runtime_error);
+    TS_ASSERT_THROWS(dl.setPropertyValue("FileName", "anything"),
+                     std::runtime_error);
+  }
+
+  void test_propertiesOK() {
+    testFacilities.push_back(std::make_pair("SNS", "Fermi"));
+    testFacilities.push_back(std::make_pair("ISIS", "SCARF@STFC"));
+
+    const Mantid::Kernel::FacilityInfo &prevFac =
+        Mantid::Kernel::ConfigService::Instance().getFacility();
+    for (size_t fi = 0; fi < testFacilities.size(); fi++) {
+      const std::string facName = testFacilities[fi].first;
+      const std::string compName = testFacilities[fi].second;
+
+      Mantid::Kernel::ConfigService::Instance().setFacility(facName);
+      DownloadRemoteFile2 dl;
+      TS_ASSERT_THROWS_NOTHING(dl.initialize());
+      TS_ASSERT_THROWS_NOTHING(
+          dl.setPropertyValue("ComputeResource", compName));
+      TS_ASSERT_THROWS_NOTHING(
+          dl.setPropertyValue("TransactionID", "anything"));
+      TS_ASSERT_THROWS_NOTHING(
+          dl.setPropertyValue("RemoteFileName", "anything"));
+      // TODO: this would run the algorithm and do a remote
+      // connection. uncomment only when/if we have a mock up for this
+      // TS_ASSERT_THROWS(dl.execute(), std::exception);
+      TS_ASSERT(!dl.isExecuted());
+    }
+    Mantid::Kernel::ConfigService::Instance().setFacility(prevFac.name());
+  }
+
+  // TODO: void test_runOK() - with a mock when we can add it.
+  // ideally, with different compute resources to check the remote job
+  // manager factory, etc.
+
+private:
+  Mantid::API::IAlgorithm_sptr testAlg;
+  std::vector<std::pair<std::string, std::string>> testFacilities;
+};
+
+#endif // MANTID_REMOTEALGORITHMS_DOWNLOADREMOTEFILE2TEST_H_
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/test/DownloadRemoteFileTest.h b/Code/Mantid/Framework/RemoteAlgorithms/test/DownloadRemoteFileTest.h
index 2431b4d9ae3d5c61fa2b488eb93f6ade67d961e1..30f2ab7e6e197af5d9f21fb00e54917d7494159b 100644
--- a/Code/Mantid/Framework/RemoteAlgorithms/test/DownloadRemoteFileTest.h
+++ b/Code/Mantid/Framework/RemoteAlgorithms/test/DownloadRemoteFileTest.h
@@ -21,7 +21,7 @@ public:
 
   void test_algorithm() {
     testAlg = Mantid::API::AlgorithmManager::Instance().create(
-        "DownloadRemoteFile" /*, 1*/);
+        "DownloadRemoteFile", 1);
     TS_ASSERT(testAlg);
     TS_ASSERT_EQUALS(testAlg->name(), "DownloadRemoteFile");
     TS_ASSERT_EQUALS(testAlg->version(), 1);
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/test/QueryAllRemoteJobs2Test.h b/Code/Mantid/Framework/RemoteAlgorithms/test/QueryAllRemoteJobs2Test.h
new file mode 100644
index 0000000000000000000000000000000000000000..8f78b708b3bb3a0470277a021ea66218a4552869
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/test/QueryAllRemoteJobs2Test.h
@@ -0,0 +1,110 @@
+#ifndef MANTID_REMOTEALGORITHMS_QUERYALLREMOTEJOBS2TEST_H_
+#define MANTID_REMOTEALGORITHMS_QUERYALLREMOTEJOBS2TEST_H_
+
+#include <cxxtest/TestSuite.h>
+
+#include "MantidAPI/AlgorithmManager.h"
+#include "MantidKernel/ConfigService.h"
+#include "MantidKernel/FacilityInfo.h"
+#include "MantidRemoteAlgorithms/QueryAllRemoteJobs2.h"
+
+using namespace Mantid::RemoteAlgorithms;
+
+class QueryAllRemoteJobs2Test : public CxxTest::TestSuite {
+public:
+  // This pair of boilerplate methods prevent the suite being created statically
+  // This means the constructor isn't called when running other tests
+  static QueryAllRemoteJobs2Test *createSuite() {
+    return new QueryAllRemoteJobs2Test();
+  }
+  static void destroySuite(QueryAllRemoteJobs2Test *suite) { delete suite; }
+
+  void test_algorithm() {
+    testAlg = Mantid::API::AlgorithmManager::Instance().create(
+        "QueryAllRemoteJobs" /*, 2*/);
+    TS_ASSERT(testAlg);
+    TS_ASSERT_EQUALS(testAlg->name(), "QueryAllRemoteJobs");
+    TS_ASSERT_EQUALS(testAlg->version(), 2);
+  }
+
+  void test_castAlgorithm() {
+    // can create
+    boost::shared_ptr<QueryAllRemoteJobs2> a;
+    TS_ASSERT(a = boost::make_shared<QueryAllRemoteJobs2>());
+
+    // can cast to inherited interfaces and base classes
+    TS_ASSERT(
+        dynamic_cast<Mantid::RemoteAlgorithms::QueryAllRemoteJobs2 *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::API::Algorithm *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::Kernel::PropertyManagerOwner *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::API::IAlgorithm *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::Kernel::IPropertyManager *>(a.get()));
+  }
+
+  void test_init() {
+    if (!testAlg->isInitialized())
+      TS_ASSERT_THROWS_NOTHING(testAlg->initialize());
+
+    TS_ASSERT(testAlg->isInitialized());
+
+    QueryAllRemoteJobs2 qar;
+    TS_ASSERT_THROWS_NOTHING(qar.initialize());
+  }
+
+  // TODO: when we have a RemoteJobManager capable of creating
+  // algorithms for different types of compute resources (example:
+  // Fermi@SNS and SCARF@STFC), create different algorithms for them
+  void test_propertiesMissing() {
+    QueryAllRemoteJobs2 qar;
+    TS_ASSERT_THROWS_NOTHING(qar.initialize());
+    // compute resource missing
+    TS_ASSERT_THROWS_NOTHING(qar.setPropertyValue("JobID", "john_missing"));
+
+    TS_ASSERT_THROWS(qar.execute(), std::runtime_error);
+    TS_ASSERT(!qar.isExecuted());
+  }
+
+  void test_wrongProperty() {
+    QueryAllRemoteJobs2 qar;
+    TS_ASSERT_THROWS_NOTHING(qar.initialize();)
+    TS_ASSERT_THROWS(qar.setPropertyValue("ComputeRes", "anything"),
+                     std::runtime_error);
+    TS_ASSERT_THROWS(qar.setPropertyValue("TransactionID", "whatever"),
+                     std::runtime_error);
+    TS_ASSERT_THROWS(qar.setPropertyValue("ID", "whichever"),
+                     std::runtime_error);
+  }
+
+  void test_propertiesOK() {
+    testFacilities.push_back(std::make_pair("SNS", "Fermi"));
+    testFacilities.push_back(std::make_pair("ISIS", "SCARF@STFC"));
+
+    const Mantid::Kernel::FacilityInfo &prevFac =
+        Mantid::Kernel::ConfigService::Instance().getFacility();
+    for (size_t fi = 0; fi < testFacilities.size(); fi++) {
+      const std::string facName = testFacilities[fi].first;
+      const std::string compName = testFacilities[fi].second;
+
+      Mantid::Kernel::ConfigService::Instance().setFacility(facName);
+      QueryAllRemoteJobs2 qar;
+      TS_ASSERT_THROWS_NOTHING(qar.initialize());
+      TS_ASSERT_THROWS_NOTHING(
+          qar.setPropertyValue("ComputeResource", compName));
+      // TODO: this would run the algorithm and do a remote
+      // connection. uncomment only when/if we have a mock up for this
+      // TS_ASSERT_THROWS(qar.execute(), std::exception);
+      TS_ASSERT(!qar.isExecuted());
+    }
+    Mantid::Kernel::ConfigService::Instance().setFacility(prevFac.name());
+  }
+
+  // TODO: void test_runOK() - with a mock when we can add it.
+  // ideally, with different compute resources to check the remote job
+  // manager factory, etc.
+
+private:
+  Mantid::API::IAlgorithm_sptr testAlg;
+  std::vector<std::pair<std::string, std::string>> testFacilities;
+};
+
+#endif // MANTID_REMOTEALGORITHMS_QUERYALLREMOTEJOBSTEST_H_
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/test/QueryAllRemoteJobsTest.h b/Code/Mantid/Framework/RemoteAlgorithms/test/QueryAllRemoteJobsTest.h
index 1ab456f1d45e980bb63d91161e4f5a1f6b391dae..5c3d747f8c0547e8c15dc8b1ae9b442c620db421 100644
--- a/Code/Mantid/Framework/RemoteAlgorithms/test/QueryAllRemoteJobsTest.h
+++ b/Code/Mantid/Framework/RemoteAlgorithms/test/QueryAllRemoteJobsTest.h
@@ -21,7 +21,7 @@ public:
 
   void test_algorithm() {
     testAlg = Mantid::API::AlgorithmManager::Instance().create(
-        "QueryAllRemoteJobs" /*, 1*/);
+        "QueryAllRemoteJobs", 1);
     TS_ASSERT(testAlg);
     TS_ASSERT_EQUALS(testAlg->name(), "QueryAllRemoteJobs");
     TS_ASSERT_EQUALS(testAlg->version(), 1);
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/test/QueryRemoteFile2Test.h b/Code/Mantid/Framework/RemoteAlgorithms/test/QueryRemoteFile2Test.h
new file mode 100644
index 0000000000000000000000000000000000000000..e369b9f4035b20c8b9f16d125cc48559d6675fb0
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/test/QueryRemoteFile2Test.h
@@ -0,0 +1,122 @@
+#ifndef MANTID_REMOTEALGORITHMS_QUERYREMOTEFILE2TEST_H_
+#define MANTID_REMOTEALGORITHMS_QUERYREMOTEFILE2TEST_H_
+
+#include <cxxtest/TestSuite.h>
+
+#include "MantidAPI/AlgorithmManager.h"
+#include "MantidKernel/ConfigService.h"
+#include "MantidKernel/FacilityInfo.h"
+#include "MantidRemoteAlgorithms/QueryRemoteFile2.h"
+
+using namespace Mantid::RemoteAlgorithms;
+
+class QueryRemoteFile2Test : public CxxTest::TestSuite {
+public:
+  // This pair of boilerplate methods prevent the suite being created statically
+  // This means the constructor isn't called when running other tests
+  static QueryRemoteFile2Test *createSuite() {
+    return new QueryRemoteFile2Test();
+  }
+  static void destroySuite(QueryRemoteFile2Test *suite) { delete suite; }
+
+  void test_algorithm() {
+    testAlg = Mantid::API::AlgorithmManager::Instance().create(
+        "QueryRemoteFile" /*, 2*/);
+    TS_ASSERT(testAlg);
+    TS_ASSERT_EQUALS(testAlg->name(), "QueryRemoteFile");
+    TS_ASSERT_EQUALS(testAlg->version(), 2);
+  }
+
+  void test_castAlgorithm() {
+    // can create
+    boost::shared_ptr<QueryRemoteFile2> a;
+    TS_ASSERT(a = boost::make_shared<QueryRemoteFile2>());
+
+    // can cast to inherited interfaces and base classes
+    TS_ASSERT(
+        dynamic_cast<Mantid::RemoteAlgorithms::QueryRemoteFile2 *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::API::Algorithm *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::Kernel::PropertyManagerOwner *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::API::IAlgorithm *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::Kernel::IPropertyManager *>(a.get()));
+  }
+
+  void test_init() {
+    if (!testAlg->isInitialized())
+      TS_ASSERT_THROWS_NOTHING(testAlg->initialize());
+
+    TS_ASSERT(testAlg->isInitialized());
+
+    QueryRemoteFile2 qrf;
+    TS_ASSERT_THROWS_NOTHING(qrf.initialize());
+  }
+
+  // TODO: when we have a RemoteJobManager capable of creating
+  // algorithms for different types of compute resources (example:
+  // Fermi@SNS and SCARF@STFC), create different algorithms for them
+  void test_propertiesMissing() {
+    QueryRemoteFile2 alg1;
+    TS_ASSERT_THROWS_NOTHING(alg1.initialize());
+    // Transaction id missing
+    TS_ASSERT_THROWS(alg1.setPropertyValue("ComputeResource", "missing!"),
+                     std::invalid_argument);
+
+    TS_ASSERT_THROWS(alg1.execute(), std::runtime_error);
+    TS_ASSERT(!alg1.isExecuted());
+
+    QueryRemoteFile2 alg2;
+    TS_ASSERT_THROWS_NOTHING(alg2.initialize());
+    // compute resource missing
+    TS_ASSERT_THROWS_NOTHING(
+        alg2.setPropertyValue("TransactionID", "trans0001"));
+
+    TS_ASSERT_THROWS(alg2.execute(), std::runtime_error);
+    TS_ASSERT(!alg2.isExecuted());
+  }
+
+  void test_wrongProperty() {
+    QueryRemoteFile2 qrf;
+    TS_ASSERT_THROWS_NOTHING(qrf.initialize();)
+    TS_ASSERT_THROWS(qrf.setPropertyValue("Compute", "anything"),
+                     std::runtime_error);
+    TS_ASSERT_THROWS(qrf.setPropertyValue("TransID", "anything"),
+                     std::runtime_error);
+    TS_ASSERT_THROWS(qrf.setPropertyValue("ComputeResourc", "anything"),
+                     std::runtime_error);
+  }
+
+  void test_propertiesOK() {
+    testFacilities.push_back(std::make_pair("SNS", "Fermi"));
+    testFacilities.push_back(std::make_pair("ISIS", "SCARF@STFC"));
+
+    const Mantid::Kernel::FacilityInfo &prevFac =
+        Mantid::Kernel::ConfigService::Instance().getFacility();
+    for (size_t fi = 0; fi < testFacilities.size(); fi++) {
+      const std::string facName = testFacilities[fi].first;
+      const std::string compName = testFacilities[fi].second;
+
+      Mantid::Kernel::ConfigService::Instance().setFacility(facName);
+      QueryRemoteFile2 qrf;
+      TS_ASSERT_THROWS_NOTHING(qrf.initialize());
+      TS_ASSERT_THROWS_NOTHING(
+          qrf.setPropertyValue("ComputeResource", compName));
+      TS_ASSERT_THROWS_NOTHING(
+          qrf.setPropertyValue("TransactionID", "anything001"));
+      // TODO: this would run the algorithm and do a remote
+      // connection. uncomment only when/if we have a mock up for this
+      // TS_ASSERT_THROWS(qrf.execute(), std::exception);
+      TS_ASSERT(!qrf.isExecuted());
+    }
+    Mantid::Kernel::ConfigService::Instance().setFacility(prevFac.name());
+  }
+
+  // TODO: void test_runOK() - with a mock when we can add it.
+  // ideally, with different compute resources to check the remote job
+  // manager factory, etc.
+
+private:
+  Mantid::API::IAlgorithm_sptr testAlg;
+  std::vector<std::pair<std::string, std::string>> testFacilities;
+};
+
+#endif // MANTID_REMOTEALGORITHMS_QUERYREMOTEFILE2TEST_H_
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/test/QueryRemoteFileTest.h b/Code/Mantid/Framework/RemoteAlgorithms/test/QueryRemoteFileTest.h
index 1635644164e8a3f59673f5156b7f9e32cfc1daaf..b82a3ff5eb85899563e41a65a4f929a63d717775 100644
--- a/Code/Mantid/Framework/RemoteAlgorithms/test/QueryRemoteFileTest.h
+++ b/Code/Mantid/Framework/RemoteAlgorithms/test/QueryRemoteFileTest.h
@@ -21,7 +21,7 @@ public:
 
   void test_algorithm() {
     testAlg = Mantid::API::AlgorithmManager::Instance().create(
-        "QueryRemoteFile" /*, 1*/);
+        "QueryRemoteFile", 1);
     TS_ASSERT(testAlg);
     TS_ASSERT_EQUALS(testAlg->name(), "QueryRemoteFile");
     TS_ASSERT_EQUALS(testAlg->version(), 1);
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/test/QueryRemoteJob2Test.h b/Code/Mantid/Framework/RemoteAlgorithms/test/QueryRemoteJob2Test.h
new file mode 100644
index 0000000000000000000000000000000000000000..a5c0fd2cc72330c90fef3eaad7f6562396926d49
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/test/QueryRemoteJob2Test.h
@@ -0,0 +1,118 @@
+#ifndef MANTID_REMOTEALGORITHMS_QUERYREMOTEJOBTEST_H_
+#define MANTID_REMOTEALGORITHMS_QUERYREMOTEJOBTEST_H_
+
+#include <cxxtest/TestSuite.h>
+
+#include "MantidAPI/AlgorithmManager.h"
+#include "MantidKernel/ConfigService.h"
+#include "MantidKernel/FacilityInfo.h"
+#include "MantidRemoteAlgorithms/QueryRemoteJob2.h"
+
+using namespace Mantid::RemoteAlgorithms;
+
+class QueryRemoteJob2Test : public CxxTest::TestSuite {
+public:
+  // This pair of boilerplate methods prevent the suite being created statically
+  // This means the constructor isn't called when running other tests
+  static QueryRemoteJob2Test *createSuite() { return new QueryRemoteJob2Test(); }
+  static void destroySuite(QueryRemoteJob2Test *suite) { delete suite; }
+
+  void test_algorithm() {
+    testAlg = Mantid::API::AlgorithmManager::Instance().create(
+        "QueryRemoteJob" /*, 2*/);
+    TS_ASSERT(testAlg);
+    TS_ASSERT_EQUALS(testAlg->name(), "QueryRemoteJob");
+    TS_ASSERT_EQUALS(testAlg->version(), 2);
+  }
+
+  void test_castAlgorithm() {
+    // can create
+    boost::shared_ptr<QueryRemoteJob2> a;
+    TS_ASSERT(a = boost::make_shared<QueryRemoteJob2>());
+
+    // can cast to inherited interfaces and base classes
+    TS_ASSERT(
+        dynamic_cast<Mantid::RemoteAlgorithms::QueryRemoteJob2 *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::API::Algorithm *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::Kernel::PropertyManagerOwner *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::API::IAlgorithm *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::Kernel::IPropertyManager *>(a.get()));
+  }
+
+  void test_init() {
+    if (!testAlg->isInitialized())
+      TS_ASSERT_THROWS_NOTHING(testAlg->initialize());
+
+    TS_ASSERT(testAlg->isInitialized());
+
+    QueryRemoteJob2 qr;
+    TS_ASSERT_THROWS_NOTHING(qr.initialize());
+  }
+
+  // TODO: when we have a RemoteJobManager capable of creating
+  // algorithms for different types of compute resources (example:
+  // Fermi@SNS and SCARF@STFC), create different algorithms for them
+  void test_propertiesMissing() {
+    QueryRemoteJob2 alg1;
+    TS_ASSERT_THROWS_NOTHING(alg1.initialize());
+    // id missing
+    TS_ASSERT_THROWS(alg1.setPropertyValue("ComputeResource", "missing!"),
+                     std::invalid_argument);
+
+    TS_ASSERT_THROWS(alg1.execute(), std::runtime_error);
+    TS_ASSERT(!alg1.isExecuted());
+
+    QueryRemoteJob2 alg2;
+    TS_ASSERT_THROWS_NOTHING(alg2.initialize());
+    // compute resource missing
+    TS_ASSERT_THROWS_NOTHING(alg2.setPropertyValue("JobID", "missing001"));
+
+    TS_ASSERT_THROWS(alg2.execute(), std::runtime_error);
+    TS_ASSERT(!alg2.isExecuted());
+  }
+
+  void test_wrongProperty() {
+    QueryRemoteJob2 qr;
+    TS_ASSERT_THROWS_NOTHING(qr.initialize();)
+    TS_ASSERT_THROWS(qr.setPropertyValue("job", "whatever"),
+                     std::runtime_error);
+    TS_ASSERT_THROWS(qr.setPropertyValue("id", "whichever"),
+                     std::runtime_error);
+    TS_ASSERT_THROWS(qr.setPropertyValue("ComputeRes", "anything"),
+                     std::runtime_error);
+  }
+
+  void test_propertiesOK() {
+    testFacilities.push_back(std::make_pair("SNS", "Fermi"));
+    testFacilities.push_back(std::make_pair("ISIS", "SCARF@STFC"));
+
+    const Mantid::Kernel::FacilityInfo &prevFac =
+        Mantid::Kernel::ConfigService::Instance().getFacility();
+    for (size_t fi = 0; fi < testFacilities.size(); fi++) {
+      const std::string facName = testFacilities[fi].first;
+      const std::string compName = testFacilities[fi].second;
+
+      Mantid::Kernel::ConfigService::Instance().setFacility(facName);
+      QueryRemoteJob2 qr;
+      TS_ASSERT_THROWS_NOTHING(qr.initialize());
+      TS_ASSERT_THROWS_NOTHING(
+          qr.setPropertyValue("ComputeResource", compName));
+      TS_ASSERT_THROWS_NOTHING(qr.setPropertyValue("JobID", "000001"));
+      // TODO: this would run the algorithm and do a remote
+      // connection. uncomment only when/if we have a mock up for this
+      // TS_ASSERT_THROWS(qr.execute(), std::exception);
+      TS_ASSERT(!qr.isExecuted());
+    }
+    Mantid::Kernel::ConfigService::Instance().setFacility(prevFac.name());
+  }
+
+  // TODO: void test_runOK() - with a mock when we can add it.
+  // ideally, with different compute resources to check the remote job
+  // manager factory, etc.
+
+private:
+  Mantid::API::IAlgorithm_sptr testAlg;
+  std::vector<std::pair<std::string, std::string>> testFacilities;
+};
+
+#endif // MANTID_REMOTEALGORITHMS_QUERYREMOTEJOBTEST_H_
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/test/QueryRemoteJobTest.h b/Code/Mantid/Framework/RemoteAlgorithms/test/QueryRemoteJobTest.h
index cdd9350bf9f5dbe6e501c15601be310e8fce84e4..6e4db4d73786bb89f49e4a5552e3bc2175f04999 100644
--- a/Code/Mantid/Framework/RemoteAlgorithms/test/QueryRemoteJobTest.h
+++ b/Code/Mantid/Framework/RemoteAlgorithms/test/QueryRemoteJobTest.h
@@ -18,8 +18,8 @@ public:
   static void destroySuite(QueryRemoteJobTest *suite) { delete suite; }
 
   void test_algorithm() {
-    testAlg = Mantid::API::AlgorithmManager::Instance().create(
-        "QueryRemoteJob" /*, 1*/);
+    testAlg =
+        Mantid::API::AlgorithmManager::Instance().create("QueryRemoteJob", 1);
     TS_ASSERT(testAlg);
     TS_ASSERT_EQUALS(testAlg->name(), "QueryRemoteJob");
     TS_ASSERT_EQUALS(testAlg->version(), 1);
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/test/StartRemoteTransaction2Test.h b/Code/Mantid/Framework/RemoteAlgorithms/test/StartRemoteTransaction2Test.h
new file mode 100644
index 0000000000000000000000000000000000000000..d81c8595b425b145db2c1fb250c9d32c952f2ec7
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/test/StartRemoteTransaction2Test.h
@@ -0,0 +1,122 @@
+#ifndef MANTID_REMOTEALGORITHMS_STARTREMOTETRANSACTION2TEST_H_
+#define MANTID_REMOTEALGORITHMS_STARTREMOTETRANSACTION2TEST_H_
+
+#include <cxxtest/TestSuite.h>
+
+#include "MantidAPI/AlgorithmManager.h"
+#include "MantidKernel/ConfigService.h"
+#include "MantidKernel/FacilityInfo.h"
+#include "MantidRemoteAlgorithms/StartRemoteTransaction2.h"
+
+using namespace Mantid::RemoteAlgorithms;
+
+class StartRemoteTransaction2Test : public CxxTest::TestSuite {
+public:
+  // This pair of boilerplate methods prevent the suite being created statically
+  // This means the constructor isn't called when running other tests
+  static StartRemoteTransaction2Test *createSuite() {
+    return new StartRemoteTransaction2Test();
+  }
+  static void destroySuite(StartRemoteTransaction2Test *suite) { delete suite; }
+
+  void test_algorithm() {
+    testAlg = Mantid::API::AlgorithmManager::Instance().create(
+        "StartRemoteTransaction", 2);
+    TS_ASSERT(testAlg);
+    TS_ASSERT_EQUALS(testAlg->name(), "StartRemoteTransaction");
+    TS_ASSERT_EQUALS(testAlg->version(), 2);
+  }
+
+  void test_castAlgorithm() {
+    // can create
+    boost::shared_ptr<StartRemoteTransaction2> a;
+    TS_ASSERT(a = boost::make_shared<StartRemoteTransaction2>());
+
+    // can cast to inherited interfaces and base classes
+    TS_ASSERT(dynamic_cast<Mantid::RemoteAlgorithms::StartRemoteTransaction2 *>(
+        a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::API::Algorithm *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::Kernel::PropertyManagerOwner *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::API::IAlgorithm *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::Kernel::IPropertyManager *>(a.get()));
+  }
+
+  void test_init() {
+    if (!testAlg->isInitialized())
+      TS_ASSERT_THROWS_NOTHING(testAlg->initialize());
+
+    TS_ASSERT(testAlg->isInitialized());
+
+    StartRemoteTransaction2 start;
+    TS_ASSERT_THROWS_NOTHING(start.initialize());
+  }
+
+  // TODO: when we have a RemoteJobManager capable of creating
+  // algorithms for different types of compute resources (example:
+  // Fermi@SNS and SCARF@STFC), create different algorithms for them
+  void test_propertiesMissing() {
+    StartRemoteTransaction2 alg1;
+    TS_ASSERT_THROWS_NOTHING(alg1.initialize());
+    // id missing
+    TS_ASSERT_THROWS(alg1.setPropertyValue("ComputeResource", "missing!"),
+                     std::invalid_argument);
+
+    TS_ASSERT_THROWS(alg1.execute(), std::runtime_error);
+    TS_ASSERT(!alg1.isExecuted());
+
+    StartRemoteTransaction2 alg2;
+    TS_ASSERT_THROWS_NOTHING(alg2.initialize());
+    // compute resource missing
+    TS_ASSERT_THROWS_NOTHING(
+        alg2.setPropertyValue("TransactionID", "john_missing"));
+
+    TS_ASSERT_THROWS(alg2.execute(), std::runtime_error);
+    TS_ASSERT(!alg2.isExecuted());
+  }
+
+  void test_wrongProperty() {
+    StartRemoteTransaction2 start;
+    TS_ASSERT_THROWS_NOTHING(start.initialize();)
+    TS_ASSERT_THROWS(start.setPropertyValue("Compute", "anything"),
+                     std::runtime_error);
+    TS_ASSERT_THROWS(start.setPropertyValue("Transaction", "whatever"),
+                     std::runtime_error);
+    TS_ASSERT_THROWS(start.setPropertyValue("ID", "whichever"),
+                     std::runtime_error);
+  }
+
+  void test_propertiesOK() {
+    testFacilities.push_back(std::make_pair("SNS", "Fermi"));
+    testFacilities.push_back(std::make_pair("ISIS", "SCARF@STFC"));
+
+    const Mantid::Kernel::FacilityInfo &prevFac =
+        Mantid::Kernel::ConfigService::Instance().getFacility();
+    for (size_t fi = 0; fi < testFacilities.size(); fi++) {
+      const std::string facName = testFacilities[fi].first;
+      const std::string compName = testFacilities[fi].second;
+
+      Mantid::Kernel::ConfigService::Instance().setFacility(facName);
+      StartRemoteTransaction2 start;
+      TS_ASSERT_THROWS_NOTHING(start.initialize());
+      TS_ASSERT_THROWS_NOTHING(
+          start.setPropertyValue("ComputeResource", compName));
+      TS_ASSERT_THROWS_NOTHING(
+          start.setPropertyValue("TransactionID", "000001"));
+      // TODO: this would run the algorithm and do a remote
+      // connection. uncomment only when/if we have a mock up for this
+      // TS_ASSERT_THROWS(start.execute(), std::exception);
+      TS_ASSERT(!start.isExecuted());
+    }
+    Mantid::Kernel::ConfigService::Instance().setFacility(prevFac.name());
+  }
+
+  // TODO: void test_runOK() - with a mock when we can add it.
+  // ideally, with different compute resources to check the remote job
+  // manager factory, etc.
+
+private:
+  Mantid::API::IAlgorithm_sptr testAlg;
+  std::vector<std::pair<std::string, std::string>> testFacilities;
+};
+
+#endif // MANTID_REMOTEALGORITHMS_STARTREMOTETRANSACTION2TEST_H_
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/test/StartRemoteTransactionTest.h b/Code/Mantid/Framework/RemoteAlgorithms/test/StartRemoteTransactionTest.h
index aa6086d8431302942c6713bdee0cb8d46df00d55..6fabd7b8ade12ce140f4bd627f1740949d4f24a1 100644
--- a/Code/Mantid/Framework/RemoteAlgorithms/test/StartRemoteTransactionTest.h
+++ b/Code/Mantid/Framework/RemoteAlgorithms/test/StartRemoteTransactionTest.h
@@ -21,7 +21,7 @@ public:
 
   void test_algorithm() {
     testAlg = Mantid::API::AlgorithmManager::Instance().create(
-        "StartRemoteTransaction" /*, 1*/);
+        "StartRemoteTransaction", 1);
     TS_ASSERT(testAlg);
     TS_ASSERT_EQUALS(testAlg->name(), "StartRemoteTransaction");
     TS_ASSERT_EQUALS(testAlg->version(), 1);
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/test/StopRemoteTransaction2Test.h b/Code/Mantid/Framework/RemoteAlgorithms/test/StopRemoteTransaction2Test.h
new file mode 100644
index 0000000000000000000000000000000000000000..6de11b7433ab05bcea1958876544cb343dab8035
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/test/StopRemoteTransaction2Test.h
@@ -0,0 +1,124 @@
+#ifndef MANTID_REMOTEALGORITHMS_STOPREMOTETRANSACTIONTEST_H_
+#define MANTID_REMOTEALGORITHMS_STOPREMOTETRANSACTIONTEST_H_
+
+#include <cxxtest/TestSuite.h>
+
+#include "MantidAPI/AlgorithmManager.h"
+#include "MantidKernel/ConfigService.h"
+#include "MantidKernel/FacilityInfo.h"
+#include "MantidRemoteAlgorithms/StopRemoteTransaction2.h"
+
+using namespace Mantid::RemoteAlgorithms;
+
+class StopRemoteTransaction2Test : public CxxTest::TestSuite {
+public:
+  // This pair of boilerplate methods prevent the suite being created statically
+  // This means the constructor isn't called when running other tests
+  static StopRemoteTransaction2Test *createSuite() {
+    return new StopRemoteTransaction2Test();
+  }
+  static void destroySuite(StopRemoteTransaction2Test *suite) { delete suite; }
+
+  void test_algorithm() {
+    testAlg = Mantid::API::AlgorithmManager::Instance().create(
+        "StopRemoteTransaction" /*, 2*/);
+    TS_ASSERT(testAlg);
+    TS_ASSERT_EQUALS(testAlg->name(), "StopRemoteTransaction");
+    TS_ASSERT_EQUALS(testAlg->version(), 2);
+  }
+
+  void test_castAlgorithm() {
+    // can create
+    boost::shared_ptr<StopRemoteTransaction2> a;
+    TS_ASSERT(a = boost::make_shared<StopRemoteTransaction2>());
+
+    // can cast to inherited interfaces and base classes
+    TS_ASSERT(dynamic_cast<Mantid::RemoteAlgorithms::StopRemoteTransaction2 *>(
+        a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::API::Algorithm *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::Kernel::PropertyManagerOwner *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::API::IAlgorithm *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::Kernel::IPropertyManager *>(a.get()));
+  }
+
+  void test_init() {
+    if (!testAlg->isInitialized())
+      TS_ASSERT_THROWS_NOTHING(testAlg->initialize());
+
+    TS_ASSERT(testAlg->isInitialized());
+
+    StopRemoteTransaction2 stop;
+    TS_ASSERT_THROWS_NOTHING(stop.initialize());
+  }
+
+  // TODO: when we have a RemoteJobManager capable of creating
+  // algorithms for different types of compute resources (example:
+  // Fermi@SNS and SCARF@STFC), create different algorithms for them
+  void test_propertiesMissing() {
+    StopRemoteTransaction2 alg1;
+    TS_ASSERT_THROWS_NOTHING(alg1.initialize());
+    // transaction id missing
+    TS_ASSERT_THROWS(alg1.setPropertyValue("ComputeResource", "missing!"),
+                     std::invalid_argument);
+
+    TS_ASSERT_THROWS(alg1.execute(), std::runtime_error);
+    TS_ASSERT(!alg1.isExecuted());
+
+    StopRemoteTransaction2 alg2;
+    TS_ASSERT_THROWS_NOTHING(alg2.initialize());
+    // compute resource missing
+    TS_ASSERT_THROWS_NOTHING(
+        alg2.setPropertyValue("TransactionID", "john_missing"));
+
+    TS_ASSERT_THROWS(alg2.execute(), std::runtime_error);
+    TS_ASSERT(!alg2.isExecuted());
+  }
+
+  void test_wrongProperty() {
+    StopRemoteTransaction2 stop;
+    TS_ASSERT_THROWS_NOTHING(stop.initialize();)
+    TS_ASSERT_THROWS(stop.setPropertyValue("Compute", "anything"),
+                     std::runtime_error);
+    TS_ASSERT_THROWS(stop.setPropertyValue("Transaction", "whatever"),
+                     std::runtime_error);
+    TS_ASSERT_THROWS(stop.setPropertyValue("JobID", "whichever"),
+                     std::runtime_error);
+    TS_ASSERT_THROWS(stop.setPropertyValue("ID", "whichever"),
+                     std::runtime_error);
+  }
+
+  void test_propertiesOK() {
+    testFacilities.push_back(std::make_pair("SNS", "Fermi"));
+    testFacilities.push_back(std::make_pair("ISIS", "SCARF@STFC"));
+
+    const Mantid::Kernel::FacilityInfo &prevFac =
+        Mantid::Kernel::ConfigService::Instance().getFacility();
+    for (size_t fi = 0; fi < testFacilities.size(); fi++) {
+      const std::string facName = testFacilities[fi].first;
+      const std::string compName = testFacilities[fi].second;
+
+      Mantid::Kernel::ConfigService::Instance().setFacility(facName);
+      StopRemoteTransaction2 stop;
+      TS_ASSERT_THROWS_NOTHING(stop.initialize());
+      TS_ASSERT_THROWS_NOTHING(
+          stop.setPropertyValue("ComputeResource", compName));
+      TS_ASSERT_THROWS_NOTHING(
+          stop.setPropertyValue("TransactionID", "000001"));
+      // TODO: this would run the algorithm and do a remote
+      // connection. uncomment only when/if we have a mock up for this
+      // TS_ASSERT_THROWS(stop.execute(), std::exception);
+      TS_ASSERT(!stop.isExecuted());
+    }
+    Mantid::Kernel::ConfigService::Instance().setFacility(prevFac.name());
+  }
+
+  // TODO: void test_runOK() - with a mock when we can add it.
+  // ideally, with different compute resources to check the remote job
+  // manager factory, etc.
+
+private:
+  Mantid::API::IAlgorithm_sptr testAlg;
+  std::vector<std::pair<std::string, std::string>> testFacilities;
+};
+
+#endif // MANTID_REMOTEALGORITHMS_STOPREMOTETRANSACTIONTEST_H_
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/test/StopRemoteTransactionTest.h b/Code/Mantid/Framework/RemoteAlgorithms/test/StopRemoteTransactionTest.h
index 52555a72e3f6b005ad75c907bf0618bb3491d47e..97746f958dec44185c1b2bf502d8c58b6b5ba737 100644
--- a/Code/Mantid/Framework/RemoteAlgorithms/test/StopRemoteTransactionTest.h
+++ b/Code/Mantid/Framework/RemoteAlgorithms/test/StopRemoteTransactionTest.h
@@ -21,7 +21,7 @@ public:
 
   void test_algorithm() {
     testAlg = Mantid::API::AlgorithmManager::Instance().create(
-        "StopRemoteTransaction" /*, 1*/);
+        "StopRemoteTransaction", 1);
     TS_ASSERT(testAlg);
     TS_ASSERT_EQUALS(testAlg->name(), "StopRemoteTransaction");
     TS_ASSERT_EQUALS(testAlg->version(), 1);
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/test/SubmitRemoteJob2Test.h b/Code/Mantid/Framework/RemoteAlgorithms/test/SubmitRemoteJob2Test.h
new file mode 100644
index 0000000000000000000000000000000000000000..6b9394540e26ec9851250dfa1a150992d0f737ae
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/test/SubmitRemoteJob2Test.h
@@ -0,0 +1,193 @@
+#ifndef MANTID_REMOTEALGORITHMS_SUBMITREMOTEJOBTEST_H_
+#define MANTID_REMOTEALGORITHMS_SUBMITREMOTEJOBTEST_H_
+
+#include <cxxtest/TestSuite.h>
+
+#include "MantidAPI/AlgorithmManager.h"
+#include "MantidKernel/ConfigService.h"
+#include "MantidKernel/FacilityInfo.h"
+#include "MantidRemoteAlgorithms/SubmitRemoteJob2.h"
+
+using namespace Mantid::RemoteAlgorithms;
+
+class SubmitRemoteJob2Test : public CxxTest::TestSuite {
+public:
+  // This pair of boilerplate methods prevent the suite being created statically
+  // This means the constructor isn't called when running other tests
+  static SubmitRemoteJob2Test *createSuite() {
+    return new SubmitRemoteJob2Test();
+  }
+  static void destroySuite(SubmitRemoteJob2Test *suite) { delete suite; }
+
+  void test_algorithm() {
+    testAlg = Mantid::API::AlgorithmManager::Instance().create(
+        "SubmitRemoteJob" /*, 2*/);
+    TS_ASSERT(testAlg);
+    TS_ASSERT_EQUALS(testAlg->name(), "SubmitRemoteJob");
+    TS_ASSERT_EQUALS(testAlg->version(), 2);
+  }
+
+  void test_castAlgorithm() {
+    // can create
+    boost::shared_ptr<SubmitRemoteJob2> a;
+    TS_ASSERT(a = boost::make_shared<SubmitRemoteJob2>());
+
+    // can cast to inherited interfaces and base classes
+    TS_ASSERT(
+        dynamic_cast<Mantid::RemoteAlgorithms::SubmitRemoteJob2 *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::API::Algorithm *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::Kernel::PropertyManagerOwner *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::API::IAlgorithm *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::Kernel::IPropertyManager *>(a.get()));
+  }
+
+  void test_init() {
+    if (!testAlg->isInitialized())
+      TS_ASSERT_THROWS_NOTHING(testAlg->initialize());
+
+    TS_ASSERT(testAlg->isInitialized());
+
+    SubmitRemoteJob2 s;
+    TS_ASSERT_THROWS_NOTHING(s.initialize());
+  }
+
+  // TODO: when we have a RemoteJobManager capable of creating
+  // algorithms for different types of compute resources (example:
+  // Fermi@SNS and SCARF@STFC), create different algorithms for them
+  void test_propertiesMissing() {
+    SubmitRemoteJob2 alg1;
+    TS_ASSERT_THROWS_NOTHING(alg1.initialize());
+    // Transaction id missing
+    TS_ASSERT_THROWS_NOTHING(alg1.setPropertyValue("NumNodes", "1"));
+    TS_ASSERT_THROWS_NOTHING(alg1.setPropertyValue("CoresPerNode", "4"));
+    TS_ASSERT_THROWS_NOTHING(alg1.setPropertyValue("TaskName", "unit test"));
+    TS_ASSERT_THROWS_NOTHING(
+        alg1.setPropertyValue("ScriptName", "test script"));
+    TS_ASSERT_THROWS_NOTHING(
+        alg1.setPropertyValue("ScriptParams", "print 'hello world'"));
+    TS_ASSERT_THROWS(alg1.setPropertyValue("ComputeResource", "missing!"),
+                     std::invalid_argument);
+
+    TS_ASSERT_THROWS(alg1.execute(), std::runtime_error);
+    TS_ASSERT(!alg1.isExecuted());
+
+    SubmitRemoteJob2 alg2;
+    TS_ASSERT_THROWS_NOTHING(alg2.initialize());
+    // task name name missing
+    TS_ASSERT_THROWS(alg2.setPropertyValue("ComputeResource", "missing!"),
+                     std::invalid_argument);
+    TS_ASSERT_THROWS_NOTHING(alg2.setPropertyValue("TransactionID", "id001"));
+    TS_ASSERT_THROWS_NOTHING(
+        alg2.setPropertyValue("ScriptName", "test script"));
+    TS_ASSERT_THROWS_NOTHING(
+        alg2.setPropertyValue("ScriptParams", "print 'hello world'"));
+
+    TS_ASSERT_THROWS(alg2.execute(), std::runtime_error);
+    TS_ASSERT(!alg2.isExecuted());
+
+    SubmitRemoteJob2 alg3;
+    TS_ASSERT_THROWS_NOTHING(alg3.initialize());
+    // script name name missing
+    TS_ASSERT_THROWS_NOTHING(alg3.setPropertyValue("TaskName", "unit test"));
+    TS_ASSERT_THROWS_NOTHING(alg3.setPropertyValue("TransactionID", "id001"));
+    TS_ASSERT_THROWS_NOTHING(
+        alg3.setPropertyValue("ScriptParams", "print 'hello world'"));
+    TS_ASSERT_THROWS(alg3.setPropertyValue("ComputeResource", "missing!"),
+                     std::invalid_argument);
+
+    TS_ASSERT_THROWS(alg3.execute(), std::runtime_error);
+    TS_ASSERT(!alg3.isExecuted());
+
+    SubmitRemoteJob2 alg4;
+    TS_ASSERT_THROWS_NOTHING(alg4.initialize());
+    // compute resource missing
+    TS_ASSERT_THROWS_NOTHING(alg4.setPropertyValue("TransactionID", "id001"));
+    TS_ASSERT_THROWS_NOTHING(alg4.setPropertyValue("TaskName", "unit test"));
+    TS_ASSERT_THROWS_NOTHING(
+        alg4.setPropertyValue("ScriptName", "test script"));
+    TS_ASSERT_THROWS_NOTHING(
+        alg4.setPropertyValue("ScriptParams", "print 'hello world'"));
+
+    TS_ASSERT_THROWS(alg4.execute(), std::runtime_error);
+    TS_ASSERT(!alg4.isExecuted());
+
+    SubmitRemoteJob2 alg5;
+    TS_ASSERT_THROWS_NOTHING(alg5.initialize());
+    // py script missing
+    TS_ASSERT_THROWS_NOTHING(alg5.setPropertyValue("TransactionID", "id001"));
+    TS_ASSERT_THROWS_NOTHING(alg5.setPropertyValue("TaskName", "unit test"));
+    TS_ASSERT_THROWS_NOTHING(
+        alg5.setPropertyValue("ScriptName", "test script"));
+    TS_ASSERT_THROWS(alg5.setPropertyValue("ComputeResource", "missing!"),
+                     std::invalid_argument);
+
+    TS_ASSERT_THROWS(alg5.execute(), std::runtime_error);
+    TS_ASSERT(!alg5.isExecuted());
+  }
+
+  void test_wrongProperty() {
+    SubmitRemoteJob2 s;
+    TS_ASSERT_THROWS_NOTHING(s.initialize();)
+    TS_ASSERT_THROWS(s.setPropertyValue("Compute", "anything"),
+                     std::runtime_error);
+    TS_ASSERT_THROWS(s.setPropertyValue("NumNodes", "anything"),
+                     std::invalid_argument);
+    TS_ASSERT_THROWS(s.setPropertyValue("NumNodes", "-3"),
+                     std::invalid_argument);
+    TS_ASSERT_THROWS(s.setPropertyValue("CoresPerNode", "anything"),
+                     std::invalid_argument);
+    TS_ASSERT_THROWS(s.setPropertyValue("Task", "anything"),
+                     std::runtime_error);
+    TS_ASSERT_THROWS(s.setPropertyValue("Name", "anything"),
+                     std::runtime_error);
+    TS_ASSERT_THROWS(s.setPropertyValue("Transaction", "anything"),
+                     std::runtime_error);
+    TS_ASSERT_THROWS(s.setPropertyValue("ID", "anything"), std::runtime_error);
+    TS_ASSERT_THROWS(s.setPropertyValue("ScriptName", ""),
+                     std::invalid_argument);
+    TS_ASSERT_THROWS(s.setPropertyValue("Scrip", "any name"),
+                     std::runtime_error);
+    TS_ASSERT_THROWS(s.setPropertyValue("ScriptParams", ""),
+                     std::invalid_argument);
+  }
+
+  void test_propertiesOK() {
+    testFacilities.push_back(std::make_pair("SNS", "Fermi"));
+    testFacilities.push_back(std::make_pair("ISIS", "SCARF@STFC"));
+
+    const Mantid::Kernel::FacilityInfo &prevFac =
+        Mantid::Kernel::ConfigService::Instance().getFacility();
+    for (size_t fi = 0; fi < testFacilities.size(); fi++) {
+      const std::string facName = testFacilities[fi].first;
+      const std::string compName = testFacilities[fi].second;
+
+      Mantid::Kernel::ConfigService::Instance().setFacility(facName);
+
+      SubmitRemoteJob2 s;
+      TS_ASSERT_THROWS_NOTHING(s.initialize());
+      TS_ASSERT_THROWS_NOTHING(s.setPropertyValue("ComputeResource", compName));
+      TS_ASSERT_THROWS_NOTHING(s.setPropertyValue("NumNodes", "1"));
+      TS_ASSERT_THROWS_NOTHING(s.setPropertyValue("CoresPerNode", "4"));
+      TS_ASSERT_THROWS_NOTHING(s.setPropertyValue("TaskName", "unit test"));
+      TS_ASSERT_THROWS_NOTHING(s.setPropertyValue("TransactionID", "tr001"));
+      TS_ASSERT_THROWS_NOTHING(s.setPropertyValue("ScriptName", "test script"));
+      TS_ASSERT_THROWS_NOTHING(
+          s.setPropertyValue("ScriptParams", "print 'hello world'"));
+      // TODO: this would run the algorithm and do a remote
+      // connection. uncomment only when/if we have a mock up for this
+      // TS_ASSERT_THROWS(s.execute(), std::exception);
+      TS_ASSERT(!s.isExecuted());
+    }
+    Mantid::Kernel::ConfigService::Instance().setFacility(prevFac.name());
+  }
+
+  // TODO: void test_runOK() - with a mock when we can add it.
+  // ideally, with different compute resources to check the remote job
+  // manager factory, etc.
+
+private:
+  Mantid::API::IAlgorithm_sptr testAlg;
+  std::vector<std::pair<std::string, std::string>> testFacilities;
+};
+
+#endif // MANTID_REMOTEALGORITHMS_SUBMITREMOTEJOBTEST_H_
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/test/SubmitRemoteJobTest.h b/Code/Mantid/Framework/RemoteAlgorithms/test/SubmitRemoteJobTest.h
index 9af2b6cae2c7be0a3c718f2e371583a3b54b9b76..5a50bf3089fb7bd53c0fa41f51e5f7ddda08ed8d 100644
--- a/Code/Mantid/Framework/RemoteAlgorithms/test/SubmitRemoteJobTest.h
+++ b/Code/Mantid/Framework/RemoteAlgorithms/test/SubmitRemoteJobTest.h
@@ -21,7 +21,7 @@ public:
 
   void test_algorithm() {
     testAlg = Mantid::API::AlgorithmManager::Instance().create(
-        "SubmitRemoteJob" /*, 1*/);
+        "SubmitRemoteJob" , 1);
     TS_ASSERT(testAlg);
     TS_ASSERT_EQUALS(testAlg->name(), "SubmitRemoteJob");
     TS_ASSERT_EQUALS(testAlg->version(), 1);
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/test/UploadRemoteFile2Test.h b/Code/Mantid/Framework/RemoteAlgorithms/test/UploadRemoteFile2Test.h
new file mode 100644
index 0000000000000000000000000000000000000000..e9b2bcb833d517751f257abefb1c27e41d86e685
--- /dev/null
+++ b/Code/Mantid/Framework/RemoteAlgorithms/test/UploadRemoteFile2Test.h
@@ -0,0 +1,160 @@
+#ifndef MANTID_REMOTEALGORITHMS_UPLOADREMOTEFILETEST_H_
+#define MANTID_REMOTEALGORITHMS_UPLOADREMOTEFILETEST_H_
+
+#include <cxxtest/TestSuite.h>
+
+#include "MantidAPI/AlgorithmManager.h"
+#include "MantidKernel/ConfigService.h"
+#include "MantidKernel/FacilityInfo.h"
+#include "MantidRemoteAlgorithms/UploadRemoteFile2.h"
+
+using namespace Mantid::RemoteAlgorithms;
+
+class UploadRemoteFile2Test : public CxxTest::TestSuite {
+public:
+  // This pair of boilerplate methods prevent the suite being created statically
+  // This means the constructor isn't called when running other tests
+  static UploadRemoteFile2Test *createSuite() {
+    return new UploadRemoteFile2Test();
+  }
+  static void destroySuite(UploadRemoteFile2Test *suite) { delete suite; }
+
+  void test_algorithm() {
+    testAlg = Mantid::API::AlgorithmManager::Instance().create(
+        "UploadRemoteFile" /*, 2*/);
+    TS_ASSERT(testAlg);
+    TS_ASSERT_EQUALS(testAlg->name(), "UploadRemoteFile");
+    TS_ASSERT_EQUALS(testAlg->version(), 2);
+  }
+
+  void test_castAlgorithm() {
+    // can create
+    boost::shared_ptr<UploadRemoteFile2> a;
+    TS_ASSERT(a = boost::make_shared<UploadRemoteFile2>());
+
+    // can cast to inherited interfaces and base classes
+    TS_ASSERT(
+        dynamic_cast<Mantid::RemoteAlgorithms::UploadRemoteFile2 *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::API::Algorithm *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::Kernel::PropertyManagerOwner *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::API::IAlgorithm *>(a.get()));
+    TS_ASSERT(dynamic_cast<Mantid::Kernel::IPropertyManager *>(a.get()));
+  }
+
+  void test_init() {
+    if (!testAlg->isInitialized())
+      TS_ASSERT_THROWS_NOTHING(testAlg->initialize());
+
+    TS_ASSERT(testAlg->isInitialized());
+
+    UploadRemoteFile2 ul;
+    TS_ASSERT_THROWS_NOTHING(ul.initialize());
+  }
+
+  // TODO: when we have a RemoteJobManager capable of creating
+  // algorithms for different types of compute resources (example:
+  // Fermi@SNS and SCARF@STFC), create different algorithms for them
+  void test_propertiesMissing() {
+    UploadRemoteFile2 alg1;
+    TS_ASSERT_THROWS_NOTHING(alg1.initialize());
+    // Transaction id missing
+    TS_ASSERT_THROWS_NOTHING(
+        alg1.setPropertyValue("RemoteFileName", "file name"));
+    TS_ASSERT_THROWS_NOTHING(
+        alg1.setPropertyValue("LocalFileName", "local file name"));
+    TS_ASSERT_THROWS(alg1.setPropertyValue("ComputeResource", "missing!"),
+                     std::invalid_argument);
+
+    TS_ASSERT_THROWS(alg1.execute(), std::runtime_error);
+    TS_ASSERT(!alg1.isExecuted());
+
+    UploadRemoteFile2 alg2;
+    TS_ASSERT_THROWS_NOTHING(alg2.initialize());
+    // remote file name missing
+    TS_ASSERT_THROWS_NOTHING(alg2.setPropertyValue("TransactionID", "id001"));
+    TS_ASSERT_THROWS_NOTHING(
+        alg2.setPropertyValue("LocalFileName", "local file name"));
+    TS_ASSERT_THROWS(alg2.setPropertyValue("ComputeResource", "missing!"),
+                     std::invalid_argument);
+
+    TS_ASSERT_THROWS(alg2.execute(), std::runtime_error);
+    TS_ASSERT(!alg2.isExecuted());
+
+    UploadRemoteFile2 alg3;
+    TS_ASSERT_THROWS_NOTHING(alg3.initialize());
+    // local file name missing
+    TS_ASSERT_THROWS_NOTHING(alg3.setPropertyValue("TransactionID", "id001"));
+    TS_ASSERT_THROWS_NOTHING(
+        alg3.setPropertyValue("RemoteFileName", "remote file name"));
+    TS_ASSERT_THROWS(alg3.setPropertyValue("ComputeResource", "missing!"),
+                     std::invalid_argument);
+
+    TS_ASSERT_THROWS(alg3.execute(), std::runtime_error);
+    TS_ASSERT(!alg3.isExecuted());
+
+    UploadRemoteFile2 alg4;
+    TS_ASSERT_THROWS_NOTHING(alg4.initialize());
+    // compute resource missing
+    TS_ASSERT_THROWS_NOTHING(
+        alg4.setPropertyValue("RemoteFileName", "file name"));
+    TS_ASSERT_THROWS_NOTHING(alg4.setPropertyValue("TransactionID", "id001"));
+
+    TS_ASSERT_THROWS(alg4.execute(), std::runtime_error);
+    TS_ASSERT(!alg4.isExecuted());
+  }
+
+  void test_wrongProperty() {
+    UploadRemoteFile2 ul;
+    TS_ASSERT_THROWS_NOTHING(ul.initialize();)
+    TS_ASSERT_THROWS(ul.setPropertyValue("Compute", "anything"),
+                     std::runtime_error);
+    TS_ASSERT_THROWS(ul.setPropertyValue("TransID", "anything"),
+                     std::runtime_error);
+    TS_ASSERT_THROWS(ul.setPropertyValue("RemoteFile", "anything"),
+                     std::runtime_error);
+    TS_ASSERT_THROWS(ul.setPropertyValue("FileName", "anything"),
+                     std::runtime_error);
+    TS_ASSERT_THROWS(ul.setPropertyValue("LocalFile", "anything"),
+                     std::runtime_error);
+  }
+
+  void test_propertiesOK() {
+    testFacilities.push_back(std::make_pair("SNS", "Fermi"));
+    testFacilities.push_back(std::make_pair("ISIS", "SCARF@STFC"));
+
+    const Mantid::Kernel::FacilityInfo &prevFac =
+        Mantid::Kernel::ConfigService::Instance().getFacility();
+    for (size_t fi = 0; fi < testFacilities.size(); fi++) {
+      const std::string facName = testFacilities[fi].first;
+      const std::string compName = testFacilities[fi].second;
+
+      Mantid::Kernel::ConfigService::Instance().setFacility(facName);
+
+      UploadRemoteFile2 ul;
+      TS_ASSERT_THROWS_NOTHING(ul.initialize());
+      TS_ASSERT_THROWS_NOTHING(
+          ul.setPropertyValue("ComputeResource", compName));
+      TS_ASSERT_THROWS_NOTHING(
+          ul.setPropertyValue("TransactionID", "anything001"));
+      TS_ASSERT_THROWS_NOTHING(
+          ul.setPropertyValue("RemoteFileName", "any name"));
+      TS_ASSERT_THROWS_NOTHING(
+          ul.setPropertyValue("LocalFileName", "any local path"));
+      // TODO: this would run the algorithm and do a remote
+      // connection. uncomment only when/if we have a mock up for this
+      // TS_ASSERT_THROWS(ul.execute(), std::exception);
+      TS_ASSERT(!ul.isExecuted());
+    }
+    Mantid::Kernel::ConfigService::Instance().setFacility(prevFac.name());
+  }
+
+  // TODO: void test_runOK() - with a mock when we can add it.
+  // ideally, with different compute resources to check the remote job
+  // manager factory, etc.
+
+private:
+  Mantid::API::IAlgorithm_sptr testAlg;
+  std::vector<std::pair<std::string, std::string>> testFacilities;
+};
+
+#endif // MANTID_REMOTEALGORITHMS_UPLOADREMOTEFILETEST_H_
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/test/UploadRemoteFileTest.h b/Code/Mantid/Framework/RemoteAlgorithms/test/UploadRemoteFileTest.h
index 9aae4d4257dd1d79a0718fd5d9771d572a7c143c..4d4ad6f2ffaca3398d5d69ba4df286dacd8166c2 100644
--- a/Code/Mantid/Framework/RemoteAlgorithms/test/UploadRemoteFileTest.h
+++ b/Code/Mantid/Framework/RemoteAlgorithms/test/UploadRemoteFileTest.h
@@ -20,8 +20,8 @@ public:
   static void destroySuite(UploadRemoteFileTest *suite) { delete suite; }
 
   void test_algorithm() {
-    testAlg = Mantid::API::AlgorithmManager::Instance().create(
-        "UploadRemoteFile" /*, 1*/);
+    testAlg =
+        Mantid::API::AlgorithmManager::Instance().create("UploadRemoteFile", 1);
     TS_ASSERT(testAlg);
     TS_ASSERT_EQUALS(testAlg->name(), "UploadRemoteFile");
     TS_ASSERT_EQUALS(testAlg->version(), 1);
diff --git a/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiFitPeaks2D.h b/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiFitPeaks2D.h
index a7217d53e063a97becbcd694f891652508413fdc..9735c98abde77c7f654431055f5b7519646feb58 100644
--- a/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiFitPeaks2D.h
+++ b/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiFitPeaks2D.h
@@ -64,52 +64,61 @@ public:
 
   std::map<std::string, std::string> validateInputs();
 
-  boost::shared_ptr<Kernel::DblMatrix> getLocalCovarianceMatrix(
-      const boost::shared_ptr<const Kernel::DblMatrix> &covarianceMatrix,
-      size_t parameterOffset, size_t nParams) const;
+  bool checkGroups() { return false; }
 
 protected:
-  Poldi2DFunction_sptr getFunctionIndividualPeaks(
-      std::string profileFunctionName,
-      const PoldiPeakCollection_sptr &peakCollection) const;
-
-  Poldi2DFunction_sptr
-  getFunctionPawley(std::string profileFunctionName,
-                    const PoldiPeakCollection_sptr &peakCollection) const;
-
-  PoldiPeak_sptr
-  getPeakFromPeakFunction(API::IPeakFunction_sptr profileFunction,
-                          const Kernel::V3D &hkl);
-
-  API::ITableWorkspace_sptr
-  getRefinedCellParameters(const API::IFunction_sptr &fitFunction) const;
+  // Workspace handling
+  std::vector<PoldiPeakCollection_sptr> getPeakCollectionsFromInput() const;
 
   PoldiPeakCollection_sptr
   getPeakCollection(const DataObjects::TableWorkspace_sptr &peakTable) const;
+
+  // Peak integration and transformations
+  std::vector<PoldiPeakCollection_sptr> getNormalizedPeakCollections(
+      const std::vector<PoldiPeakCollection_sptr> &peakCollections) const;
+
   PoldiPeakCollection_sptr getIntegratedPeakCollection(
       const PoldiPeakCollection_sptr &rawPeakCollection) const;
   PoldiPeakCollection_sptr getNormalizedPeakCollection(
       const PoldiPeakCollection_sptr &peakCollection) const;
+
+  std::vector<PoldiPeakCollection_sptr>
+  getCountPeakCollections(const API::IFunction_sptr &fitFunction);
   PoldiPeakCollection_sptr
   getCountPeakCollection(const PoldiPeakCollection_sptr &peakCollection) const;
 
-  void assignMillerIndices(const PoldiPeakCollection_sptr &from,
-                           PoldiPeakCollection_sptr &to) const;
+  // Conversion between peaks and functions
+  PoldiPeak_sptr
+  getPeakFromPeakFunction(API::IPeakFunction_sptr profileFunction,
+                          const Kernel::V3D &hkl);
+
+  // Conversion between peak collections and functions
+  Poldi2DFunction_sptr
+  getFunctionFromPeakCollection(const PoldiPeakCollection_sptr &peakCollection);
+
+  Poldi2DFunction_sptr getFunctionIndividualPeaks(
+      std::string profileFunctionName,
+      const PoldiPeakCollection_sptr &peakCollection) const;
+
+  Poldi2DFunction_sptr
+  getFunctionPawley(std::string profileFunctionName,
+                    const PoldiPeakCollection_sptr &peakCollection);
+
+  std::string
+  getRefinedStartingCell(const std::string &initialCell,
+                         const std::string &crystalSystem,
+                         const PoldiPeakCollection_sptr &peakCollection);
 
   PoldiPeakCollection_sptr
   getPeakCollectionFromFunction(const API::IFunction_sptr &fitFunction);
-  Poldi2DFunction_sptr getFunctionFromPeakCollection(
-      const PoldiPeakCollection_sptr &peakCollection) const;
-  void addBackgroundTerms(Poldi2DFunction_sptr poldi2DFunction) const;
 
-  API::IAlgorithm_sptr
-  calculateSpectrum(const PoldiPeakCollection_sptr &peakCollection,
-                    const API::MatrixWorkspace_sptr &matrixWorkspace);
-  API::MatrixWorkspace_sptr
-  getWorkspace(const API::IAlgorithm_sptr &fitAlgorithm) const;
-  API::IFunction_sptr
-  getFunction(const API::IAlgorithm_sptr &fitAlgorithm) const;
+  void assignMillerIndices(const PoldiPeakCollection_sptr &from,
+                           PoldiPeakCollection_sptr &to) const;
 
+  void assignCrystalData(PoldiPeakCollection_sptr &normalizedPeakCollection,
+                         const PoldiPeakCollection_sptr &peakCollection) const;
+
+  // Extraction of 1D spectrum and cell
   API::MatrixWorkspace_sptr
   get1DSpectrum(const API::IFunction_sptr &fitFunction,
                 const API::MatrixWorkspace_sptr &workspace) const;
@@ -118,6 +127,26 @@ protected:
   getQSpectrum(const API::FunctionDomain1D &domain,
                const API::FunctionValues &values) const;
 
+  API::ITableWorkspace_sptr
+  getRefinedCellParameters(const API::IFunction_sptr &fitFunction) const;
+
+  // Interacting with Fit
+  API::IAlgorithm_sptr calculateSpectrum(
+      const std::vector<PoldiPeakCollection_sptr> &peakCollections,
+      const API::MatrixWorkspace_sptr &matrixWorkspace);
+
+  API::MatrixWorkspace_sptr
+  getWorkspace(const API::IAlgorithm_sptr &fitAlgorithm) const;
+  API::IFunction_sptr
+  getFunction(const API::IAlgorithm_sptr &fitAlgorithm) const;
+
+  void addBackgroundTerms(Poldi2DFunction_sptr poldi2DFunction) const;
+
+  boost::shared_ptr<Kernel::DblMatrix> getLocalCovarianceMatrix(
+      const boost::shared_ptr<const Kernel::DblMatrix> &covarianceMatrix,
+      size_t parameterOffset, size_t nParams) const;
+
+  // Poldi instrument book-keeping
   void setPoldiInstrument(const PoldiInstrumentAdapter_sptr &instrument);
   void setTimeTransformerFromInstrument(
       const PoldiInstrumentAdapter_sptr &poldiInstrument);
@@ -128,8 +157,6 @@ protected:
   void setDeltaT(double newDeltaT);
   bool isValidDeltaT(double deltaT) const;
 
-  void throwOnInsufficientState();
-
   PoldiInstrumentAdapter_sptr m_poldiInstrument;
   PoldiTimeTransformer_sptr m_timeTransformer;
   double m_deltaT;
diff --git a/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiIndexKnownCompounds.h b/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiIndexKnownCompounds.h
index 683805eec2df33845de6b33c1cc4ba9e7a3359c9..73d750ce7344fc0888e1708ba07497e3061cffd4 100644
--- a/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiIndexKnownCompounds.h
+++ b/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiIndexKnownCompounds.h
@@ -151,6 +151,10 @@ protected:
   PoldiPeakCollection_sptr
   getIntensitySortedPeakCollection(const PoldiPeakCollection_sptr &peaks) const;
 
+  void assignCrystalStructureParameters(
+      PoldiPeakCollection_sptr &indexedPeaks,
+      const PoldiPeakCollection_sptr &phasePeaks) const;
+
   PoldiPeakCollection_sptr m_measuredPeaks;
   std::vector<PoldiPeakCollection_sptr> m_expectedPhases;
   std::vector<std::string> m_phaseNames;
diff --git a/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiUtilities/PoldiMockInstrumentHelpers.h b/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiUtilities/PoldiMockInstrumentHelpers.h
index 16e9961504594011889ba82136daed035440e580..b78bd093181ee11405158e54c5e2b469e05a7c5b 100644
--- a/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiUtilities/PoldiMockInstrumentHelpers.h
+++ b/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiUtilities/PoldiMockInstrumentHelpers.h
@@ -515,16 +515,16 @@ public:
     PoldiPeakCollection_sptr peaks(
         new PoldiPeakCollection(PoldiPeakCollection::Integral));
     peaks->addPeak(PoldiPeak::create(
-        MillerIndices(0, 0, 0), UncertainValue(1.108644),
+        MillerIndices(4, 2, 2), UncertainValue(1.108644),
         UncertainValue(1.926395655), UncertainValue(0.002475747)));
     peaks->addPeak(PoldiPeak::create(
-        MillerIndices(0, 0, 0), UncertainValue(1.637539),
+        MillerIndices(3, 1, 1), UncertainValue(1.637539),
         UncertainValue(4.773980141), UncertainValue(0.002516417)));
     peaks->addPeak(PoldiPeak::create(
-        MillerIndices(0, 0, 0), UncertainValue(1.920200),
+        MillerIndices(2, 2, 0), UncertainValue(1.920200),
         UncertainValue(9.370919228), UncertainValue(0.002444439)));
     peaks->addPeak(PoldiPeak::create(
-        MillerIndices(0, 0, 0), UncertainValue(1.245958),
+        MillerIndices(3, 3, 1), UncertainValue(1.245958),
         UncertainValue(1.758037806), UncertainValue(0.002696334)));
 
     peaks->setProfileFunctionName("Gaussian");
diff --git a/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiUtilities/PoldiPeakCollection.h b/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiUtilities/PoldiPeakCollection.h
index e9e708c8dbcbcdd7689aa62038a74811637cbbd3..0bb36350f7c3102961e84c9e758f83a816ac4cbe 100644
--- a/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiUtilities/PoldiPeakCollection.h
+++ b/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiUtilities/PoldiPeakCollection.h
@@ -46,7 +46,10 @@ typedef boost::shared_ptr<PoldiPeakCollection> PoldiPeakCollection_sptr;
 
 class MANTID_SINQ_DLL PoldiPeakCollection {
 public:
-  enum IntensityType { Maximum, Integral };
+  enum IntensityType {
+    Maximum,
+    Integral
+  };
 
   PoldiPeakCollection(IntensityType intensityType = Maximum);
   PoldiPeakCollection(const DataObjects::TableWorkspace_sptr &workspace);
@@ -72,6 +75,9 @@ public:
   void setPointGroup(const Geometry::PointGroup_sptr &pointGroup);
   Geometry::PointGroup_sptr pointGroup() const;
 
+  void setUnitCell(const Geometry::UnitCell &unitCell);
+  Geometry::UnitCell unitCell() const;
+
   DataObjects::TableWorkspace_sptr asTableWorkspace();
 
 protected:
@@ -93,6 +99,7 @@ protected:
   std::string
   getProfileFunctionNameFromLog(const API::LogManager_sptr &tableLog);
   std::string getPointGroupStringFromLog(const API::LogManager_sptr &tableLog);
+  std::string getUnitCellStringFromLog(const API::LogManager_sptr &tableLog);
 
   std::string getStringValueFromLog(const API::LogManager_sptr &logManager,
                                     std::string valueName);
@@ -105,11 +112,15 @@ protected:
   Geometry::PointGroup_sptr
   pointGroupFromString(const std::string &pointGroupString) const;
 
+  Geometry::UnitCell
+  unitCellFromString(const std::string &unitCellString) const;
+
   std::vector<PoldiPeak_sptr> m_peaks;
   IntensityType m_intensityType;
   std::string m_profileFunctionName;
 
   Geometry::PointGroup_sptr m_pointGroup;
+  Geometry::UnitCell m_unitCell;
 };
 }
 }
diff --git a/Code/Mantid/Framework/SINQ/src/PoldiFitPeaks1D2.cpp b/Code/Mantid/Framework/SINQ/src/PoldiFitPeaks1D2.cpp
index f009cceecec6a329fa45bfbd8c68929da3426aa4..3a9b1cca815bc5912f3ab7521934c4387b699ba9 100644
--- a/Code/Mantid/Framework/SINQ/src/PoldiFitPeaks1D2.cpp
+++ b/Code/Mantid/Framework/SINQ/src/PoldiFitPeaks1D2.cpp
@@ -363,7 +363,8 @@ PoldiPeakCollection_sptr PoldiFitPeaks1D2::getReducedPeakCollection(
 }
 
 bool PoldiFitPeaks1D2::peakIsAcceptable(const PoldiPeak_sptr &peak) const {
-  return peak->intensity() > 0 && peak->fwhm(PoldiPeak::Relative) < 0.02;
+  return peak->intensity() > 0 && peak->fwhm(PoldiPeak::Relative) < 0.02 &&
+         peak->fwhm(PoldiPeak::Relative) > 0.001;
 }
 
 void PoldiFitPeaks1D2::exec() {
@@ -386,7 +387,7 @@ void PoldiFitPeaks1D2::exec() {
     ++i;
   }
 
-  setProperty("OutputWorkspace", m_peaks->asTableWorkspace());
+  setProperty("OutputWorkspace", fittedPeaksNew->asTableWorkspace());
   setProperty("FitPlotsWorkspace", m_fitplots);
 }
 
diff --git a/Code/Mantid/Framework/SINQ/src/PoldiFitPeaks2D.cpp b/Code/Mantid/Framework/SINQ/src/PoldiFitPeaks2D.cpp
index d1bd62548f5d7a926540a957fb8d66ecfe9df3ea..38fa55e167894b78a52f70d1d8d6d15f32ae3e2d 100644
--- a/Code/Mantid/Framework/SINQ/src/PoldiFitPeaks2D.cpp
+++ b/Code/Mantid/Framework/SINQ/src/PoldiFitPeaks2D.cpp
@@ -15,8 +15,11 @@
 #include "MantidSINQ/PoldiUtilities/PoldiPeakCollection.h"
 #include "MantidSINQ/PoldiUtilities/PoldiInstrumentAdapter.h"
 #include "MantidSINQ/PoldiUtilities/PoldiDeadWireDecorator.h"
+
+#include "MantidAPI/ILatticeFunction.h"
 #include "MantidAPI/IPeakFunction.h"
 #include "MantidAPI/IPawleyFunction.h"
+#include "MantidGeometry/Crystal/UnitCell.h"
 
 #include "MantidSINQ/PoldiUtilities/Poldi2DFunction.h"
 
@@ -31,6 +34,7 @@ DECLARE_ALGORITHM(PoldiFitPeaks2D)
 using namespace API;
 using namespace Kernel;
 using namespace DataObjects;
+using namespace Geometry;
 
 /** Constructor
  */
@@ -62,11 +66,6 @@ std::map<std::string, std::string> PoldiFitPeaks2D::validateInputs() {
   bool isPawleyFit = getProperty("PawleyFit");
 
   if (isPawleyFit) {
-    Property *cellProperty = getPointerToProperty("InitialCell");
-    if (cellProperty->isDefault()) {
-      errorMap["InitialCell"] = "Initial cell must be given for PawleyFit.";
-    }
-
     Property *refinedCellParameters =
         getPointerToProperty("RefinedCellParameters");
     if (refinedCellParameters->isDefault()) {
@@ -79,78 +78,311 @@ std::map<std::string, std::string> PoldiFitPeaks2D::validateInputs() {
   return errorMap;
 }
 
-/// Initialization of algorithm properties.
-void PoldiFitPeaks2D::init() {
-  declareProperty(new WorkspaceProperty<MatrixWorkspace>("InputWorkspace", "",
-                                                         Direction::Input),
-                  "Measured POLDI 2D-spectrum.");
-  declareProperty(new WorkspaceProperty<TableWorkspace>("PoldiPeakWorkspace",
-                                                        "", Direction::Input),
-                  "Table workspace with peak information.");
+/**
+ * Extracts a vector of PoldiPeakCollection objects from the input
+ *
+ * This method examines what kind of workspace has been supplied to the
+ * PoldiPeakWorkspace input property and tries to construct a vector
+ * of peak collections from this. It works with either a single TableWorkspace
+ * or with a WorkspaceGroups that contains several TableWorkspaces.
+ *
+ * If the workspace can not be interpreted properly, the method throws an
+ * std::invalid_argument exception.
+ *
+ * @return Vector with one or more PoldiPeakCollections.
+ */
+std::vector<PoldiPeakCollection_sptr>
+PoldiFitPeaks2D::getPeakCollectionsFromInput() const {
+  Workspace_sptr peakWorkspace = getProperty("PoldiPeakWorkspace");
+
+  std::vector<PoldiPeakCollection_sptr> peakCollections;
+
+  // If the input workspace is a TableWorkspace, insert it into the vector and
+  // return it.
+  TableWorkspace_sptr peakTable =
+      boost::dynamic_pointer_cast<TableWorkspace>(peakWorkspace);
+  if (peakTable) {
+    try {
+      peakCollections.push_back(getPeakCollection(peakTable));
+    }
+    catch (std::runtime_error) {
+      // do nothing
+    }
 
-  auto peakFunctionValidator = boost::make_shared<StringListValidator>(
-      FunctionFactory::Instance().getFunctionNames<IPeakFunction>());
-  declareProperty("PeakProfileFunction", "Gaussian", peakFunctionValidator,
-                  "Profile function to use for integrating the peak profiles "
-                  "before calculating the spectrum.");
+    return peakCollections;
+  }
 
-  declareProperty("PawleyFit", false, "Instead of refining individual peaks, "
-                                      "refine a unit cell. Peaks must be "
-                                      "indexed, an initial cell must be "
-                                      "provided, as well as a crystal system.");
-  declareProperty("InitialCell", "", "Initial unit cell parameters as 6 "
-                                     "space-separated numbers. Only used when "
-                                     "PawleyFit is checked.");
-
-  std::vector<std::string> crystalSystems;
-  crystalSystems.push_back("Cubic");
-  crystalSystems.push_back("Tetragonal");
-  crystalSystems.push_back("Hexagonal");
-  crystalSystems.push_back("Trigonal");
-  crystalSystems.push_back("Orthorhombic");
-  crystalSystems.push_back("Monoclinic");
-  crystalSystems.push_back("Triclinic");
-
-  auto crystalSystemValidator =
-      boost::make_shared<StringListValidator>(crystalSystems);
-
-  declareProperty("CrystalSystem", "Cubic", crystalSystemValidator,
-                  "Crystal system to use for constraining "
-                  "unit cell parameters. Only used when "
-                  "PawleyFit is checked.");
+  // If it's a WorkspaceGroup there are multiple peak tables, make a collection
+  // for each of them.
+  WorkspaceGroup_sptr peakTables =
+      boost::dynamic_pointer_cast<WorkspaceGroup>(peakWorkspace);
+  if (peakTables) {
+    for (size_t i = 0;
+         i < static_cast<size_t>(peakTables->getNumberOfEntries()); ++i) {
+      TableWorkspace_sptr peakTable =
+          boost::dynamic_pointer_cast<TableWorkspace>(peakTables->getItem(i));
+
+      if (peakTable) {
+        try {
+          peakCollections.push_back(getPeakCollection(peakTable));
+        }
+        catch (std::runtime_error) {
+          // do nothing
+        }
+      }
+    }
 
-  declareProperty("FitConstantBackground", true,
-                  "Add a constant background term to the fit.");
-  declareProperty("ConstantBackgroundParameter", 0.0,
-                  "Initial value of constant background.");
+    return peakCollections;
+  }
 
-  declareProperty("FitLinearBackground", true,
-                  "Add a background term linear in 2theta to the fit.");
-  declareProperty("LinearBackgroundParameter", 0.0,
-                  "Initial value of linear background.");
+  // Otherwise throw a runtime error.
+  throw std::runtime_error("Cannot proceed without peak workspace.");
+}
 
-  declareProperty("MaximumIterations", 0, "Maximum number of iterations for "
-                                          "the fit. Use 0 to calculate "
-                                          "2D-spectrum without fitting.");
+/**
+ * Tries to construct a PoldiPeakCollection from the supplied table.
+ *
+ * @param peakTable :: TableWorkspace with POLDI peak data.
+ * @return PoldiPeakCollection with the data from the table workspace.
+ */
+PoldiPeakCollection_sptr
+PoldiFitPeaks2D::getPeakCollection(const TableWorkspace_sptr &peakTable) const {
+  try {
+    return boost::make_shared<PoldiPeakCollection>(peakTable);
+  }
+  catch (...) {
+    throw std::runtime_error("Could not initialize peak collection.");
+  }
+}
 
-  declareProperty(new WorkspaceProperty<MatrixWorkspace>("OutputWorkspace", "",
-                                                         Direction::Output),
-                  "Calculated POLDI 2D-spectrum");
-  declareProperty(new WorkspaceProperty<MatrixWorkspace>("Calculated1DSpectrum",
-                                                         "", Direction::Output),
-                  "Calculated POLDI 1D-spectrum.");
+/// Returns an PoldiPeakCollection with normalized peaks for each input
+/// collection.
+std::vector<PoldiPeakCollection_sptr>
+PoldiFitPeaks2D::getNormalizedPeakCollections(
+    const std::vector<PoldiPeakCollection_sptr> &peakCollections) const {
 
-  declareProperty("LambdaMin", 1.1,
-                  "Minimum wavelength for 1D spectrum calculation");
-  declareProperty("LambdaMax", 5.0,
-                  "Minimum wavelength for 1D spectrum calculation");
+  std::vector<PoldiPeakCollection_sptr> normalizedPeakCollections;
 
-  declareProperty(new WorkspaceProperty<TableWorkspace>(
-                      "RefinedPoldiPeakWorkspace", "", Direction::Output),
-                  "Table workspace with fitted peaks.");
+  for (auto pc = peakCollections.begin(); pc != peakCollections.end(); ++pc) {
+    // First integrate peak collection, then normalize and append to vector
+    PoldiPeakCollection_sptr integratedPeakCollection =
+        getIntegratedPeakCollection(*pc);
 
-  declareProperty(new WorkspaceProperty<ITableWorkspace>(
-      "RefinedCellParameters", "", Direction::Output, PropertyMode::Optional));
+    normalizedPeakCollections.push_back(
+        getNormalizedPeakCollection(integratedPeakCollection));
+  }
+
+  return normalizedPeakCollections;
+}
+
+/**
+ * Return peak collection with integrated peaks
+ *
+ * This method takes a PoldiPeakCollection where the intensity is represented
+ * by the maximum. Then it takes the profile function stored in the peak
+ * collection, which must be the name of a registered
+ * IPeakFunction-implementation. The parameters height and fwhm are assigned,
+ * centre is set to 0 to avoid problems with the parameter transformation for
+ * the integration from -inf to inf. The profiles are integrated using
+ * a PeakFunctionIntegrator to the precision of 1e-10.
+ *
+ * The original peak collection is not modified, a new instance is created.
+ *
+ * @param rawPeakCollection :: PoldiPeakCollection
+ * @return PoldiPeakCollection with integrated intensities
+ */
+PoldiPeakCollection_sptr PoldiFitPeaks2D::getIntegratedPeakCollection(
+    const PoldiPeakCollection_sptr &rawPeakCollection) const {
+  if (!rawPeakCollection) {
+    throw std::invalid_argument(
+        "Cannot proceed with invalid PoldiPeakCollection.");
+  }
+
+  if (!isValidDeltaT(m_deltaT)) {
+    throw std::invalid_argument("Cannot proceed with invalid time bin size.");
+  }
+
+  if (!m_timeTransformer) {
+    throw std::invalid_argument(
+        "Cannot proceed with invalid PoldiTimeTransformer.");
+  }
+
+  if (rawPeakCollection->intensityType() == PoldiPeakCollection::Integral) {
+    /* Intensities are integral already - don't need to do anything,
+     * except cloning the collection, to make behavior consistent, since
+     * integrating also results in a new peak collection.
+     */
+    return rawPeakCollection->clone();
+  }
+
+  /* If no profile function is specified, it's not possible to get integrated
+   * intensities at all and we try to use the one specified by the user
+   * instead.
+   */
+  std::string profileFunctionName = rawPeakCollection->getProfileFunctionName();
+
+  if (!rawPeakCollection->hasProfileFunctionName()) {
+    profileFunctionName = getPropertyValue("PeakProfileFunction");
+  }
+
+  std::vector<std::string> allowedProfiles =
+      FunctionFactory::Instance().getFunctionNames<IPeakFunction>();
+
+  if (std::find(allowedProfiles.begin(), allowedProfiles.end(),
+                profileFunctionName) == allowedProfiles.end()) {
+    throw std::runtime_error(
+        "Cannot integrate peak profiles with invalid profile function.");
+  }
+
+  PoldiPeakCollection_sptr integratedPeakCollection =
+      boost::make_shared<PoldiPeakCollection>(PoldiPeakCollection::Integral);
+  integratedPeakCollection->setProfileFunctionName(profileFunctionName);
+
+  // Preserve unit cell, point group
+  assignCrystalData(integratedPeakCollection, rawPeakCollection);
+
+  for (size_t i = 0; i < rawPeakCollection->peakCount(); ++i) {
+    PoldiPeak_sptr peak = rawPeakCollection->peak(i);
+
+    IPeakFunction_sptr profileFunction =
+        boost::dynamic_pointer_cast<IPeakFunction>(
+            FunctionFactory::Instance().createFunction(profileFunctionName));
+
+    profileFunction->setHeight(peak->intensity());
+    profileFunction->setFwhm(peak->fwhm(PoldiPeak::AbsoluteD));
+
+    PoldiPeak_sptr integratedPeak = peak->clone();
+    integratedPeak->setIntensity(UncertainValue(profileFunction->intensity()));
+    integratedPeakCollection->addPeak(integratedPeak);
+  }
+
+  return integratedPeakCollection;
+}
+
+/**
+ * Normalized the intensities of the given integrated peaks
+ *
+ * This function normalizes the peak intensities according to the source
+ * spectrum, the number of chopper slits and the number of detector elements.
+ *
+ * @param peakCollection :: PoldiPeakCollection with integrated intensities
+ * @return PoldiPeakCollection with normalized intensities
+ */
+PoldiPeakCollection_sptr PoldiFitPeaks2D::getNormalizedPeakCollection(
+    const PoldiPeakCollection_sptr &peakCollection) const {
+  if (!peakCollection) {
+    throw std::invalid_argument(
+        "Cannot proceed with invalid PoldiPeakCollection.");
+  }
+
+  if (!m_timeTransformer) {
+    throw std::invalid_argument("Cannot proceed without PoldiTimeTransformer.");
+  }
+
+  PoldiPeakCollection_sptr normalizedPeakCollection =
+      boost::make_shared<PoldiPeakCollection>(PoldiPeakCollection::Integral);
+  normalizedPeakCollection->setProfileFunctionName(
+      peakCollection->getProfileFunctionName());
+
+  // Carry over unit cell and point group
+  assignCrystalData(normalizedPeakCollection, peakCollection);
+
+  for (size_t i = 0; i < peakCollection->peakCount(); ++i) {
+    PoldiPeak_sptr peak = peakCollection->peak(i);
+    double calculatedIntensity =
+        m_timeTransformer->calculatedTotalIntensity(peak->d());
+
+    PoldiPeak_sptr normalizedPeak = peak->clone();
+    normalizedPeak->setIntensity(peak->intensity() / calculatedIntensity);
+    normalizedPeakCollection->addPeak(normalizedPeak);
+  }
+
+  return normalizedPeakCollection;
+}
+
+/// Returns a vector of peak collections extracted from the function
+std::vector<PoldiPeakCollection_sptr> PoldiFitPeaks2D::getCountPeakCollections(
+    const API::IFunction_sptr &fitFunction) {
+  Poldi2DFunction_sptr poldiFunction =
+      boost::dynamic_pointer_cast<Poldi2DFunction>(fitFunction);
+
+  if (!poldiFunction) {
+    throw std::runtime_error("Can only extract peaks from Poldi2DFunction.");
+  }
+
+  // Covariance matrix - needs to be assigned to the member functions for error
+  // calculation
+  boost::shared_ptr<const Kernel::DblMatrix> covarianceMatrix =
+      poldiFunction->getCovarianceMatrix();
+
+  std::vector<PoldiPeakCollection_sptr> countPeakCollections;
+
+  size_t offset = 0;
+  for (size_t i = 0; i < poldiFunction->nFunctions(); ++i) {
+    IFunction_sptr localFunction = poldiFunction->getFunction(i);
+    size_t nLocalParams = localFunction->nParams();
+
+    // Assign local covariance matrix.
+    boost::shared_ptr<Kernel::DblMatrix> localCov =
+        getLocalCovarianceMatrix(covarianceMatrix, offset, nLocalParams);
+    localFunction->setCovarianceMatrix(localCov);
+
+    try {
+      PoldiPeakCollection_sptr normalizedPeaks =
+          getPeakCollectionFromFunction(localFunction);
+
+      countPeakCollections.push_back(getCountPeakCollection(normalizedPeaks));
+    }
+    catch (std::invalid_argument) {
+      // not a Poldi2DFunction - skip (the background functions)
+    }
+
+    offset += nLocalParams;
+  }
+
+  return countPeakCollections;
+}
+
+/**
+ * Converts normalized peak intensities to count based integral intensities
+ *
+ * This operation is the opposite of getNormalizedPeakCollection and is used
+ * to convert the intensities back to integral intensities.
+ *
+ * @param peakCollection :: PoldiPeakCollection with normalized intensities
+ * @return PoldiPeakCollection with integral intensities
+ */
+PoldiPeakCollection_sptr PoldiFitPeaks2D::getCountPeakCollection(
+    const PoldiPeakCollection_sptr &peakCollection) const {
+  if (!peakCollection) {
+    throw std::invalid_argument(
+        "Cannot proceed with invalid PoldiPeakCollection.");
+  }
+
+  if (!m_timeTransformer) {
+    throw std::invalid_argument("Cannot proceed without PoldiTimeTransformer.");
+  }
+
+  PoldiPeakCollection_sptr countPeakCollection =
+      boost::make_shared<PoldiPeakCollection>(PoldiPeakCollection::Integral);
+  countPeakCollection->setProfileFunctionName(
+      peakCollection->getProfileFunctionName());
+
+  // Get crystal data into new peak collection
+  assignCrystalData(countPeakCollection, peakCollection);
+
+  for (size_t i = 0; i < peakCollection->peakCount(); ++i) {
+    PoldiPeak_sptr peak = peakCollection->peak(i);
+    double calculatedIntensity =
+        m_timeTransformer->calculatedTotalIntensity(peak->d());
+
+    PoldiPeak_sptr countPeak = peak->clone();
+    countPeak->setIntensity(peak->intensity() * calculatedIntensity);
+
+    countPeakCollection->addPeak(countPeak);
+  }
+
+  return countPeakCollection;
 }
 
 /// Creates a PoldiPeak from the given profile function/hkl pair.
@@ -158,6 +390,7 @@ PoldiPeak_sptr
 PoldiFitPeaks2D::getPeakFromPeakFunction(IPeakFunction_sptr profileFunction,
                                          const V3D &hkl) {
 
+  // Use EstimatePeakErrors to calculate errors of FWHM and so on
   IAlgorithm_sptr errorAlg = createChildAlgorithm("EstimatePeakErrors");
   errorAlg->setProperty(
       "Function", boost::dynamic_pointer_cast<IFunction>(profileFunction));
@@ -178,6 +411,7 @@ PoldiFitPeaks2D::getPeakFromPeakFunction(IPeakFunction_sptr profileFunction,
   UncertainValue intensity(height, heightError);
   UncertainValue fwhm(fwhmValue, fwhmError);
 
+  // Create peak with extracted parameters and supplied hkl
   PoldiPeak_sptr peak =
       PoldiPeak::create(MillerIndices(hkl), d, intensity, UncertainValue(1.0));
   peak->setFwhm(fwhm, PoldiPeak::FwhmRelation::AbsoluteD);
@@ -185,95 +419,209 @@ PoldiFitPeaks2D::getPeakFromPeakFunction(IPeakFunction_sptr profileFunction,
   return peak;
 }
 
-/// Returns a TableWorkspace with refined cell parameters and error.
-ITableWorkspace_sptr PoldiFitPeaks2D::getRefinedCellParameters(
-    const IFunction_sptr &fitFunction) const {
-  Poldi2DFunction_sptr poldi2DFunction =
-      boost::dynamic_pointer_cast<Poldi2DFunction>(fitFunction);
+/**
+ * Constructs a proper function from a peak collection
+ *
+ * This method constructs a Poldi2DFunction depending on whether or not a
+ * Pawley fit is performed each peak contained in the peak collection.
+ *
+ * @param peakCollection :: PoldiPeakCollection containing peaks with integral
+ *                          intensities
+ * @return Poldi2DFunction with one PoldiSpectrumDomainFunction per peak
+ */
+Poldi2DFunction_sptr PoldiFitPeaks2D::getFunctionFromPeakCollection(
+    const PoldiPeakCollection_sptr &peakCollection) {
+  std::string profileFunctionName = getProperty("PeakProfileFunction");
 
-  if (!poldi2DFunction || poldi2DFunction->nFunctions() < 1) {
-    throw std::invalid_argument(
-        "Cannot process function that is not a Poldi2DFunction.");
+  bool pawleyFit = getProperty("PawleyFit");
+  if (pawleyFit) {
+    return getFunctionPawley(profileFunctionName, peakCollection);
   }
 
-  ITableWorkspace_sptr latticeParameterTable =
-      WorkspaceFactory::Instance().createTable();
+  return getFunctionIndividualPeaks(profileFunctionName, peakCollection);
+}
 
-  latticeParameterTable->addColumn("str", "Parameter");
-  latticeParameterTable->addColumn("double", "Value");
-  latticeParameterTable->addColumn("double", "Error");
+/**
+ * Returns a Poldi2DFunction that encapsulates individual peaks
+ *
+ * This function takes all peaks from the supplied peak collection and
+ * generates an IPeakFunction of the type given in the name parameter, wraps
+ * them in a Poldi2DFunction and returns it.
+ *
+ * @param profileFunctionName :: Profile function name.
+ * @param peakCollection :: Peak collection with peaks to be used in the fit.
+ * @return :: A Poldi2DFunction with peak profile functions.
+ */
+Poldi2DFunction_sptr PoldiFitPeaks2D::getFunctionIndividualPeaks(
+    std::string profileFunctionName,
+    const PoldiPeakCollection_sptr &peakCollection) const {
+  Poldi2DFunction_sptr mdFunction(new Poldi2DFunction);
+
+  for (size_t i = 0; i < peakCollection->peakCount(); ++i) {
+    PoldiPeak_sptr peak = peakCollection->peak(i);
+
+    boost::shared_ptr<PoldiSpectrumDomainFunction> peakFunction =
+        boost::dynamic_pointer_cast<PoldiSpectrumDomainFunction>(
+            FunctionFactory::Instance().createFunction(
+                "PoldiSpectrumDomainFunction"));
+
+    if (!peakFunction) {
+      throw std::invalid_argument(
+          "Cannot process null pointer poldi function.");
+    }
+
+    peakFunction->setDecoratedFunction(profileFunctionName);
+
+    IPeakFunction_sptr wrappedProfile =
+        boost::dynamic_pointer_cast<IPeakFunction>(
+            peakFunction->getProfileFunction());
+
+    if (wrappedProfile) {
+      wrappedProfile->setCentre(peak->d());
+      wrappedProfile->setFwhm(peak->fwhm(PoldiPeak::AbsoluteD));
+      wrappedProfile->setIntensity(peak->intensity());
+    }
+
+    mdFunction->addFunction(peakFunction);
+  }
+
+  return mdFunction;
+}
+
+/**
+ * Returns a Poldi2DFunction that encapsulates a PawleyFunction
+ *
+ * This function creates a PawleyFunction using the supplied profile function
+ * name and the crystal system as well as initial cell from the input
+ * properties of the algorithm and wraps it in a Poldi2DFunction.
+ *
+ * The cell is refined using LatticeFunction to get better starting values.
+ *
+ * Because the peak intensities are integral at this step but PawleyFunction
+ * expects peak heights, a profile function is created and
+ * setIntensity/height-methods are used to convert.
+ *
+ * @param profileFunctionName :: Profile function name for PawleyFunction.
+ * @param peakCollection :: Peak collection with peaks to be used in the fit.
+ * @return :: A Poldi2DFunction with a PawleyFunction.
+ */
+Poldi2DFunction_sptr PoldiFitPeaks2D::getFunctionPawley(
+    std::string profileFunctionName,
+    const PoldiPeakCollection_sptr &peakCollection) {
+  Poldi2DFunction_sptr mdFunction(new Poldi2DFunction);
 
-  // The first function should be PoldiSpectrumPawleyFunction
   boost::shared_ptr<PoldiSpectrumPawleyFunction> poldiPawleyFunction =
       boost::dynamic_pointer_cast<PoldiSpectrumPawleyFunction>(
-          poldi2DFunction->getFunction(0));
+          FunctionFactory::Instance().createFunction(
+              "PoldiSpectrumPawleyFunction"));
 
   if (!poldiPawleyFunction) {
-    throw std::invalid_argument("First function in Poldi2DFunction is not "
-                                "PoldiSpectrumPawleyFunction.");
+    throw std::invalid_argument("Could not create pawley function.");
   }
 
+  poldiPawleyFunction->setDecoratedFunction("PawleyFunction");
+
   IPawleyFunction_sptr pawleyFunction =
-      boost::dynamic_pointer_cast<IPawleyFunction>(
-          poldiPawleyFunction->getDecoratedFunction());
+      poldiPawleyFunction->getPawleyFunction();
+  pawleyFunction->setProfileFunction(profileFunctionName);
 
-  if (pawleyFunction) {
-    CompositeFunction_sptr pawleyParts =
-        boost::dynamic_pointer_cast<CompositeFunction>(
-            pawleyFunction->getDecoratedFunction());
+  // Extract crystal system from peak collection
+  PointGroup_sptr pointGroup = peakCollection->pointGroup();
+  if (!pointGroup) {
+    throw std::invalid_argument("Can not initialize pawley function properly - "
+                                "peaks do not have point group.");
+  }
 
-    IFunction_sptr pawleyParameters = pawleyParts->getFunction(0);
+  std::string crystalSystem =
+      getCrystalSystemAsString(pointGroup->crystalSystem());
+  pawleyFunction->setCrystalSystem(crystalSystem);
 
-    for (size_t i = 0; i < pawleyParameters->nParams(); ++i) {
-      TableRow newRow = latticeParameterTable->appendRow();
-      newRow << pawleyParameters->parameterName(i)
-             << pawleyParameters->getParameter(i)
-             << pawleyParameters->getError(i);
-    }
+  UnitCell cell = peakCollection->unitCell();
+  // Extract unit cell from peak collection
+  pawleyFunction->setUnitCell(getRefinedStartingCell(
+      unitCellToStr(cell), crystalSystem, peakCollection));
+
+  IPeakFunction_sptr pFun = boost::dynamic_pointer_cast<IPeakFunction>(
+      FunctionFactory::Instance().createFunction(profileFunctionName));
+
+  for (size_t i = 0; i < peakCollection->peakCount(); ++i) {
+    PoldiPeak_sptr peak = peakCollection->peak(i);
+
+    pFun->setCentre(peak->d());
+    pFun->setFwhm(peak->fwhm(PoldiPeak::AbsoluteD));
+    pFun->setIntensity(peak->intensity());
+
+    pawleyFunction->addPeak(peak->hkl().asV3D(),
+                            peak->fwhm(PoldiPeak::AbsoluteD), pFun->height());
   }
 
-  return latticeParameterTable;
+  pawleyFunction->fix(pawleyFunction->parameterIndex("f0.ZeroShift"));
+  mdFunction->addFunction(poldiPawleyFunction);
+
+  return mdFunction;
 }
 
 /**
- * Extracts the covariance matrix for the supplied function
+ * Tries to refine the initial cell using the supplied peaks
  *
- * This method extracts the covariance matrix for a sub-function from
- * the global covariance matrix. If no matrix is given, a zero-matrix is
- * returned.
+ * This method tries to refine the initial unit cell using the indexed peaks
+ * that are supplied in the PoldiPeakCollection. If there are unindexed peaks,
+ * the cell will not be refined at all, instead the unmodified initial cell
+ * is returned.
  *
- * @param covarianceMatrix :: Global covariance matrix.
- * @param parameterOffset :: Offset for the parameters of profileFunction.
- * @param nParams :: Number of parameters of the local function.
- * @return
+ * @param initialCell :: String with the initial unit cell
+ * @param crystalSystem :: Crystal system name
+ * @param peakCollection :: Collection of bragg peaks, must be indexed
+ *
+ * @return String for refined unit cell
  */
-boost::shared_ptr<DblMatrix> PoldiFitPeaks2D::getLocalCovarianceMatrix(
-    const boost::shared_ptr<const Kernel::DblMatrix> &covarianceMatrix,
-    size_t parameterOffset, size_t nParams) const {
-  if (covarianceMatrix) {
-    boost::shared_ptr<Kernel::DblMatrix> localCov =
-        boost::make_shared<Kernel::DblMatrix>(nParams, nParams, false);
-    for (size_t j = 0; j < nParams; ++j) {
-      for (size_t k = 0; k < nParams; ++k) {
-        (*localCov)[j][k] =
-            (*covarianceMatrix)[parameterOffset + j][parameterOffset + k];
-      }
+std::string PoldiFitPeaks2D::getRefinedStartingCell(
+    const std::string &initialCell, const std::string &crystalSystem,
+    const PoldiPeakCollection_sptr &peakCollection) {
+
+  Geometry::UnitCell cell = Geometry::strToUnitCell(initialCell);
+
+  ILatticeFunction_sptr latticeFunction =
+      boost::dynamic_pointer_cast<ILatticeFunction>(
+          FunctionFactory::Instance().createFunction("LatticeFunction"));
+
+  latticeFunction->setCrystalSystem(crystalSystem);
+  latticeFunction->fix(latticeFunction->parameterIndex("ZeroShift"));
+  latticeFunction->setUnitCell(cell);
+
+  // Remove errors from d-values
+  PoldiPeakCollection_sptr clone = peakCollection->clone();
+  for (size_t i = 0; i < clone->peakCount(); ++i) {
+    PoldiPeak_sptr peak = clone->peak(i);
+
+    // If there are unindexed peaks, don't refine, just return the initial cell
+    if (peak->hkl() == MillerIndices()) {
+      return initialCell;
     }
 
-    return localCov;
+    peak->setD(UncertainValue(peak->d().value()));
   }
 
-  return boost::make_shared<Kernel::DblMatrix>(nParams, nParams, false);
+  TableWorkspace_sptr peakTable = clone->asTableWorkspace();
+
+  IAlgorithm_sptr fit = createChildAlgorithm("Fit");
+  fit->setProperty("Function",
+                   boost::static_pointer_cast<IFunction>(latticeFunction));
+  fit->setProperty("InputWorkspace", peakTable);
+  fit->setProperty("CostFunction", "Unweighted least squares");
+  fit->execute();
+
+  Geometry::UnitCell refinedCell = latticeFunction->getUnitCell();
+
+  return Geometry::unitCellToStr(refinedCell);
 }
 
 /**
  * Construct a PoldiPeakCollection from a Poldi2DFunction
  *
- * This method performs the opposite operation of
- *getFunctionFromPeakCollection.
+ * This method performs the opposite operation of getFunctionFromPeakCollection.
  * It takes a function, checks if it's of the proper type and turns the
- *information
- * into a PoldiPeakCollection.
+ * information into a PoldiPeakCollection.
  *
  * @param  Poldi2DFunction with one PoldiSpectrumDomainFunction per peak
  * @return PoldiPeakCollection containing peaks with normalized intensities
@@ -301,6 +649,7 @@ PoldiPeakCollection_sptr PoldiFitPeaks2D::getPeakCollectionFromFunction(
         boost::dynamic_pointer_cast<PoldiSpectrumPawleyFunction>(
             poldi2DFunction->getFunction(i));
 
+    // If it's a Pawley function, there are several peaks in one function.
     if (poldiPawleyFunction) {
       IPawleyFunction_sptr pawleyFunction =
           poldiPawleyFunction->getPawleyFunction();
@@ -335,6 +684,7 @@ PoldiPeakCollection_sptr PoldiFitPeaks2D::getPeakCollectionFromFunction(
       break;
     }
 
+    // Otherwise, it's just one peak in this function.
     boost::shared_ptr<PoldiSpectrumDomainFunction> peakFunction =
         boost::dynamic_pointer_cast<PoldiSpectrumDomainFunction>(
             poldi2DFunction->getFunction(i));
@@ -351,231 +701,167 @@ PoldiPeakCollection_sptr PoldiFitPeaks2D::getPeakCollectionFromFunction(
       profileFunction->setCovarianceMatrix(localCov);
 
       // Increment offset for next function
-      offset += nLocalParams;
-
-      PoldiPeak_sptr peak =
-          getPeakFromPeakFunction(profileFunction, V3D(0, 0, 0));
-
-      normalizedPeaks->addPeak(peak);
-    }
-  }
-
-  return normalizedPeaks;
-}
-
-/**
- * Returns a Poldi2DFunction that encapsulates individual peaks
- *
- * This function takes all peaks from the supplied peak collection and
- *generates
- * an IPeakFunction of the type given in the name parameter, wraps them
- * in a Poldi2DFunction and returns it.
- *
- * @param profileFunctionName :: Profile function name.
- * @param peakCollection :: Peak collection with peaks to be used in the fit.
- * @return :: A Poldi2DFunction with peak profile functions.
- */
-Poldi2DFunction_sptr PoldiFitPeaks2D::getFunctionIndividualPeaks(
-    std::string profileFunctionName,
-    const PoldiPeakCollection_sptr &peakCollection) const {
-  Poldi2DFunction_sptr mdFunction(new Poldi2DFunction);
-
-  for (size_t i = 0; i < peakCollection->peakCount(); ++i) {
-    PoldiPeak_sptr peak = peakCollection->peak(i);
-
-    boost::shared_ptr<PoldiSpectrumDomainFunction> peakFunction =
-        boost::dynamic_pointer_cast<PoldiSpectrumDomainFunction>(
-            FunctionFactory::Instance().createFunction(
-                "PoldiSpectrumDomainFunction"));
-
-    if (!peakFunction) {
-      throw std::invalid_argument(
-          "Cannot process null pointer poldi function.");
-    }
-
-    peakFunction->setDecoratedFunction(profileFunctionName);
-
-    IPeakFunction_sptr wrappedProfile =
-        boost::dynamic_pointer_cast<IPeakFunction>(
-            peakFunction->getProfileFunction());
-
-    if (wrappedProfile) {
-      wrappedProfile->setCentre(peak->d());
-      wrappedProfile->setFwhm(peak->fwhm(PoldiPeak::AbsoluteD));
-      wrappedProfile->setIntensity(peak->intensity());
-    }
-
-    mdFunction->addFunction(peakFunction);
-  }
-
-  return mdFunction;
-}
-
-/**
- * Returns a Poldi2DFunction that encapsulates a PawleyFunction
- *
- * This function creates a PawleyFunction using the supplied profile function
- * name and the crystal system as well as initial cell from the input
- *properties
- * of the algorithm and wraps it in a Poldi2DFunction.
- *
- * Because the peak intensities are integral at this step but PawleyFunction
- * expects peak heights, a profile function is created and
- *setIntensity/height-
- * methods are used to convert.
- *
- * @param profileFunctionName :: Profile function name for PawleyFunction.
- * @param peakCollection :: Peak collection with peaks to be used in the fit.
- * @return :: A Poldi2DFunction with a PawleyFunction.
- */
-Poldi2DFunction_sptr PoldiFitPeaks2D::getFunctionPawley(
-    std::string profileFunctionName,
-    const PoldiPeakCollection_sptr &peakCollection) const {
-  Poldi2DFunction_sptr mdFunction(new Poldi2DFunction);
-
-  boost::shared_ptr<PoldiSpectrumPawleyFunction> poldiPawleyFunction =
-      boost::dynamic_pointer_cast<PoldiSpectrumPawleyFunction>(
-          FunctionFactory::Instance().createFunction(
-              "PoldiSpectrumPawleyFunction"));
-
-  if (!poldiPawleyFunction) {
-    throw std::invalid_argument("Could not create pawley function.");
-  }
-
-  poldiPawleyFunction->setDecoratedFunction("PawleyFunction");
-
-  IPawleyFunction_sptr pawleyFunction =
-      poldiPawleyFunction->getPawleyFunction();
-  pawleyFunction->setProfileFunction(profileFunctionName);
-
-  std::string crystalSystem = getProperty("CrystalSystem");
-  pawleyFunction->setCrystalSystem(crystalSystem);
+      offset += nLocalParams;
 
-  std::string initialCell = getProperty("InitialCell");
-  pawleyFunction->setUnitCell(initialCell);
+      PoldiPeak_sptr peak =
+          getPeakFromPeakFunction(profileFunction, V3D(0, 0, 0));
 
-  IPeakFunction_sptr pFun = boost::dynamic_pointer_cast<IPeakFunction>(
-      FunctionFactory::Instance().createFunction(profileFunctionName));
+      normalizedPeaks->addPeak(peak);
+    }
+  }
 
-  for (size_t i = 0; i < peakCollection->peakCount(); ++i) {
-    PoldiPeak_sptr peak = peakCollection->peak(i);
+  return normalizedPeaks;
+}
 
-    pFun->setCentre(peak->d());
-    pFun->setFwhm(peak->fwhm(PoldiPeak::AbsoluteD));
-    pFun->setIntensity(peak->intensity());
+/// Assign Miller indices from one peak collection to another.
+void PoldiFitPeaks2D::assignMillerIndices(const PoldiPeakCollection_sptr &from,
+                                          PoldiPeakCollection_sptr &to) const {
+  if (!from || !to) {
+    throw std::invalid_argument("Cannot process invalid peak collections.");
+  }
 
-    pawleyFunction->addPeak(peak->hkl().asV3D(),
-                            peak->fwhm(PoldiPeak::AbsoluteD), pFun->height());
+  if (from->peakCount() != to->peakCount()) {
+    throw std::runtime_error(
+        "Cannot assign indices if number of peaks does not match.");
   }
 
-  pawleyFunction->fix(pawleyFunction->parameterIndex("f0.ZeroShift"));
-  mdFunction->addFunction(poldiPawleyFunction);
+  for (size_t i = 0; i < from->peakCount(); ++i) {
+    PoldiPeak_sptr fromPeak = from->peak(i);
+    PoldiPeak_sptr toPeak = to->peak(i);
 
-  return mdFunction;
+    toPeak->setHKL(fromPeak->hkl());
+  }
+}
+
+/// Copy crystal data from source to target collection to preserve during
+/// integration etc.
+void PoldiFitPeaks2D::assignCrystalData(
+    PoldiPeakCollection_sptr &targetCollection,
+    const PoldiPeakCollection_sptr &sourceCollection) const {
+  targetCollection->setUnitCell(sourceCollection->unitCell());
+  targetCollection->setPointGroup(sourceCollection->pointGroup());
 }
 
 /**
- * Constructs a proper function from a peak collection
+ * Calculates the 1D diffractogram based on the supplied function
  *
- * This method constructs a Poldi2DFunction depending on whether or not a
- * Pawley fit is performed each peak contained in the peak collection.
+ * This method takes a fit function and checks whether it implements the
+ * IPoldiFunction1D interface. If that's the case, it calculates the
+ * diffractogram based on the function.
  *
- * @param peakCollection :: PoldiPeakCollection containing peaks with integral
- *intensities
- * @return Poldi2DFunction with one PoldiSpectrumDomainFunction per peak
+ * @param fitFunction :: IFunction that also implements IPoldiFunction1D.
+ * @param workspace :: Workspace with POLDI raw data.
+ * @return :: Q-based diffractogram.
  */
-Poldi2DFunction_sptr PoldiFitPeaks2D::getFunctionFromPeakCollection(
-    const PoldiPeakCollection_sptr &peakCollection) const {
-  std::string profileFunctionName = getProperty("PeakProfileFunction");
+MatrixWorkspace_sptr PoldiFitPeaks2D::get1DSpectrum(
+    const IFunction_sptr &fitFunction,
+    const API::MatrixWorkspace_sptr &workspace) const {
 
-  bool pawleyFit = getProperty("PawleyFit");
-  if (pawleyFit) {
-    return getFunctionPawley(profileFunctionName, peakCollection);
+  // Check whether the function is of correct type
+  boost::shared_ptr<IPoldiFunction1D> poldiFunction =
+      boost::dynamic_pointer_cast<IPoldiFunction1D>(fitFunction);
+
+  if (!poldiFunction) {
+    throw std::invalid_argument("Can only process Poldi2DFunctions.");
   }
 
-  return getFunctionIndividualPeaks(profileFunctionName, peakCollection);
+  // And that we have an instrument available
+  if (!m_poldiInstrument) {
+    throw std::runtime_error("No POLDI instrument available.");
+  }
+
+  PoldiAbstractDetector_sptr detector(new PoldiDeadWireDecorator(
+      workspace->getInstrument(), m_poldiInstrument->detector()));
+  std::vector<int> indices = detector->availableElements();
+
+  // Create the grid for the diffractogram and corresponding domain/values
+  double lambdaMin = getProperty("LambdaMin");
+  double lambdaMax = getProperty("LambdaMax");
+
+  PoldiDGrid grid(detector, m_poldiInstrument->chopper(), m_deltaT,
+                  std::make_pair(lambdaMin, lambdaMax));
+
+  FunctionDomain1DVector domain(grid.grid());
+  FunctionValues values(domain);
+
+  // Calculate 1D function
+  poldiFunction->poldiFunction1D(indices, domain, values);
+
+  // Create and return Q-based workspace with spectrum
+  return getQSpectrum(domain, values);
 }
 
-/// Executes the algorithm
-void PoldiFitPeaks2D::exec() {
-  TableWorkspace_sptr peakTable = getProperty("PoldiPeakWorkspace");
-  if (!peakTable) {
-    throw std::runtime_error("Cannot proceed without peak workspace.");
-  }
+/// Takes a d-based domain and creates a Q-based MatrixWorkspace.
+MatrixWorkspace_sptr
+PoldiFitPeaks2D::getQSpectrum(const FunctionDomain1D &domain,
+                              const FunctionValues &values) const {
+  // Put result into workspace, based on Q
+  MatrixWorkspace_sptr ws1D = WorkspaceFactory::Instance().create(
+      "Workspace2D", 1, domain.size(), values.size());
 
-  MatrixWorkspace_sptr ws = getProperty("InputWorkspace");
-  setDeltaTFromWorkspace(ws);
+  MantidVec &xData = ws1D->dataX(0);
+  MantidVec &yData = ws1D->dataY(0);
+  size_t offset = values.size() - 1;
+  for (size_t i = 0; i < values.size(); ++i) {
+    xData[offset - i] = Conversions::dToQ(domain[i]);
+    yData[offset - i] = values[i];
+  }
 
-  setPoldiInstrument(boost::make_shared<PoldiInstrumentAdapter>(ws));
-  setTimeTransformerFromInstrument(m_poldiInstrument);
+  ws1D->getAxis(0)->setUnit("MomentumTransfer");
+  return ws1D;
+}
 
-  PoldiPeakCollection_sptr peakCollection = getPeakCollection(peakTable);
+/// Returns a TableWorkspace with refined cell parameters and error.
+ITableWorkspace_sptr PoldiFitPeaks2D::getRefinedCellParameters(
+    const IFunction_sptr &fitFunction) const {
+  Poldi2DFunction_sptr poldi2DFunction =
+      boost::dynamic_pointer_cast<Poldi2DFunction>(fitFunction);
 
-  Property *profileFunctionProperty =
-      getPointerToProperty("PeakProfileFunction");
-  if (!profileFunctionProperty->isDefault()) {
-    peakCollection->setProfileFunctionName(profileFunctionProperty->value());
+  if (!poldi2DFunction || poldi2DFunction->nFunctions() < 1) {
+    throw std::invalid_argument(
+        "Cannot process function that is not a Poldi2DFunction.");
   }
 
-  IAlgorithm_sptr fitAlgorithm = calculateSpectrum(peakCollection, ws);
+  // Create a new table for lattice parameters
+  ITableWorkspace_sptr latticeParameterTable =
+      WorkspaceFactory::Instance().createTable();
 
-  IFunction_sptr fitFunction = getFunction(fitAlgorithm);
+  latticeParameterTable->addColumn("str", "Parameter");
+  latticeParameterTable->addColumn("double", "Value");
+  latticeParameterTable->addColumn("double", "Error");
 
-  MatrixWorkspace_sptr outWs1D = get1DSpectrum(fitFunction, ws);
+  // The first function should be PoldiSpectrumPawleyFunction
+  boost::shared_ptr<PoldiSpectrumPawleyFunction> poldiPawleyFunction =
+      boost::dynamic_pointer_cast<PoldiSpectrumPawleyFunction>(
+          poldi2DFunction->getFunction(0));
 
-  PoldiPeakCollection_sptr normalizedPeaks =
-      getPeakCollectionFromFunction(fitFunction);
-  PoldiPeakCollection_sptr integralPeaks =
-      getCountPeakCollection(normalizedPeaks);
+  if (!poldiPawleyFunction) {
+    throw std::invalid_argument("First function in Poldi2DFunction is not "
+                                "PoldiSpectrumPawleyFunction.");
+  }
 
-  assignMillerIndices(peakCollection, integralPeaks);
+  // Get the actual PawleyFunction to extract parameters.
+  IPawleyFunction_sptr pawleyFunction =
+      boost::dynamic_pointer_cast<IPawleyFunction>(
+          poldiPawleyFunction->getDecoratedFunction());
 
-  setProperty("OutputWorkspace", getWorkspace(fitAlgorithm));
-  setProperty("RefinedPoldiPeakWorkspace", integralPeaks->asTableWorkspace());
-  setProperty("Calculated1DSpectrum", outWs1D);
+  if (pawleyFunction) {
+    CompositeFunction_sptr pawleyParts =
+        boost::dynamic_pointer_cast<CompositeFunction>(
+            pawleyFunction->getDecoratedFunction());
 
-  bool isPawleyFit = getProperty("PawleyFit");
-  if (isPawleyFit) {
-    ITableWorkspace_sptr cellParameters = getRefinedCellParameters(fitFunction);
+    // The first function in PawleyFunction contains the parameters
+    IFunction_sptr pawleyParameters = pawleyParts->getFunction(0);
 
-    if (cellParameters->rowCount() > 0) {
-      setProperty("RefinedCellParameters",
-                  getRefinedCellParameters(fitFunction));
-    } else {
-      g_log.warning() << "Warning: Cell parameter table is empty.";
+    for (size_t i = 0; i < pawleyParameters->nParams(); ++i) {
+      TableRow newRow = latticeParameterTable->appendRow();
+      newRow << pawleyParameters->parameterName(i)
+             << pawleyParameters->getParameter(i)
+             << pawleyParameters->getError(i);
     }
   }
-}
-
-/**
- * Adds background functions for the background if applicable
- *
- * If specified by the user via the corresponding algorithm parameters,
- * this function adds a constant and a linear background term to the
- * supplied Poldi2DFunction.
- *
- * @param poldi2DFunction :: Poldi2DFunction to which the background is added.
- */
-void PoldiFitPeaks2D::addBackgroundTerms(Poldi2DFunction_sptr poldi2DFunction)
-    const {
-  bool addConstantBackground = getProperty("FitConstantBackground");
-  if (addConstantBackground) {
-    IFunction_sptr constantBackground =
-        FunctionFactory::Instance().createFunction(
-            "PoldiSpectrumConstantBackground");
-    constantBackground->setParameter(
-        0, getProperty("ConstantBackgroundParameter"));
-    poldi2DFunction->addFunction(constantBackground);
-  }
 
-  bool addLinearBackground = getProperty("FitLinearBackground");
-  if (addLinearBackground) {
-    IFunction_sptr linearBackground =
-        FunctionFactory::Instance().createFunction(
-            "PoldiSpectrumLinearBackground");
-    linearBackground->setParameter(0, getProperty("LinearBackgroundParameter"));
-    poldi2DFunction->addFunction(linearBackground);
-  }
+  return latticeParameterTable;
 }
 
 /**
@@ -587,20 +873,26 @@ void PoldiFitPeaks2D::addBackgroundTerms(Poldi2DFunction_sptr poldi2DFunction)
  *
  * @param peakCollection :: PoldiPeakCollection
  * @param matrixWorkspace :: MatrixWorkspace with POLDI instrument and correct
- *dimensions
+ *                           dimensions
  * @return Instance of Fit-algorithm, after execution
  */
 IAlgorithm_sptr PoldiFitPeaks2D::calculateSpectrum(
-    const PoldiPeakCollection_sptr &peakCollection,
+    const std::vector<PoldiPeakCollection_sptr> &peakCollections,
     const MatrixWorkspace_sptr &matrixWorkspace) {
-  PoldiPeakCollection_sptr integratedPeaks =
-      getIntegratedPeakCollection(peakCollection);
-  PoldiPeakCollection_sptr normalizedPeakCollection =
-      getNormalizedPeakCollection(integratedPeaks);
 
-  Poldi2DFunction_sptr mdFunction =
-      getFunctionFromPeakCollection(normalizedPeakCollection);
+  std::vector<PoldiPeakCollection_sptr> normalizedPeakCollections =
+      getNormalizedPeakCollections(peakCollections);
+
+  // Create a Poldi2DFunction that collects all sub-functions
+  Poldi2DFunction_sptr mdFunction(new Poldi2DFunction);
+
+  // Add one Poldi2DFunction for each peak collection
+  for (auto pc = normalizedPeakCollections.begin();
+       pc != normalizedPeakCollections.end(); ++pc) {
+    mdFunction->addFunction(getFunctionFromPeakCollection(*pc));
+  }
 
+  // And finally background terms
   addBackgroundTerms(mdFunction);
 
   IAlgorithm_sptr fit = createChildAlgorithm("Fit", -1, -1, true);
@@ -653,72 +945,65 @@ PoldiFitPeaks2D::getFunction(const IAlgorithm_sptr &fitAlgorithm) const {
 }
 
 /**
- * Calculates the 1D diffractogram based on the supplied function
+ * Adds background functions for the background if applicable
  *
- * This method takes a fit function and checks whether it implements the
- * IPoldiFunction1D interface. If that's the case, it calculates the
- * diffractogram based on the function.
+ * If specified by the user via the corresponding algorithm parameters,
+ * this function adds a constant and a linear background term to the
+ * supplied Poldi2DFunction.
  *
- * @param fitFunction :: IFunction that also implements IPoldiFunction1D.
- * @param workspace :: Workspace with POLDI raw data.
- * @return :: Q-based diffractogram.
+ * @param poldi2DFunction :: Poldi2DFunction to which the background is added.
  */
-MatrixWorkspace_sptr PoldiFitPeaks2D::get1DSpectrum(
-    const IFunction_sptr &fitFunction,
-    const API::MatrixWorkspace_sptr &workspace) const {
-
-  // Check whether the function is of correct type
-  boost::shared_ptr<IPoldiFunction1D> poldiFunction =
-      boost::dynamic_pointer_cast<IPoldiFunction1D>(fitFunction);
-
-  if (!poldiFunction) {
-    throw std::invalid_argument("Can only process Poldi2DFunctions.");
-  }
-
-  // And that we have an instrument available
-  if (!m_poldiInstrument) {
-    throw std::runtime_error("No POLDI instrument available.");
+void PoldiFitPeaks2D::addBackgroundTerms(Poldi2DFunction_sptr poldi2DFunction)
+    const {
+  bool addConstantBackground = getProperty("FitConstantBackground");
+  if (addConstantBackground) {
+    IFunction_sptr constantBackground =
+        FunctionFactory::Instance().createFunction(
+            "PoldiSpectrumConstantBackground");
+    constantBackground->setParameter(
+        0, getProperty("ConstantBackgroundParameter"));
+    poldi2DFunction->addFunction(constantBackground);
   }
 
-  PoldiAbstractDetector_sptr detector(new PoldiDeadWireDecorator(
-      workspace->getInstrument(), m_poldiInstrument->detector()));
-  std::vector<int> indices = detector->availableElements();
-
-  // Create the grid for the diffractogram and corresponding domain/values
-  double lambdaMin = getProperty("LambdaMin");
-  double lambdaMax = getProperty("LambdaMax");
-
-  PoldiDGrid grid(detector, m_poldiInstrument->chopper(), m_deltaT,
-                  std::make_pair(lambdaMin, lambdaMax));
-
-  FunctionDomain1DVector domain(grid.grid());
-  FunctionValues values(domain);
-
-  // Calculate 1D function
-  poldiFunction->poldiFunction1D(indices, domain, values);
-
-  // Create and return Q-based workspace with spectrum
-  return getQSpectrum(domain, values);
+  bool addLinearBackground = getProperty("FitLinearBackground");
+  if (addLinearBackground) {
+    IFunction_sptr linearBackground =
+        FunctionFactory::Instance().createFunction(
+            "PoldiSpectrumLinearBackground");
+    linearBackground->setParameter(0, getProperty("LinearBackgroundParameter"));
+    poldi2DFunction->addFunction(linearBackground);
+  }
 }
 
-/// Takes a d-based domain and creates a Q-based MatrixWorkspace.
-MatrixWorkspace_sptr
-PoldiFitPeaks2D::getQSpectrum(const FunctionDomain1D &domain,
-                              const FunctionValues &values) const {
-  // Put result into workspace, based on Q
-  MatrixWorkspace_sptr ws1D = WorkspaceFactory::Instance().create(
-      "Workspace2D", 1, domain.size(), values.size());
+/**
+ * Extracts the covariance matrix for the supplied function
+ *
+ * This method extracts the covariance matrix for a sub-function from
+ * the global covariance matrix. If no matrix is given, a zero-matrix is
+ * returned.
+ *
+ * @param covarianceMatrix :: Global covariance matrix.
+ * @param parameterOffset :: Offset for the parameters of profileFunction.
+ * @param nParams :: Number of parameters of the local function.
+ * @return
+ */
+boost::shared_ptr<DblMatrix> PoldiFitPeaks2D::getLocalCovarianceMatrix(
+    const boost::shared_ptr<const Kernel::DblMatrix> &covarianceMatrix,
+    size_t parameterOffset, size_t nParams) const {
+  if (covarianceMatrix) {
+    boost::shared_ptr<Kernel::DblMatrix> localCov =
+        boost::make_shared<Kernel::DblMatrix>(nParams, nParams, false);
+    for (size_t j = 0; j < nParams; ++j) {
+      for (size_t k = 0; k < nParams; ++k) {
+        (*localCov)[j][k] =
+            (*covarianceMatrix)[parameterOffset + j][parameterOffset + k];
+      }
+    }
 
-  MantidVec &xData = ws1D->dataX(0);
-  MantidVec &yData = ws1D->dataY(0);
-  size_t offset = values.size() - 1;
-  for (size_t i = 0; i < values.size(); ++i) {
-    xData[offset - i] = Conversions::dToQ(domain[i]);
-    yData[offset - i] = values[i];
+    return localCov;
   }
 
-  ws1D->getAxis(0)->setUnit("MomentumTransfer");
-  return ws1D;
+  return boost::make_shared<Kernel::DblMatrix>(nParams, nParams, false);
 }
 
 void PoldiFitPeaks2D::setPoldiInstrument(
@@ -728,7 +1013,7 @@ void PoldiFitPeaks2D::setPoldiInstrument(
 
 /**
  * Constructs a PoldiTimeTransformer from given instrument and calls
- *setTimeTransformer.
+ * setTimeTransformer.
  *
  * @param poldiInstrument :: PoldiInstrumentAdapter with valid components
  */
@@ -751,17 +1036,12 @@ void PoldiFitPeaks2D::setTimeTransformer(
  * Extracts time bin width from workspace parameter
  *
  * The method uses the difference between first and second x-value of the
- *first
- *spectrum as
- * time bin width. If the workspace does not contain proper data (0 spectra or
- *less than
- * 2 x-values), the method throws an std::invalid_argument-exception.
- *Otherwise
- *it calls setDeltaT.
- *
- * @param matrixWorkspace :: MatrixWorkspace with at least one spectrum with
- *at
- *least two x-values.
+ * first spectrum as time bin width. If the workspace does not contain proper
+ * data (0 spectra or less than 2 x-values), the method throws an
+ * std::invalid_argument-exception Otherwise it calls setDeltaT.
+ *
+ * @param matrixWorkspace :: MatrixWorkspace with at least one spectrum with at
+ *                           least two x-values.
  */
 void PoldiFitPeaks2D::setDeltaTFromWorkspace(
     const MatrixWorkspace_sptr &matrixWorkspace) {
@@ -783,8 +1063,7 @@ void PoldiFitPeaks2D::setDeltaTFromWorkspace(
 
 /**
  * Assigns delta t, throws std::invalid_argument on invalid value (determined
- *by
- *isValidDeltaT).
+ * by isValidDeltaT).
  *
  * @param newDeltaT :: Value to be used as delta t for calculations.
  */
@@ -806,203 +1085,153 @@ bool PoldiFitPeaks2D::isValidDeltaT(double deltaT) const {
   return deltaT > 0.0;
 }
 
-/**
- * Tries to construct a PoldiPeakCollection from the supplied table.
- *
- * @param peakTable :: TableWorkspace with POLDI peak data.
- * @return PoldiPeakCollection with the data from the table workspace.
- */
-PoldiPeakCollection_sptr
-PoldiFitPeaks2D::getPeakCollection(const TableWorkspace_sptr &peakTable) const {
-  try {
-    return boost::make_shared<PoldiPeakCollection>(peakTable);
-  }
-  catch (...) {
-    throw std::runtime_error("Could not initialize peak collection.");
-  }
-}
+/// Initialization of algorithm properties.
+void PoldiFitPeaks2D::init() {
+  declareProperty(new WorkspaceProperty<MatrixWorkspace>("InputWorkspace", "",
+                                                         Direction::Input),
+                  "Measured POLDI 2D-spectrum.");
+  declareProperty(new WorkspaceProperty<Workspace>("PoldiPeakWorkspace", "",
+                                                   Direction::Input),
+                  "Table workspace with peak information.");
 
-/**
- * Return peak collection with integrated peaks
- *
- * This method takes a PoldiPeakCollection where the intensity is represented
- *by
- *the maximum. Then
- * it takes the profile function stored in the peak collection, which must be
- *the name of a registered
- * IPeakFunction-implementation. The parameters height and fwhm are assigned,
- *centre is set to 0 to
- * avoid problems with the parameter transformation for the integration from
- *-inf to inf. The profiles are
- * integrated using a PeakFunctionIntegrator to the precision of 1e-10.
- *
- * The original peak collection is not modified, a new instance is created.
- *
- * @param rawPeakCollection :: PoldiPeakCollection
- * @return PoldiPeakCollection with integrated intensities
- */
-PoldiPeakCollection_sptr PoldiFitPeaks2D::getIntegratedPeakCollection(
-    const PoldiPeakCollection_sptr &rawPeakCollection) const {
-  if (!rawPeakCollection) {
-    throw std::invalid_argument(
-        "Cannot proceed with invalid PoldiPeakCollection.");
-  }
+  auto peakFunctionValidator = boost::make_shared<StringListValidator>(
+      FunctionFactory::Instance().getFunctionNames<IPeakFunction>());
+  declareProperty("PeakProfileFunction", "Gaussian", peakFunctionValidator,
+                  "Profile function to use for integrating the peak profiles "
+                  "before calculating the spectrum.");
 
-  if (!isValidDeltaT(m_deltaT)) {
-    throw std::invalid_argument("Cannot proceed with invalid time bin size.");
-  }
+  declareProperty("PawleyFit", false,
+                  "Instead of refining individual peaks, "
+                  "refine a unit cell. Peaks must be "
+                  "indexed using PoldiIndexKnownCompounds.");
 
-  if (!m_timeTransformer) {
-    throw std::invalid_argument(
-        "Cannot proceed with invalid PoldiTimeTransformer.");
-  }
+  declareProperty("FitConstantBackground", true,
+                  "Add a constant background term to the fit.");
+  declareProperty("ConstantBackgroundParameter", 0.0,
+                  "Initial value of constant background.");
 
-  if (rawPeakCollection->intensityType() == PoldiPeakCollection::Integral) {
-    /* Intensities are integral already - don't need to do anything,
-     * except cloning the collection, to make behavior consistent, since
-     * integrating also results in a new peak collection.
-     */
-    return rawPeakCollection->clone();
-  }
+  declareProperty("FitLinearBackground", true,
+                  "Add a background term linear in 2theta to the fit.");
+  declareProperty("LinearBackgroundParameter", 0.0,
+                  "Initial value of linear background.");
 
-  /* If no profile function is specified, it's not possible to get integrated
-   * intensities at all and we try to use the one specified by the user
-   * instead.
-   */
-  std::string profileFunctionName = rawPeakCollection->getProfileFunctionName();
+  declareProperty("MaximumIterations", 0, "Maximum number of iterations for "
+                                          "the fit. Use 0 to calculate "
+                                          "2D-spectrum without fitting.");
 
-  if (!rawPeakCollection->hasProfileFunctionName()) {
-    profileFunctionName = getPropertyValue("PeakProfileFunction");
-  }
+  declareProperty(new WorkspaceProperty<MatrixWorkspace>("OutputWorkspace", "",
+                                                         Direction::Output),
+                  "Calculated POLDI 2D-spectrum");
+  declareProperty(new WorkspaceProperty<MatrixWorkspace>("Calculated1DSpectrum",
+                                                         "", Direction::Output),
+                  "Calculated POLDI 1D-spectrum.");
 
-  std::vector<std::string> allowedProfiles =
-      FunctionFactory::Instance().getFunctionNames<IPeakFunction>();
+  declareProperty("LambdaMin", 1.1,
+                  "Minimum wavelength for 1D spectrum calculation");
+  declareProperty("LambdaMax", 5.0,
+                  "Maximum wavelength for 1D spectrum calculation");
 
-  if (std::find(allowedProfiles.begin(), allowedProfiles.end(),
-                profileFunctionName) == allowedProfiles.end()) {
-    throw std::runtime_error(
-        "Cannot integrate peak profiles with invalid profile function.");
-  }
+  declareProperty(new WorkspaceProperty<Workspace>("RefinedPoldiPeakWorkspace",
+                                                   "", Direction::Output),
+                  "Table workspace with fitted peaks.");
 
-  PoldiPeakCollection_sptr integratedPeakCollection =
-      boost::make_shared<PoldiPeakCollection>(PoldiPeakCollection::Integral);
-  integratedPeakCollection->setProfileFunctionName(profileFunctionName);
+  declareProperty(new WorkspaceProperty<Workspace>(
+      "RefinedCellParameters", "", Direction::Output, PropertyMode::Optional));
+}
 
-  for (size_t i = 0; i < rawPeakCollection->peakCount(); ++i) {
-    PoldiPeak_sptr peak = rawPeakCollection->peak(i);
+/// Executes the algorithm
+void PoldiFitPeaks2D::exec() {
+  std::vector<PoldiPeakCollection_sptr> peakCollections =
+      getPeakCollectionsFromInput();
 
-    IPeakFunction_sptr profileFunction =
-        boost::dynamic_pointer_cast<IPeakFunction>(
-            FunctionFactory::Instance().createFunction(profileFunctionName));
+  // Try to setup the 2D data and poldi instrument
+  MatrixWorkspace_sptr ws = getProperty("InputWorkspace");
+  setDeltaTFromWorkspace(ws);
 
-    profileFunction->setHeight(peak->intensity());
-    profileFunction->setFwhm(peak->fwhm(PoldiPeak::AbsoluteD));
+  setPoldiInstrument(boost::make_shared<PoldiInstrumentAdapter>(ws));
+  setTimeTransformerFromInstrument(m_poldiInstrument);
 
-    PoldiPeak_sptr integratedPeak = peak->clone();
-    integratedPeak->setIntensity(UncertainValue(profileFunction->intensity()));
-    integratedPeakCollection->addPeak(integratedPeak);
+  // If a profile function is selected, set it on the peak collections.
+  Property *profileFunctionProperty =
+      getPointerToProperty("PeakProfileFunction");
+  if (!profileFunctionProperty->isDefault()) {
+    for (auto pc = peakCollections.begin(); pc != peakCollections.end(); ++pc) {
+      (*pc)->setProfileFunctionName(profileFunctionProperty->value());
+    }
   }
 
-  return integratedPeakCollection;
-}
-
-/**
- * Normalized the intensities of the given integrated peaks
- *
- * This function normalizes the peak intensities according to the source
- *spectrum, the number of
- * chopper slits and the number of detector elements.
- *
- * @param peakCollection :: PoldiPeakCollection with integrated intensities
- * @return PoldiPeakCollection with normalized intensities
- */
-PoldiPeakCollection_sptr PoldiFitPeaks2D::getNormalizedPeakCollection(
-    const PoldiPeakCollection_sptr &peakCollection) const {
-  if (!peakCollection) {
-    throw std::invalid_argument(
-        "Cannot proceed with invalid PoldiPeakCollection.");
-  }
+  // Perform 2D-fit and return Fit algorithm to extract various information
+  IAlgorithm_sptr fitAlgorithm = calculateSpectrum(peakCollections, ws);
 
-  if (!m_timeTransformer) {
-    throw std::invalid_argument("Cannot proceed without PoldiTimeTransformer.");
-  }
+  // The FitFunction is used to generate...
+  IFunction_sptr fitFunction = getFunction(fitAlgorithm);
 
-  PoldiPeakCollection_sptr normalizedPeakCollection =
-      boost::make_shared<PoldiPeakCollection>(PoldiPeakCollection::Integral);
-  normalizedPeakCollection->setProfileFunctionName(
-      peakCollection->getProfileFunctionName());
+  // ...a calculated 1D-spectrum...
+  MatrixWorkspace_sptr outWs1D = get1DSpectrum(fitFunction, ws);
 
-  for (size_t i = 0; i < peakCollection->peakCount(); ++i) {
-    PoldiPeak_sptr peak = peakCollection->peak(i);
-    double calculatedIntensity =
-        m_timeTransformer->calculatedTotalIntensity(peak->d());
+  // ...a vector of peak collections.
+  std::vector<PoldiPeakCollection_sptr> integralPeaks =
+      getCountPeakCollections(fitFunction);
 
-    PoldiPeak_sptr normalizedPeak = peak->clone();
-    normalizedPeak->setIntensity(peak->intensity() / calculatedIntensity);
-    normalizedPeakCollection->addPeak(normalizedPeak);
+  for(size_t i = 0; i < peakCollections.size(); ++i) {
+      assignMillerIndices(peakCollections[i], integralPeaks[i]);
   }
 
-  return normalizedPeakCollection;
-}
+  // Get the calculated 2D workspace
+  setProperty("OutputWorkspace", getWorkspace(fitAlgorithm));
 
-/**
- * Converts normalized peak intensities to count based integral intensities
- *
- * This operation is the opposite of getNormalizedPeakCollection and is used
- *to
- *convert
- * the intensities back to integral intensities.
- *
- * @param peakCollection :: PoldiPeakCollection with normalized intensities
- * @return PoldiPeakCollection with integral intensities
- */
-PoldiPeakCollection_sptr PoldiFitPeaks2D::getCountPeakCollection(
-    const PoldiPeakCollection_sptr &peakCollection) const {
-  if (!peakCollection) {
-    throw std::invalid_argument(
-        "Cannot proceed with invalid PoldiPeakCollection.");
-  }
+  // Set the output peaks depending on whether it's one or more workspaces
+  if (integralPeaks.size() == 1) {
+    setProperty("RefinedPoldiPeakWorkspace",
+                integralPeaks.front()->asTableWorkspace());
+  } else {
+    WorkspaceGroup_sptr peaksGroup = boost::make_shared<WorkspaceGroup>();
 
-  if (!m_timeTransformer) {
-    throw std::invalid_argument("Cannot proceed without PoldiTimeTransformer.");
-  }
+    for (auto pc = integralPeaks.begin(); pc != integralPeaks.end(); ++pc) {
+      peaksGroup->addWorkspace((*pc)->asTableWorkspace());
+    }
 
-  PoldiPeakCollection_sptr countPeakCollection =
-      boost::make_shared<PoldiPeakCollection>(PoldiPeakCollection::Integral);
-  countPeakCollection->setProfileFunctionName(
-      peakCollection->getProfileFunctionName());
+    setProperty("RefinedPoldiPeakWorkspace", peaksGroup);
+  }
 
-  for (size_t i = 0; i < peakCollection->peakCount(); ++i) {
-    PoldiPeak_sptr peak = peakCollection->peak(i);
-    double calculatedIntensity =
-        m_timeTransformer->calculatedTotalIntensity(peak->d());
+  // Set the 1D-spectrum output
+  setProperty("Calculated1DSpectrum", outWs1D);
 
-    PoldiPeak_sptr countPeak = peak->clone();
-    countPeak->setIntensity(peak->intensity() * calculatedIntensity);
+  // If it was a PawleyFit, also produce one or more cell parameter tables.
+  bool isPawleyFit = getProperty("PawleyFit");
+  if (isPawleyFit) {
+    Poldi2DFunction_sptr poldi2DFunction =
+        boost::dynamic_pointer_cast<Poldi2DFunction>(fitFunction);
 
-    countPeakCollection->addPeak(countPeak);
-  }
+    std::vector<ITableWorkspace_sptr> cells;
 
-  return countPeakCollection;
-}
+    if (poldi2DFunction) {
+      for (size_t i = 0; i < poldi2DFunction->nFunctions(); ++i) {
+        try {
+          ITableWorkspace_sptr cell =
+              getRefinedCellParameters(poldi2DFunction->getFunction(i));
+          cells.push_back(cell);
+        }
+        catch (std::invalid_argument) {
+          // do nothing
+        }
+      }
 
-/// Assign Miller indices from one peak collection to another.
-void PoldiFitPeaks2D::assignMillerIndices(const PoldiPeakCollection_sptr &from,
-                                          PoldiPeakCollection_sptr &to) const {
-  if (!from || !to) {
-    throw std::invalid_argument("Cannot process invalid peak collections.");
-  }
+      if (cells.size() == 1) {
+        setProperty("RefinedCellParameters", cells.front());
+      } else {
+        WorkspaceGroup_sptr cellsGroup = boost::make_shared<WorkspaceGroup>();
 
-  if (from->peakCount() != to->peakCount()) {
-    throw std::runtime_error(
-        "Cannot assign indices if number of peaks does not match.");
-  }
+        for (auto it = cells.begin(); it != cells.end(); ++it) {
+          cellsGroup->addWorkspace(*it);
+        }
 
-  for (size_t i = 0; i < from->peakCount(); ++i) {
-    PoldiPeak_sptr fromPeak = from->peak(i);
-    PoldiPeak_sptr toPeak = to->peak(i);
+        setProperty("RefinedCellParameters", cellsGroup);
+      }
 
-    toPeak->setHKL(fromPeak->hkl());
+    } else {
+      g_log.warning() << "Warning: Cell parameter table is empty.";
+    }
   }
 }
 
diff --git a/Code/Mantid/Framework/SINQ/src/PoldiIndexKnownCompounds.cpp b/Code/Mantid/Framework/SINQ/src/PoldiIndexKnownCompounds.cpp
index 80eb0093d7374230935d6101b4f85b16292379c7..626dae94cecd1e23a45ffbbfb0ccfeb08b392c58 100644
--- a/Code/Mantid/Framework/SINQ/src/PoldiIndexKnownCompounds.cpp
+++ b/Code/Mantid/Framework/SINQ/src/PoldiIndexKnownCompounds.cpp
@@ -747,6 +747,14 @@ PoldiIndexKnownCompounds::getIntensitySortedPeakCollection(
   return sortedPeaks;
 }
 
+void PoldiIndexKnownCompounds::assignCrystalStructureParameters(
+    PoldiPeakCollection_sptr &indexedPeaks,
+    const PoldiPeakCollection_sptr &phasePeaks) const {
+
+  indexedPeaks->setPointGroup(phasePeaks->pointGroup());
+  indexedPeaks->setUnitCell(phasePeaks->unitCell());
+}
+
 /** Initialize the algorithm's properties.
    */
 void PoldiIndexKnownCompounds::init() {
@@ -831,23 +839,26 @@ void PoldiIndexKnownCompounds::exec() {
   /* Finally, the peaks are put into separate workspaces, determined by
    * the phase they have been attributed to, plus unindexed peaks.
    */
+  std::string inputWorkspaceName = getPropertyValue("InputWorkspace");
   WorkspaceGroup_sptr outputWorkspaces = boost::make_shared<WorkspaceGroup>();
 
   for (size_t i = 0; i < m_indexedPeaks.size(); ++i) {
     PoldiPeakCollection_sptr intensitySorted =
         getIntensitySortedPeakCollection(m_indexedPeaks[i]);
+
+    assignCrystalStructureParameters(intensitySorted, m_expectedPhases[i]);
+
     ITableWorkspace_sptr tableWs = intensitySorted->asTableWorkspace();
-    AnalysisDataService::Instance().addOrReplace("Indexed_" + m_phaseNames[i],
-                                                 tableWs);
+    AnalysisDataService::Instance().addOrReplace(
+        inputWorkspaceName + "_indexed_" + m_phaseNames[i], tableWs);
 
     outputWorkspaces->addWorkspace(tableWs);
   }
 
   ITableWorkspace_sptr unindexedTableWs = m_unindexedPeaks->asTableWorkspace();
 
-  std::string inputWorkspaceName = getPropertyValue("InputWorkspace");
   AnalysisDataService::Instance().addOrReplace(
-      "Unindexed_" + inputWorkspaceName, unindexedTableWs);
+      inputWorkspaceName + "_unindexed", unindexedTableWs);
   outputWorkspaces->addWorkspace(unindexedTableWs);
 
   setProperty("OutputWorkspace", outputWorkspaces);
diff --git a/Code/Mantid/Framework/SINQ/src/PoldiPeakSearch.cpp b/Code/Mantid/Framework/SINQ/src/PoldiPeakSearch.cpp
index 384743a5834001d2a7d9368c82e3e26f5b1268c5..ff51a3319bffb169579997815c95040604cd97ba 100644
--- a/Code/Mantid/Framework/SINQ/src/PoldiPeakSearch.cpp
+++ b/Code/Mantid/Framework/SINQ/src/PoldiPeakSearch.cpp
@@ -632,7 +632,7 @@ void PoldiPeakSearch::exec() {
   auto newEnd = std::remove_copy_if(
       peakCoordinates.begin(), peakCoordinates.end(),
       intensityFilteredPeaks.begin(),
-      boost::bind<bool>(&PoldiPeakSearch::isLessThanMinimum, this, _1));
+      boost::bind(&PoldiPeakSearch::isLessThanMinimum, this, _1));
   intensityFilteredPeaks.resize(
       std::distance(intensityFilteredPeaks.begin(), newEnd));
 
diff --git a/Code/Mantid/Framework/SINQ/src/PoldiUtilities/PoldiAutoCorrelationCore.cpp b/Code/Mantid/Framework/SINQ/src/PoldiUtilities/PoldiAutoCorrelationCore.cpp
index fd7be8b349ba0248303d52b8ec76736a3764cd6a..d1715e50f383fe52ed4f5f12750dea35d549f70f 100644
--- a/Code/Mantid/Framework/SINQ/src/PoldiUtilities/PoldiAutoCorrelationCore.cpp
+++ b/Code/Mantid/Framework/SINQ/src/PoldiUtilities/PoldiAutoCorrelationCore.cpp
@@ -205,7 +205,7 @@ DataObjects::Workspace2D_sptr PoldiAutoCorrelationCore::calculate(
     std::transform(
         rawCorrelatedIntensities.begin(), rawCorrelatedIntensities.end(),
         m_weightsForD.begin(), correctedCorrelatedIntensities.rbegin(),
-        boost::bind<double>(&PoldiAutoCorrelationCore::correctedIntensity, this,
+        boost::bind(&PoldiAutoCorrelationCore::correctedIntensity, this,
                             _1, _2));
 
     /* The algorithm performs some finalization. In the default case the
@@ -315,7 +315,7 @@ PoldiAutoCorrelationCore::getRawCorrelatedIntensity(double dValue,
        */
       std::vector<UncertainValue> cmess(m_detector->elementCount());
       std::transform(m_indices.begin(), m_indices.end(), cmess.begin(),
-                     boost::bind<UncertainValue>(
+                     boost::bind(
                          &PoldiAutoCorrelationCore::getCMessAndCSigma, this,
                          dValue, *slitOffset, _1));
 
@@ -589,7 +589,7 @@ std::vector<double> PoldiAutoCorrelationCore::getTofsFor1Angstrom(
   std::vector<double> twoThetas(elements.size());
   std::transform(
       elements.begin(), elements.end(), twoThetas.begin(),
-      boost::bind<double>(&PoldiAbstractDetector::twoTheta, m_detector, _1));
+      boost::bind(&PoldiAbstractDetector::twoTheta, m_detector, _1));
 
   // We will need sin(Theta) anyway, so we might just calculate those as well
   std::vector<double> sinThetas;
@@ -607,7 +607,7 @@ std::vector<double> PoldiAutoCorrelationCore::getTofsFor1Angstrom(
   std::vector<double> tofFor1Angstrom(elements.size());
   std::transform(distances.begin(), distances.end(), sinThetas.begin(),
                  tofFor1Angstrom.begin(),
-                 boost::bind<double>(&Conversions::dtoTOF, 1.0, _1, _2));
+                 boost::bind(&Conversions::dtoTOF, 1.0, _1, _2));
 
   return tofFor1Angstrom;
 }
diff --git a/Code/Mantid/Framework/SINQ/src/PoldiUtilities/PoldiBasicChopper.cpp b/Code/Mantid/Framework/SINQ/src/PoldiUtilities/PoldiBasicChopper.cpp
index 3137237487a1f801ba122f1218477ea1ac55af8f..076f33fd31ff9b5326ba558d580b7a2591d3df08 100644
--- a/Code/Mantid/Framework/SINQ/src/PoldiUtilities/PoldiBasicChopper.cpp
+++ b/Code/Mantid/Framework/SINQ/src/PoldiUtilities/PoldiBasicChopper.cpp
@@ -77,7 +77,7 @@ void PoldiBasicChopper::initializeVariableParameters(double rotationSpeed) {
   m_slitTimes.resize(m_slitPositions.size());
   std::transform(m_slitPositions.begin(), m_slitPositions.end(),
                  m_slitTimes.begin(),
-                 boost::bind<double>(
+                 boost::bind(
                      &PoldiBasicChopper::slitPositionToTimeFraction, this, _1));
 }
 
diff --git a/Code/Mantid/Framework/SINQ/src/PoldiUtilities/PoldiDeadWireDecorator.cpp b/Code/Mantid/Framework/SINQ/src/PoldiUtilities/PoldiDeadWireDecorator.cpp
index c901b0de4fc181e23b854e12d811bf204bec7ce2..25b3490e5fe9b4b879c6fb40e273d02f250204b3 100644
--- a/Code/Mantid/Framework/SINQ/src/PoldiUtilities/PoldiDeadWireDecorator.cpp
+++ b/Code/Mantid/Framework/SINQ/src/PoldiUtilities/PoldiDeadWireDecorator.cpp
@@ -68,7 +68,7 @@ PoldiDeadWireDecorator::getGoodElements(std::vector<int> rawElements) {
     std::vector<int> goodElements(newElementCount);
     std::remove_copy_if(
         rawElements.begin(), rawElements.end(), goodElements.begin(),
-        boost::bind<bool>(&PoldiDeadWireDecorator::isDeadElement, this, _1));
+        boost::bind(&PoldiDeadWireDecorator::isDeadElement, this, _1));
 
     return goodElements;
   }
diff --git a/Code/Mantid/Framework/SINQ/src/PoldiUtilities/PoldiPeak.cpp b/Code/Mantid/Framework/SINQ/src/PoldiUtilities/PoldiPeak.cpp
index 82615b639c42eea9984778e8853a40fbcf82c515..21456eb70f4846fe667693a05ae6a1e6209fb32e 100644
--- a/Code/Mantid/Framework/SINQ/src/PoldiUtilities/PoldiPeak.cpp
+++ b/Code/Mantid/Framework/SINQ/src/PoldiUtilities/PoldiPeak.cpp
@@ -127,18 +127,18 @@ bool PoldiPeak::greaterThan(const PoldiPeak_sptr &first,
                             const PoldiPeak_sptr &second,
                             UncertainValue (PoldiPeak::*function)() const) {
   return static_cast<double>(
-             boost::bind<UncertainValue>(function, first.get())()) >
+             boost::bind(function, first.get())()) >
          static_cast<double>(
-             boost::bind<UncertainValue>(function, second.get())());
+             boost::bind(function, second.get())());
 }
 
 bool PoldiPeak::lessThan(const PoldiPeak_sptr &first,
                          const PoldiPeak_sptr &second,
                          UncertainValue (PoldiPeak::*function)() const) {
   return static_cast<double>(
-             boost::bind<UncertainValue>(function, first.get())()) <
+             boost::bind(function, first.get())()) <
          static_cast<double>(
-             boost::bind<UncertainValue>(function, second.get())());
+             boost::bind(function, second.get())());
 }
 
 PoldiPeak::PoldiPeak(UncertainValue d, UncertainValue intensity,
diff --git a/Code/Mantid/Framework/SINQ/src/PoldiUtilities/PoldiPeakCollection.cpp b/Code/Mantid/Framework/SINQ/src/PoldiUtilities/PoldiPeakCollection.cpp
index dd2f70f3eca36c46de048fe9465b7845ee59d81f..14b66276b8095263d6b91c40316c88244c300e89 100644
--- a/Code/Mantid/Framework/SINQ/src/PoldiUtilities/PoldiPeakCollection.cpp
+++ b/Code/Mantid/Framework/SINQ/src/PoldiUtilities/PoldiPeakCollection.cpp
@@ -2,6 +2,8 @@
 #include "MantidAPI/TableRow.h"
 #include "MantidAPI/WorkspaceFactory.h"
 #include "MantidAPI/LogManager.h"
+#include "MantidGeometry/Crystal/PointGroupFactory.h"
+
 #include "boost/format.hpp"
 #include "boost/algorithm/string/join.hpp"
 
@@ -18,11 +20,13 @@ using namespace Mantid::Kernel;
 
 PoldiPeakCollection::PoldiPeakCollection(IntensityType intensityType)
     : m_peaks(), m_intensityType(intensityType), m_profileFunctionName(),
-      m_pointGroup() {}
+      m_pointGroup(PointGroupFactory::Instance().createPointGroup("1")),
+      m_unitCell() {}
 
 PoldiPeakCollection::PoldiPeakCollection(const TableWorkspace_sptr &workspace)
     : m_peaks(), m_intensityType(Maximum), m_profileFunctionName(),
-      m_pointGroup() {
+      m_pointGroup(PointGroupFactory::Instance().createPointGroup("1")),
+      m_unitCell() {
   if (workspace) {
     constructFromTableWorkspace(workspace);
   }
@@ -38,8 +42,10 @@ PoldiPeakCollection::PoldiPeakCollection(
         "Cannot create PoldiPeakCollection from invalid CrystalStructure.");
   }
 
-  m_pointGroup =
-      pointGroupFromString(pointGroupToString(crystalStructure->pointGroup()));
+  m_pointGroup = PointGroupFactory::Instance().createPointGroupFromSpaceGroup(
+      crystalStructure->spaceGroup());
+
+  m_unitCell = crystalStructure->cell();
 
   std::vector<V3D> uniqueHKL = crystalStructure->getUniqueHKLs(
       dMin, dMax, Geometry::CrystalStructure::UseStructureFactor);
@@ -54,6 +60,8 @@ PoldiPeakCollection_sptr PoldiPeakCollection::clone() {
   PoldiPeakCollection_sptr clone =
       boost::make_shared<PoldiPeakCollection>(m_intensityType);
   clone->setProfileFunctionName(m_profileFunctionName);
+  clone->setPointGroup(m_pointGroup);
+  clone->setUnitCell(m_unitCell);
 
   for (size_t i = 0; i < m_peaks.size(); ++i) {
     clone->addPeak(m_peaks[i]->clone());
@@ -98,11 +106,23 @@ bool PoldiPeakCollection::hasProfileFunctionName() const {
 }
 
 void PoldiPeakCollection::setPointGroup(const PointGroup_sptr &pointGroup) {
-  m_pointGroup = pointGroup;
+  if (!pointGroup) {
+    throw std::invalid_argument(
+        "Cannot assign null-pointer to pointgroup in PoldiPeakCollection.");
+  }
+
+  m_pointGroup =
+      PointGroupFactory::Instance().createPointGroup(pointGroup->getSymbol());
 }
 
 PointGroup_sptr PoldiPeakCollection::pointGroup() const { return m_pointGroup; }
 
+void PoldiPeakCollection::setUnitCell(const UnitCell &unitCell) {
+  m_unitCell = unitCell;
+}
+
+UnitCell PoldiPeakCollection::unitCell() const { return m_unitCell; }
+
 TableWorkspace_sptr PoldiPeakCollection::asTableWorkspace() {
   TableWorkspace_sptr peaks = boost::dynamic_pointer_cast<TableWorkspace>(
       WorkspaceFactory::Instance().createTable());
@@ -130,6 +150,8 @@ void PoldiPeakCollection::dataToTableLog(const TableWorkspace_sptr &table) {
                                      m_profileFunctionName);
   tableLog->addProperty<std::string>("PointGroup",
                                      pointGroupToString(m_pointGroup));
+  tableLog->addProperty<std::string>("UnitCell",
+                                     Geometry::unitCellToStr(m_unitCell));
 }
 
 void PoldiPeakCollection::peaksToTable(const TableWorkspace_sptr &table) {
@@ -216,6 +238,7 @@ void PoldiPeakCollection::recoverDataFromLog(
   m_intensityType = intensityTypeFromString(getIntensityTypeFromLog(tableLog));
   m_profileFunctionName = getProfileFunctionNameFromLog(tableLog);
   m_pointGroup = pointGroupFromString(getPointGroupStringFromLog(tableLog));
+  m_unitCell = unitCellFromString(getUnitCellStringFromLog(tableLog));
 }
 
 std::string
@@ -233,6 +256,11 @@ std::string PoldiPeakCollection::getPointGroupStringFromLog(
   return getStringValueFromLog(tableLog, "PointGroup");
 }
 
+std::string
+PoldiPeakCollection::getUnitCellStringFromLog(const LogManager_sptr &tableLog) {
+  return getStringValueFromLog(tableLog, "UnitCell");
+}
+
 std::string
 PoldiPeakCollection::getStringValueFromLog(const LogManager_sptr &logManager,
                                            std::string valueName) {
@@ -271,22 +299,33 @@ PoldiPeakCollection::intensityTypeFromString(std::string typeString) const {
 std::string PoldiPeakCollection::pointGroupToString(
     const PointGroup_sptr &pointGroup) const {
   if (pointGroup) {
-    return pointGroup->getName();
+    return pointGroup->getSymbol();
   }
 
-  return "";
+  return "1";
 }
 
 PointGroup_sptr PoldiPeakCollection::pointGroupFromString(
     const std::string &pointGroupString) const {
-  std::vector<PointGroup_sptr> allPointGroups = getAllPointGroups();
-  for (auto it = allPointGroups.begin(); it != allPointGroups.end(); ++it) {
-    if ((*it)->getName() == pointGroupString) {
-      return *it;
-    }
+  if (PointGroupFactory::Instance().isSubscribed(pointGroupString)) {
+    return PointGroupFactory::Instance().createPointGroup(pointGroupString);
+  }
+
+  return PointGroupFactory::Instance().createPointGroup("1");
+}
+
+UnitCell PoldiPeakCollection::unitCellFromString(
+    const std::string &unitCellString) const {
+  UnitCell cell;
+
+  try {
+    cell = strToUnitCell(unitCellString);
+  }
+  catch (std::runtime_error) {
+    // do nothing
   }
 
-  return PointGroup_sptr();
+  return cell;
 }
 }
 }
diff --git a/Code/Mantid/Framework/SINQ/test/PoldiFitPeaks2DTest.h b/Code/Mantid/Framework/SINQ/test/PoldiFitPeaks2DTest.h
index 88f8e3f7f6a6d8091fa3ca2809cd59489089b625..4eb4a00e1339592e0bcd548fd1ca026df564344a 100644
--- a/Code/Mantid/Framework/SINQ/test/PoldiFitPeaks2DTest.h
+++ b/Code/Mantid/Framework/SINQ/test/PoldiFitPeaks2DTest.h
@@ -322,6 +322,39 @@ public:
         TS_ASSERT_EQUALS(funConstant->nFunctions(), 1);
     }
 
+    void testGetRefinedStartingCell() {
+        // Get Silicon peaks for testing
+        PoldiPeakCollection_sptr peaks = PoldiPeakCollectionHelpers::createPoldiPeakCollectionNormalized();
+
+        TestablePoldiFitPeaks2D alg;
+
+        std::string refinedCell;
+        TS_ASSERT_THROWS_NOTHING(
+                    refinedCell = alg.getRefinedStartingCell(
+                                        "5.4 5.4 5.4 90 90 90",
+                                        "Cubic", peaks));
+
+        UnitCell cell = strToUnitCell(refinedCell);
+        TS_ASSERT_DELTA(cell.a(), 5.43111972, 1e-8);
+
+        // With less accurate starting parameters the result should not change
+        TS_ASSERT_THROWS_NOTHING(
+                    refinedCell = alg.getRefinedStartingCell(
+                                        "5 5 5 90 90 90",
+                                        "Cubic", peaks));
+
+        cell = strToUnitCell(refinedCell);
+        TS_ASSERT_DELTA(cell.a(), 5.43111972, 1e-8);
+
+        // Adding an unindexed peak should make the function return the initial
+        peaks->addPeak(PoldiPeak::create(UncertainValue(1.0)));
+        TS_ASSERT_THROWS_NOTHING(
+                    refinedCell = alg.getRefinedStartingCell(
+                                        "5 5 5 90 90 90",
+                                        "Cubic", peaks));
+        TS_ASSERT_EQUALS(refinedCell, "5 5 5 90 90 90");
+    }
+
 private:
     PoldiInstrumentAdapter_sptr m_instrument;
     PoldiTimeTransformer_sptr m_timeTransformer;
diff --git a/Code/Mantid/Framework/SINQ/test/PoldiIndexKnownCompoundsTest.h b/Code/Mantid/Framework/SINQ/test/PoldiIndexKnownCompoundsTest.h
index 7aa9f31704841fec979638309b159bbf5ac2668a..a15d75bdd30191687b6aa3ffc5c9f49887f0a2a5 100644
--- a/Code/Mantid/Framework/SINQ/test/PoldiIndexKnownCompoundsTest.h
+++ b/Code/Mantid/Framework/SINQ/test/PoldiIndexKnownCompoundsTest.h
@@ -73,16 +73,23 @@ public:
         // Table with peaks that can be attributed to Si
         ITableWorkspace_sptr tableSi = boost::dynamic_pointer_cast<ITableWorkspace>(indexedSi);
         TS_ASSERT(tableSi);
-        TS_ASSERT_EQUALS(tableSi->getName(), "Indexed_Si");
+        TS_ASSERT_EQUALS(tableSi->getName(), "measured_SI_indexed_Si");
         TS_ASSERT_EQUALS(tableSi->rowCount(), 4);
 
+        // Make sure unit cell and point group is carried over from compound ws
+        ITableWorkspace_sptr si = AnalysisDataService::Instance().retrieveWS<ITableWorkspace>("Si");
+        TS_ASSERT_EQUALS(tableSi->getLogs()->getProperty("PointGroup")->value(),
+                         si->getLogs()->getProperty("PointGroup")->value());
+        TS_ASSERT_EQUALS(tableSi->getLogs()->getProperty("UnitCell")->value(),
+                         si->getLogs()->getProperty("UnitCell")->value());
+
         Workspace_sptr unindexed = group->getItem(1);
         TS_ASSERT(unindexed);
 
         // Table with peaks that can be attributed to Si
         ITableWorkspace_sptr tableUnindexed = boost::dynamic_pointer_cast<ITableWorkspace>(unindexed);
         TS_ASSERT(tableUnindexed);
-        TS_ASSERT_EQUALS(tableUnindexed->getName(), "Unindexed_measured_SI");
+        TS_ASSERT_EQUALS(tableUnindexed->getName(), "measured_SI_unindexed");
         TS_ASSERT_EQUALS(tableUnindexed->rowCount(), 0);
 
         AnalysisDataService::Instance().remove(outWSName);
diff --git a/Code/Mantid/Framework/SINQ/test/PoldiPeakCollectionTest.h b/Code/Mantid/Framework/SINQ/test/PoldiPeakCollectionTest.h
index d185414f3e6f0789e09891e1e2e6b784a3cfd118..9e83499e21ba6929547797e4d3cb1edb3f5f07d3 100644
--- a/Code/Mantid/Framework/SINQ/test/PoldiPeakCollectionTest.h
+++ b/Code/Mantid/Framework/SINQ/test/PoldiPeakCollectionTest.h
@@ -186,12 +186,43 @@ public:
     void testPointGroup()
     {
         PoldiPeakCollection peaks;
-        TS_ASSERT(!peaks.pointGroup());
+        TS_ASSERT_EQUALS(peaks.pointGroup()->getSymbol(), "1");
 
         PointGroup_sptr m3m = PointGroupFactory::Instance().createPointGroup("m-3m");
 
         peaks.setPointGroup(m3m);
         TS_ASSERT_EQUALS(peaks.pointGroup()->getName(), m3m->getName());
+
+        // It should not be the same instance.
+        TS_ASSERT_DIFFERS(peaks.pointGroup(), m3m);
+
+        PointGroup_sptr invalid;
+        TS_ASSERT_THROWS(peaks.setPointGroup(invalid), std::invalid_argument);
+    }
+
+    void testUnitCell()
+    {
+        PoldiPeakCollection peaks;
+
+        UnitCell defaultCell;
+        TS_ASSERT_EQUALS(unitCellToStr(peaks.unitCell()), unitCellToStr(defaultCell));
+
+        UnitCell cell(1, 2, 3, 90, 91, 92);
+        peaks.setUnitCell(cell);
+
+        UnitCell newCell = peaks.unitCell();
+        TS_ASSERT_EQUALS(unitCellToStr(newCell), unitCellToStr(cell));
+    }
+
+    void testUnitCellFromLogs()
+    {
+        TableWorkspace_sptr newDummy(m_dummyData->clone());
+
+        UnitCell cell(1, 2, 3, 90, 91, 92);
+        newDummy->logs()->addProperty<std::string>("UnitCell", unitCellToStr(cell));
+
+        PoldiPeakCollection collection(newDummy);
+        TS_ASSERT_EQUALS(unitCellToStr(collection.unitCell()), unitCellToStr(cell));
     }
 
     void testPointGroupStringConversion()
@@ -200,13 +231,10 @@ public:
         PointGroup_sptr m3m = PointGroupFactory::Instance().createPointGroup("m-3m");
 
         TS_ASSERT(peaks.pointGroupFromString(peaks.pointGroupToString(m3m)));
-
-        std::cout << m3m->getName() << std::endl;
-
-        std::vector<PointGroup_sptr> pgs = getAllPointGroups();
-        std::cout << "Size:  " << pgs.size() << std::endl;
-
         TS_ASSERT_EQUALS(m3m->getName(), peaks.pointGroupFromString(peaks.pointGroupToString(m3m))->getName());
+
+        PointGroup_sptr one = PointGroupFactory::Instance().createPointGroup("1");
+        TS_ASSERT_EQUALS(peaks.pointGroupFromString("DoesNotExist")->getSymbol(), one->getSymbol());
     }
 
     void testGetPointGroupStringFromLog()
@@ -276,6 +304,8 @@ public:
         TS_ASSERT_EQUALS(clone->getProfileFunctionName(), peaks->getProfileFunctionName());
         TS_ASSERT_EQUALS(clone->intensityType(), peaks->intensityType());
         TS_ASSERT_EQUALS(clone->peakCount(), peaks->peakCount());
+        TS_ASSERT_EQUALS(unitCellToStr(clone->unitCell()), unitCellToStr(peaks->unitCell()));
+        TS_ASSERT_EQUALS(clone->pointGroup()->getSymbol(), peaks->pointGroup()->getSymbol());
 
         for(size_t i = 0; i < clone->peakCount(); ++i) {
             PoldiPeak_sptr clonePeak = clone->peak(i);
@@ -331,8 +361,6 @@ public:
         std::vector<double> fSquared(dValues.size(), 0.0);
 
         TestablePoldiPeakCollection p;
-        // point group has not been set - required for multiplicities
-        TS_ASSERT_THROWS(p.setPeaks(hkls, dValues, fSquared), std::runtime_error);
 
         p.setPointGroup(structure->pointGroup());
         TS_ASSERT_THROWS_NOTHING(p.setPeaks(hkls, dValues, fSquared));
diff --git a/Code/Mantid/Framework/TestHelpers/inc/MantidTestHelpers/ComponentCreationHelper.h b/Code/Mantid/Framework/TestHelpers/inc/MantidTestHelpers/ComponentCreationHelper.h
index 304a1ff5b6b6f59b32a66c6923934dc29bce94dd..dd57c6da7daeb6104c2a82a16a14c03338236144 100644
--- a/Code/Mantid/Framework/TestHelpers/inc/MantidTestHelpers/ComponentCreationHelper.h
+++ b/Code/Mantid/Framework/TestHelpers/inc/MantidTestHelpers/ComponentCreationHelper.h
@@ -121,7 +121,7 @@ boost::shared_ptr<Mantid::Geometry::DetectorGroup> createGroupOfTwoMonitors();
 /** create instrument with cylindrical detectors located in specific angular
  * positions */
 Mantid::Geometry::Instrument_sptr
-createCylInstrumentWithDetInGivenPosisions(const std::vector<double> &L2,
+createCylInstrumentWithDetInGivenPositions(const std::vector<double> &L2,
                                            const std::vector<double> &polar,
                                            const std::vector<double> &azim);
 /**
diff --git a/Code/Mantid/Framework/TestHelpers/inc/MantidTestHelpers/MDEventsTestHelper.h b/Code/Mantid/Framework/TestHelpers/inc/MantidTestHelpers/MDEventsTestHelper.h
index e3135117444b5e963deb5c5a4f2717f1eab51c51..f1484cd7cd6768703c31235ae5ce78e2302a0cb2 100644
--- a/Code/Mantid/Framework/TestHelpers/inc/MantidTestHelpers/MDEventsTestHelper.h
+++ b/Code/Mantid/Framework/TestHelpers/inc/MantidTestHelpers/MDEventsTestHelper.h
@@ -42,7 +42,6 @@ createDiffractionEventWorkspace(int numEvents, int numPixels = 400,
  *points
  *
  * @param wsName :: name of the workspace in ADS
- * @param fileBacked :: true for file-backed
  * @return MDEW sptr
  */
 MDEventWorkspace3Lean::sptr
@@ -206,6 +205,7 @@ makeMDGridBox(size_t split0 = 10, size_t split1 = 10,
 
   // Split
   MDGridBox<MDLeanEvent<nd>, nd> *out = new MDGridBox<MDLeanEvent<nd>, nd>(box);
+  delete box;
 
   return out;
 }
@@ -304,7 +304,7 @@ static MDGridBox<MDLeanEvent<nd>, nd> *makeRecursiveMDGridBox(size_t splitInto,
   // Split into the gridbox.
   MDGridBox<MDLeanEvent<nd>, nd> *gridbox =
       new MDGridBox<MDLeanEvent<nd>, nd>(box);
-
+  delete box;
   // Now recursively split more
   recurseSplit(gridbox, 0, levels);
 
diff --git a/Code/Mantid/Framework/TestHelpers/src/ComponentCreationHelper.cpp b/Code/Mantid/Framework/TestHelpers/src/ComponentCreationHelper.cpp
index c802d558502244f83d0edc0e8ba5d651ff48088e..743c4b5913cc98e3d5616137db330de89383e199 100644
--- a/Code/Mantid/Framework/TestHelpers/src/ComponentCreationHelper.cpp
+++ b/Code/Mantid/Framework/TestHelpers/src/ComponentCreationHelper.cpp
@@ -347,7 +347,7 @@ bool double_cmprsn(double x1, double x2) {
   }
 }
 Mantid::Geometry::Instrument_sptr
-createCylInstrumentWithDetInGivenPosisions(const std::vector<double> &L2,
+createCylInstrumentWithDetInGivenPositions(const std::vector<double> &L2,
                                            const std::vector<double> &polar,
                                            const std::vector<double> &azim) {
   boost::shared_ptr<Instrument> testInst(new Instrument("processed"));
diff --git a/Code/Mantid/Framework/TestHelpers/src/MDEventsTestHelper.cpp b/Code/Mantid/Framework/TestHelpers/src/MDEventsTestHelper.cpp
index d6c4904cc7dbdebe63323a00a153fbe397ca82ad..9a8941ae9d41b443a90a7e5521cf62d2c481c308 100644
--- a/Code/Mantid/Framework/TestHelpers/src/MDEventsTestHelper.cpp
+++ b/Code/Mantid/Framework/TestHelpers/src/MDEventsTestHelper.cpp
@@ -151,9 +151,9 @@ MDEventWorkspace3Lean::sptr makeFakeMDEventWorkspace(const std::string &wsName,
 !!!!*/
 MDBox<MDLeanEvent<1>, 1> *makeMDBox1(size_t splitInto,
                                      BoxController *splitter) {
-  if (!splitter)
+  if (!splitter) {
     splitter = (new BoxController(1));
-
+  }
   // Split at 5 events
   splitter->setSplitThreshold(5);
   // Splits into 10 boxes
diff --git a/Code/Mantid/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp b/Code/Mantid/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp
index 1b5c6875f770090cd9cdbea871d42df51eee2907..fe6361f94c506fea4f6b318f95577b4a1d7eca5e 100644
--- a/Code/Mantid/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp
+++ b/Code/Mantid/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp
@@ -918,7 +918,7 @@ createProcessedInelasticWS(const std::vector<double> &L2,
 
   // detectors at L2, sample at 0 and source at -L2_min
   ws->setInstrument(
-      ComponentCreationHelper::createCylInstrumentWithDetInGivenPosisions(
+      ComponentCreationHelper::createCylInstrumentWithDetInGivenPositions(
           L2, polar, azimutal));
 
   for (int g = 0; g < static_cast<int>(numPixels); g++) {
diff --git a/Code/Mantid/Framework/WorkflowAlgorithms/src/DgsConvertToEnergyTransfer.cpp b/Code/Mantid/Framework/WorkflowAlgorithms/src/DgsConvertToEnergyTransfer.cpp
index 643c68fa0c224c341f035d3ac669c0a0104e56e9..a53fdd1f244980b7e9f648600b64bdc9536e7875 100644
--- a/Code/Mantid/Framework/WorkflowAlgorithms/src/DgsConvertToEnergyTransfer.cpp
+++ b/Code/Mantid/Framework/WorkflowAlgorithms/src/DgsConvertToEnergyTransfer.cpp
@@ -199,7 +199,14 @@ void DgsConvertToEnergyTransfer::exec() {
         loadmon->setProperty(fileProp, runFileName);
         loadmon->setProperty("OutputWorkspace", monWsName);
         loadmon->executeAsChildAlg();
-        monWS = loadmon->getProperty("OutputWorkspace");
+        Workspace_sptr monWSOutput = loadmon->getProperty("OutputWorkspace");
+        // the algorithm can return a group workspace if the file is multi period
+        monWS = boost::dynamic_pointer_cast<MatrixWorkspace>(monWSOutput);
+        if ((monWSOutput) && (!monWS)) {
+          //this was a group workspace - DGSReduction does not support multi period data yet
+          throw Exception::NotImplementedError(
+            "The file contains multi period data, support for this is not implemented in DGSReduction yet");
+        }
       }
 
       // Calculate Ei
diff --git a/Code/Mantid/Framework/WorkflowAlgorithms/src/EQSANSLoad.cpp b/Code/Mantid/Framework/WorkflowAlgorithms/src/EQSANSLoad.cpp
index 5979526d9cf6e210b5739384de23cb02afffdfd1..8a2fcae8bfed5f8d2db29916532b8aa1a1a571dc 100644
--- a/Code/Mantid/Framework/WorkflowAlgorithms/src/EQSANSLoad.cpp
+++ b/Code/Mantid/Framework/WorkflowAlgorithms/src/EQSANSLoad.cpp
@@ -515,7 +515,13 @@ void EQSANSLoad::exec() {
     // Get monitor workspace as necessary
     std::string mon_wsname = getPropertyValue("OutputWorkspace") + "_monitors";
     if (loadMonitors && loadAlg->existsProperty("MonitorWorkspace")) {
-      MatrixWorkspace_sptr monWS = loadAlg->getProperty("MonitorWorkspace");
+      Workspace_sptr monWSOutput = loadAlg->getProperty("MonitorWorkspace");
+      MatrixWorkspace_sptr monWS = boost::dynamic_pointer_cast<MatrixWorkspace>(monWSOutput);
+      if ((monWSOutput) && (!monWS)) {
+        //this was a group workspace - EQSansLoad does not support multi period data yet
+        throw Exception::NotImplementedError(
+          "The file contains multi period data, support for this is not implemented in EQSANSLoad yet");
+      }
       declareProperty(new WorkspaceProperty<>("MonitorWorkspace", mon_wsname,
                                               Direction::Output),
                       "Monitors from the Event NeXus file");
diff --git a/Code/Mantid/Framework/WorkflowAlgorithms/src/SendUsage.cpp b/Code/Mantid/Framework/WorkflowAlgorithms/src/SendUsage.cpp
index ae6efa60dc60e605629ceacd3d9da123cfc0851f..c26467f3fe060055abfe89a10eaf99fcd2ac43cb 100644
--- a/Code/Mantid/Framework/WorkflowAlgorithms/src/SendUsage.cpp
+++ b/Code/Mantid/Framework/WorkflowAlgorithms/src/SendUsage.cpp
@@ -191,7 +191,7 @@ void SendUsage::generateHeader() {
 
   // paraview version or zero
   buffer << "\"ParaView\":\"";
-  if (ConfigService::Instance().quickParaViewCheck()) {
+  if (ConfigService::Instance().pvPluginsAvailable()) {
     buffer << Kernel::ParaViewVersion::targetVersion();
   } else {
     buffer << 0;
diff --git a/Code/Mantid/Installers/MacInstaller/Info.plist.in b/Code/Mantid/Installers/MacInstaller/Info.plist.in
index d5e7ce528e98dc707e302bcf65689c78a82118c4..dff679f8c0bc109786ce56a5ef75f035249f69f1 100644
--- a/Code/Mantid/Installers/MacInstaller/Info.plist.in
+++ b/Code/Mantid/Installers/MacInstaller/Info.plist.in
@@ -2,11 +2,6 @@
 <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
 <plist version="1.0">
 <dict>
-	<key>LSEnvironment</key>
-	<dict>
-		<key>DYLD_LIBRARY_PATH</key>
-		<string>@PARAVIEW_APP_LIB_DIR@:@PARAVIEW_APP_PLUGIN_DIR@</string>
-	</dict>
 	<key>CFBundleDevelopmentRegion</key>
 	<string>English</string>
 	<key>CFBundleExecutable</key>
diff --git a/Code/Mantid/MantidPlot/CMakeLists.txt b/Code/Mantid/MantidPlot/CMakeLists.txt
index be38f40c868eaac700586566f27a61d0eb3e482e..210b5a64233765178876f6302749ca5ddbf6e16f 100644
--- a/Code/Mantid/MantidPlot/CMakeLists.txt
+++ b/Code/Mantid/MantidPlot/CMakeLists.txt
@@ -189,7 +189,6 @@ set ( MANTID_SRCS  src/Mantid/AlgorithmMonitor.cpp
                    src/Mantid/PeakPickerTool.cpp
                    src/Mantid/Preferences.cpp
                    src/Mantid/RemoveErrorsDialog.cpp
-                   src/Mantid/SetUpParaview.cpp
                    src/Mantid/UserFitFunctionDialog.cpp
                    src/Mantid/WorkspaceIcons.cpp
                    src/Mantid/InstrumentWidget/BinDialog.cpp
@@ -427,7 +426,6 @@ set ( MANTID_HDRS  src/Mantid/AlgorithmMonitor.h
                    src/Mantid/PeakPickerTool.h
                    src/Mantid/Preferences.h
                    src/Mantid/RemoveErrorsDialog.h
-                   src/Mantid/SetUpParaview.h
                    src/Mantid/UserFitFunctionDialog.h
                    src/Mantid/WorkspaceIcons.h
                    src/Mantid/InstrumentWidget/BinDialog.h
@@ -700,7 +698,6 @@ set ( MANTID_MOC_FILES src/Mantid/AlgorithmMonitor.h
                        src/Mantid/MantidTable.h
                        src/Mantid/PeakPickerTool.h
                        src/Mantid/RemoveErrorsDialog.h
-                       src/Mantid/SetUpParaview.h
                        src/Mantid/UserFitFunctionDialog.h
                        src/Mantid/InstrumentWidget/XIntegrationControl.h
                        src/Mantid/InstrumentWidget/BinDialog.h
@@ -731,7 +728,6 @@ set ( UI_FILES src/SendToProgramDialog.ui
                src/Mantid/UserFitFunctionDialog.ui
                src/Mantid/MantidAbout.ui
                src/Mantid/RemoveErrorsDialog.ui
-               src/Mantid/SetUpParaview.ui
                src/Mantid/ManageCustomMenus.ui
                src/Mantid/ManageInterfaceCategories.ui
                src/Mantid/MantidMDCurveDialog.ui
@@ -855,20 +851,13 @@ copy_files_to_dir ( "${PY_FILES}"
 set( MTDPLOTPY_FILES
   __init__.py
   proxies.py
+  pyplot.py
+  qtiplot.py
 )
 copy_files_to_dir ( "${MTDPLOTPY_FILES}"
                             ${CMAKE_CURRENT_SOURCE_DIR}/pymantidplot
                             ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${CMAKE_CFG_INTDIR}/pymantidplot
                             MTDPLOT_INSTALL_FILES )
-                            
-set( FUTURE_FILES
-  __init__.py
-  pyplot.py
-)
-copy_files_to_dir ( "${FUTURE_FILES}"
-                            ${CMAKE_CURRENT_SOURCE_DIR}/pymantidplot/future
-                            ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${CMAKE_CFG_INTDIR}/pymantidplot/future
-                            MTDPLOT_FUTURE_INSTALL_FILES )
 
 # IPython scripts
 set( IPY_FILES
@@ -887,7 +876,7 @@ copy_files_to_dir ( "${IPY_FILES}"
 add_executable ( MantidPlot ${WIN_CONSOLE} MACOSX_BUNDLE ${ALL_SRC} src/main.cpp
 							${INC_FILES} ${QTIPLOT_C_SRC} ${UI_HDRS}
 							${RES_FILES} ${MANTID_RC_FILE}
-							${PYTHON_INSTALL_FILES} ${MTDPLOT_INSTALL_FILES} ${CONFIG_RESET_SCRIPT_FILE} ${MTDPLOT_FUTURE_INSTALL_FILES} ${IPYTHON_INSTALL_FILES}
+							${PYTHON_INSTALL_FILES} ${MTDPLOT_INSTALL_FILES} ${CONFIG_RESET_SCRIPT_FILE} ${IPYTHON_INSTALL_FILES}
 )
 
 # Library dependencies
@@ -901,6 +890,11 @@ target_link_libraries ( MantidPlot
                         ${PYTHON_LIBRARIES}
                         ${ZLIB_LIBRARIES}
 )
+
+if (WITH_ASAN)
+  target_link_libraries ( MantidPlot -lasan )
+endif ()
+
 # Plugin dependencies
 add_dependencies( MantidPlot mantidqtpython )
 
@@ -963,7 +957,7 @@ set ( MANTIDPLOT_TEST_PY_FILES
     MantidPlotMdiSubWindowTest.py
     MantidPlotTiledWindowTest.py
     MantidPlotInputArgsCheck.py
-    MantidPlotFuturePyplotGeneralTest.py
+    MantidPlotPyplotGeneralTest.py
 )
 
 if ( 0 )
@@ -1029,9 +1023,6 @@ install ( FILES ${PY_FILES} DESTINATION ${BIN_DIR} )
 foreach(PY_FILE ${MTDPLOTPY_FILES} )
   install ( FILES pymantidplot/${PY_FILE} DESTINATION ${BIN_DIR}/pymantidplot )
 endforeach()
-foreach(FUT_PY_FILE ${FUTURE_FILES} )
-  install ( FILES pymantidplot/future/${FUT_PY_FILE} DESTINATION ${BIN_DIR}/pymantidplot/future )
-endforeach()
 foreach(PY_FILE ${IPY_FILES} )
   install ( FILES ipython_widget/${PY_FILE} DESTINATION ${BIN_DIR}/ipython_widget )
 endforeach()
@@ -1054,7 +1045,10 @@ if ( APPLE )
                    @ONLY )
         install ( SCRIPT ${CMAKE_CURRENT_BINARY_DIR}/FixMacportsBundle.cmake )
   else ()
-    install ( FILES  make_package.rb DESTINATION MantidPlot.app/ )
+    configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/make_package.rb.in
+                   ${CMAKE_CURRENT_BINARY_DIR}/make_package.rb
+                   @ONLY )
+    install ( FILES  ${CMAKE_CURRENT_BINARY_DIR}/make_package.rb DESTINATION MantidPlot.app/ )
     configure_file ( ${CMAKE_CURRENT_SOURCE_DIR}/FixMavericksBundle.cmake.in
                    ${CMAKE_CURRENT_BINARY_DIR}/FixMavericksBundle.cmake
                    @ONLY )
diff --git a/Code/Mantid/MantidPlot/FixMavericksBundle.cmake.in b/Code/Mantid/MantidPlot/FixMavericksBundle.cmake.in
index 6abe55b6806c22a9e94b3f3627a222a18edc1491..572443874d5ad33431c424ca15ef99d8e3a2c56a 100644
--- a/Code/Mantid/MantidPlot/FixMavericksBundle.cmake.in
+++ b/Code/Mantid/MantidPlot/FixMavericksBundle.cmake.in
@@ -1,3 +1,6 @@
 set ( bundle ${CMAKE_INSTALL_PREFIX}/MantidPlot.app )
 execute_process(COMMAND chmod +x make_package.rb WORKING_DIRECTORY ${bundle})
-execute_process(COMMAND ./make_package.rb WORKING_DIRECTORY ${bundle})
+execute_process(COMMAND ./make_package.rb WORKING_DIRECTORY ${bundle} RESULT_VARIABLE install_name_tool_result)
+if(NOT install_name_tool_result EQUAL 0)
+  message(FATAL_ERROR "Package script failed!!!\n")
+endif()
diff --git a/Code/Mantid/MantidPlot/ipython_widget/mantid_ipython_widget.py b/Code/Mantid/MantidPlot/ipython_widget/mantid_ipython_widget.py
index 4eb697981bf9d010e3f5e469f41b4f7c3aa805b3..d801eb8ad7a61b7810db26f07dc2ca2f44d98c22 100644
--- a/Code/Mantid/MantidPlot/ipython_widget/mantid_ipython_widget.py
+++ b/Code/Mantid/MantidPlot/ipython_widget/mantid_ipython_widget.py
@@ -1,5 +1,6 @@
 import threading
 import types
+import inspect
 
 from PyQt4 import QtGui
 
@@ -14,7 +15,7 @@ from IPython.qt.console.rich_ipython_widget import RichIPythonWidget
 from IPython.qt.inprocess import QtInProcessKernelManager
 
 
-def our_run_code(self, code_obj):
+def our_run_code(self, code_obj, result=None):
     """ Method with which we replace the run_code method of IPython's InteractiveShell class.
         It calls the original method (renamed to ipython_run_code) on a separate thread
         so that we can avoid locking up the whole of MantidPlot while a command runs.
@@ -23,12 +24,20 @@ def our_run_code(self, code_obj):
         ----------
         code_obj : code object
           A compiled code object, to be executed
-
+        result : ExecutionResult, optional
+          An object to store exceptions that occur during execution.
         Returns
         -------
         False : Always, as it doesn't seem to matter.
     """
-    t = threading.Thread(target=self.ipython_run_code, args=[code_obj])
+
+    t = threading.Thread()
+    #ipython 3.0 introduces a third argument named result
+    nargs = len(inspect.getargspec(self.ipython_run_code).args)
+    if (nargs == 3):
+        t = threading.Thread(target=self.ipython_run_code, args=[code_obj,result])
+    else:
+        t = threading.Thread(target=self.ipython_run_code, args=[code_obj])
     t.start()
     while t.is_alive():
         QtGui.QApplication.processEvents()
diff --git a/Code/Mantid/MantidPlot/make_package.rb b/Code/Mantid/MantidPlot/make_package.rb.in
similarity index 58%
rename from Code/Mantid/MantidPlot/make_package.rb
rename to Code/Mantid/MantidPlot/make_package.rb.in
index 78a57d600b652b89c854b78d4cf831591cc1a6cc..afab0d3b60844b00e4b7bade807835eea796d039 100755
--- a/Code/Mantid/MantidPlot/make_package.rb
+++ b/Code/Mantid/MantidPlot/make_package.rb.in
@@ -3,8 +3,25 @@
 
 require 'pathname'
 
+def copyFile(file)
+    p "copying file #{file}"
+    output = system("cp #{file} Contents/MacOS/")
+    if output != true
+        exit 1
+    end
+end
+
+def addPythonLibrary(directory)
+    p "copying directory #{directory}"
+    output = system("rsync -a --exclude=.pyc #{directory} Contents/MacOS/")
+    if output != true
+        exit 1
+    end
+end
+
 lib_dir = Pathname.new("/usr/local/lib")
 openssl_dir = Pathname.new("/usr/local/opt/openssl/lib")
+ParaView_dir = Pathname.new("@ParaView_DIR@")
 
 #filenames with path for all shared libraries used by MantidPlot and its dependencies.
 library_filenames = ["libboost_regex-mt.dylib",
@@ -51,18 +68,18 @@ library_filenames = ["libboost_regex-mt.dylib",
 #This copies the libraries over, then changes permissions and the id from /usr/local/lib to @rpath
 library_filenames.each do |filename|
     if filename.include? "libssl.dylib"
-        `cp #{openssl_dir+filename} Contents/MacOS/`
+        copyFile(openssl_dir+filename)
     elsif  filename.include? "libcrypto.dylib"
-        `cp #{openssl_dir+filename} Contents/MacOS/`
+        copyFile(openssl_dir+filename)
     else
-        `cp #{lib_dir+filename} Contents/MacOS/`
+        copyFile(lib_dir+filename)
     end
     `chmod +w Contents/MacOS/#{filename}`
     `install_name_tool -id @rpath/#{filename} Contents/MacOS/#{filename}`
 end
 
 #use install_name_tool to change dependencies form /usr/local to libraries in the package.
-search_patterns = ["**/*.dylib","**/*.so","**/MantidPlot"]
+search_patterns = ["**/*.dylib","**/*.so","**/MantidPlot","**/VatesSimpleGui"]
 search_patterns.each do |pattern|
     Dir[pattern].each do |library|
         dependencies = `otool -L #{library}`
@@ -81,32 +98,66 @@ search_patterns.each do |pattern|
     end
 end
 
+
+if( "@MAKE_VATES@" == "ON" )
+
+  def add_ParaView_Libraries(file)
+    dependencies = `otool -L #{file}`
+    dependencies.split("\n").each do |dependency|
+      currentname = dependency.strip.split(" ")
+      filename = currentname[0]
+      if filename.include? "#{ParaView_dir}"
+        `cp #{filename} Contents/Libraries`
+        name_split_on_slash = filename.strip.split("/")
+        filename_no_dir = name_split_on_slash[-1]
+        `chmod +w Contents/Libraries/#{filename_no_dir}`
+        `install_name_tool -id @rpath/#{filename_no_dir} Contents/Libraries/#{filename_no_dir}`
+        `install_name_tool -change #{filename} @rpath/#{filename_no_dir} #{file}`
+      end
+    end
+  end
+
+  `mkdir Contents/Libraries`
+  vatesfiles = ["Contents/MacOS/VatesSimpleGui","Contents/MacOS/libMantidParaViewQtWidgets.dylib","Contents/MacOS/libMantidVatesAPI.dylib","pvplugins/libMantidVatesSimpleGuiViewWidgets.dylib"]+Dir["pvplugins/pvplugins/*.dylib"] 
+  vatesfiles.each do |file|
+    add_ParaView_Libraries(file)
+  end
+
+  loop do
+    issues_found = 0
+    Dir["Contents/Libraries/*.dylib"].each do |library|
+      dependencies = `otool -L #{library}`
+      dependencies.split("\n").each do |dependency|
+        currentname = dependency.strip.split(" ")
+        filename = currentname[0]
+        if filename.include? "#{ParaView_dir}"
+          #p "fixing #{library} #{filename}" 
+          issues_found = issues_found + 1
+          name_split_on_slash = filename.strip.split("/")
+          filename_no_dir = name_split_on_slash[-1]
+          if !FileTest.exist?("Contents/Libraries/#{filename_no_dir}")
+            `cp #{filename} Contents/Libraries`
+            `chmod +w Contents/Libraries/#{filename_no_dir}`
+            `install_name_tool -id @rpath/#{filename_no_dir} Contents/Libraries/#{filename_no_dir}`
+          end
+          `install_name_tool -add_rpath @loader_path/../Libraries #{library} > /dev/null 2>&1`
+          `install_name_tool -change #{filename} @rpath/#{filename_no_dir} #{library}`
+        end
+      end
+    end
+    p "fixed #{issues_found} issues this iteration!"
+    break if issues_found == 0
+  end
+end
+
 #We'll use macdeployqt to fix qt dependencies.
-`macdeployqt ../MantidPlot.app`
-
-#fix remaining QT linking issues
-`install_name_tool -change /usr/local/lib/Qt3Support.framework/Versions/4/Qt3Support @loader_path/../Frameworks/Qt3Support.framework/Versions/4/Qt3Support Contents/MacOS/mantidqtpython.so`
-`install_name_tool -change /usr/local/lib/QtOpenGL.framework/Versions/4/QtOpenGL @loader_path/../Frameworks/QtOpenGL.framework/Versions/4/QtOpenGL Contents/MacOS/mantidqtpython.so`
-`install_name_tool -change /usr/local/lib/QtSvg.framework/Versions/4/QtSvg @loader_path/../Frameworks/QtSvg.framework/Versions/4/QtSvg Contents/MacOS/mantidqtpython.so`
-`install_name_tool -change /usr/local/lib/QtGui.framework/Versions/4/QtGui @loader_path/../Frameworks/QtGui.framework/Versions/4/QtGui Contents/MacOS/mantidqtpython.so`
-`install_name_tool -change /usr/local/lib/QtXml.framework/Versions/4/QtXml @loader_path/../Frameworks/QtXml.framework/Versions/4/QtXml Contents/MacOS/mantidqtpython.so`
-`install_name_tool -change /usr/local/lib/QtSql.framework/Versions/4/QtSql @loader_path/../Frameworks/QtSql.framework/Versions/4/QtSql Contents/MacOS/mantidqtpython.so`
-`install_name_tool -change /usr/local/lib/QtNetwork.framework/Versions/4/QtNetwork @loader_path/../Frameworks/QtNetwork.framework/Versions/4/QtNetwork Contents/MacOS/mantidqtpython.so`
-`install_name_tool -change /usr/local/lib/QtCore.framework/Versions/4/QtCore @loader_path/../Frameworks/QtCore.framework/Versions/4/QtCore Contents/MacOS/mantidqtpython.so`
-`install_name_tool -change /usr/local/lib/QtHelp.framework/Versions/4/QtHelp @loader_path/../Frameworks/QtHelp.framework/Versions/4/QtHelp  Contents/MacOS/mantidqtpython.so`
-`install_name_tool -change /usr/local/lib/QtWebKit.framework/Versions/4/QtWebKit @loader_path/../Frameworks/QtWebKit.framework/Versions/4/QtWebKit Contents/MacOS/mantidqtpython.so`
-
-`install_name_tool -change /usr/local/lib/QtOpenGL.framework/Versions/4/QtOpenGL @loader_path/../Frameworks/QtOpenGL.framework/Versions/4/QtOpenGL Contents/MacOS/libqwtplot3d.dylib`
-`install_name_tool -change /usr/local/lib/QtGui.framework/Versions/4/QtGui @loader_path/../Frameworks/QtGui.framework/Versions/4/QtGui Contents/MacOS/libqwtplot3d.dylib`
-`install_name_tool -change /usr/local/lib/QtCore.framework/Versions/4/QtCore @loader_path/../Frameworks/QtCore.framework/Versions/4/QtCore Contents/MacOS/libqwtplot3d.dylib`
-
-`install_name_tool -change /usr/local/lib/QtGui.framework/Versions/4/QtGui @loader_path/../Frameworks/QtGui.framework/Versions/4/QtGui Contents/MacOS/libqwt.dylib`
-`install_name_tool -change /usr/local/lib/QtCore.framework/Versions/4/QtCore @loader_path/../Frameworks/QtCore.framework/Versions/4/QtCore Contents/MacOS/libqwt.dylib`
-
-`install_name_tool -change /usr/local/lib/QtGui.framework/Versions/4/QtGui @loader_path/../Frameworks/QtGui.framework/Versions/4/QtGui Contents/MacOS/libqscintilla2.dylib`
-`install_name_tool -change /usr/local/lib/QtCore.framework/Versions/4/QtCore @loader_path/../Frameworks/QtCore.framework/Versions/4/QtCore Contents/MacOS/libqscintilla2.dylib`
-
-`install_name_tool -change /usr/local/lib/QtCore.framework/Versions/4/QtCore @loader_path/../Frameworks/QtCore.framework/Versions/4/QtCore Contents/MacOS/libqscintilla2.dylib`
+Qt_Executables = "-executable=Contents/MacOS/mantidqtpython.so -executable=Contents/MacOS/libqwtplot3d.dylib -executable=Contents/MacOS/libqwt.dylib -executable=Contents/MacOS/libqscintilla2.dylib"
+if( "@MAKE_VATES@" == "ON" )
+  Qt_Executables << " -executable=Contents/MacOS/VatesSimpleGui"
+end
+`macdeployqt ../MantidPlot.app #{Qt_Executables}`
+
+#Fix remaining QT-related linking issues.
 `install_name_tool -id @rpath/libqsqlite.dylib Contents/Frameworks/plugins/sqldrivers/libqsqlite.dylib`
 
 #change id of all Qt4 imageformats libraries
@@ -151,40 +202,35 @@ end
 `install_name_tool -change /usr/local/lib/QtCore.framework/Versions/4/QtCore @loader_path/../../Frameworks/QtCore.framework/Versions/4/QtCore Contents/MacOS/PyQt4/QtXml.so`
 
 #Copy over python libraries not included with OSX. 
-`cp -r /Library/Python/2.7/site-packages/sphinx Contents/MacOS/`
-`cp -r /Library/Python/2.7/site-packages/sphinx_bootstrap_theme Contents/MacOS/`
-`cp -r /Library/Python/2.7/site-packages/IPython Contents/MacOS/`
-`cp -r /Library/Python/2.7/site-packages/zmq Contents/MacOS/`
-`cp -r /Library/Python/2.7/site-packages/pygments Contents/MacOS/`
-
-#add other dependencies found in current package
 #currently missing epics
-`cp /Library/Python/2.7/site-packages/gnureadline.so Contents/MacOS/`
-`cp /Library/Python/2.7/site-packages/readline.py Contents/MacOS/`
-`cp /Library/Python/2.7/site-packages/readline.pyc Contents/MacOS/`
-`cp /Library/Python/2.7/site-packages/pyparsing.py Contents/MacOS/`
-`cp /Library/Python/2.7/site-packages/pyparsing.pyc Contents/MacOS/`
-`cp -r /Library/Python/2.7/site-packages/_markerlib/ Contents/MacOS/`
-`cp -r /Library/Python/2.7/site-packages/backports Contents/MacOS/`
-`cp -r /Library/Python/2.7/site-packages/certifi Contents/MacOS/`
-`cp -r /Library/Python/2.7/site-packages/tornado Contents/MacOS/`
-`cp -r /Library/Python/2.7/site-packages/markupsafe Contents/MacOS/`
-`cp -r /Library/Python/2.7/site-packages/jinja2 Contents/MacOS/`
-`cp -r /usr/local/lib/python2.7/site-packages/nxs Contents/MacOS/`
-`cp -r /Library/Python/2.7/site-packages/psutil Contents/MacOS/`
+path = "/Library/Python/2.7/site-packages"
+directories = ["sphinx","sphinx_bootstrap_theme","IPython","zmq","pygments","backports","certifi","tornado","markupsafe","jinja2","psutil"]
+directories.each do |directory|
+  addPythonLibrary("#{path}/#{directory}")
+end
+
+files = ["gnureadline.so","readline.py","pyparsing.py"]
+files.each do |file|
+  copyFile("#{path}/#{file}")
+end
+
 `mkdir Contents/MacOS/bin`
 `cp /usr/local/bin/ipython Contents/MacOS/bin/`
 
-# current .pyc files have permissions issues. These files are recreated by CPack.
-`rm Contents/MacOS/nxs/*.pyc`
-
 #Lastly check for any libraries in the package linking against homebrew libraries.
 search_patterns.each do |pattern|
   Dir[pattern].each do |library|
     dependencies = `otool -L #{library}`
     dependencies.split("\n").each do |dependency|
       if dependency.include? "/usr/local/"
-         p "issue with library: #{library} linked against: #{dependency}"
+        p "issue with library: #{library} linked against: #{dependency}"
+        exit 1
+      end
+      if( "@MAKE_VATES@" == "ON" )
+        if dependency.include? "#{ParaView_dir}"
+          p "issue with library: #{library} linking against: #{dependency}"
+          exit 1
+        end
       end
     end
   end
diff --git a/Code/Mantid/MantidPlot/mantidplot.py b/Code/Mantid/MantidPlot/mantidplot.py
index e710b1a0e074d9559e17a802f1b3e8594836efdc..ee4980b5b44c35c39726d40a1b847a98cb0bdbf0 100644
--- a/Code/Mantid/MantidPlot/mantidplot.py
+++ b/Code/Mantid/MantidPlot/mantidplot.py
@@ -10,3 +10,15 @@ try:
     from pymantidplot import *
 except ImportError:
     raise ImportError('Could not import mantidplot (when trying to import pymantidplot). Something is broken in this installation, please check.')
+
+try:
+    # import pyplot and also bring it into the standard MantidPlot namespace
+    import pymantidplot.pyplot
+    from pymantidplot.pyplot import *
+except ImportError:
+    raise ImportError('Could not import pymantidplot.pyplot. Something is broken in this installation, please check.')
+
+try:
+    import pymantidplot.qtiplot
+except ImportError:
+    raise ImportError('Could not import pymantidplot.qtiplot. Something is broken in this installation, please check.')
diff --git a/Code/Mantid/MantidPlot/pymantidplot/__init__.py b/Code/Mantid/MantidPlot/pymantidplot/__init__.py
index f08c88a6503731326a542d677eccc6f891514675..4e624105398350cd560133150e97c367fbf5a396 100644
--- a/Code/Mantid/MantidPlot/pymantidplot/__init__.py
+++ b/Code/Mantid/MantidPlot/pymantidplot/__init__.py
@@ -183,25 +183,9 @@ def newTiledWindow(name=None):
     else:
         return new_proxy(proxies.TiledWindowProxy, _qti.app.newTiledWindow, name)
 
-#-----------------------------------------------------------------------------
-# Intercept qtiplot "plot" command and forward to plotSpectrum for a workspace
-def plot(source, *args, **kwargs):
-    """Create a new plot given a workspace, table or matrix.
-
-    Args:
-        source: what to plot; if it is a Workspace, will
-                call plotSpectrum()
-
-    Returns:
-        A handle to the created Graph widget.
-    """
-    if hasattr(source, '_getHeldObject') and isinstance(source._getHeldObject(), QtCore.QObject):
-        return new_proxy(proxies.Graph,_qti.app.plot, source._getHeldObject(), *args, **kwargs)
-    else:
-        return plotSpectrum(source, *args, **kwargs)
-
 #----------------------------------------------------------------------------------------------------
-def plotSpectrum(source, indices, error_bars = False, type = -1, window = None, clearWindow = False):
+def plotSpectrum(source, indices, error_bars = False, type = -1, window = None,
+                 clearWindow = False, waterfall = False):
     """Open a 1D Plot of a spectrum in a workspace.
 
     This plots one or more spectra, with X as the bin boundaries,
@@ -214,6 +198,7 @@ def plotSpectrum(source, indices, error_bars = False, type = -1, window = None,
         type: curve style for plot (-1: unspecified; 0: line, default; 1: scatter/dots)
         window: window used for plotting. If None a new one will be created
         clearWindow: if is True, the window specified will be cleared before adding new curve
+        waterfall: if True, plot as a waterfall if there is more than 1 curve
     Returns:
         A handle to window if one was specified, otherwise a handle to the created one. None in case of error.
     """
@@ -239,7 +224,7 @@ def plotSpectrum(source, indices, error_bars = False, type = -1, window = None,
 
     graph = proxies.Graph(threadsafe_call(_qti.app.mantidUI.plot1D,
                                           workspace_names, index_list, True, error_bars,
-                                          type, window, clearWindow))
+                                          type, window, clearWindow, waterfall))
     if graph._getHeldObject() == None:
         raise RuntimeError("Cannot create graph, see log for details.")
     else:
@@ -336,7 +321,8 @@ def fitBrowser():
     return proxies.FitBrowserProxy(_qti.app.mantidUI.fitFunctionBrowser())
 
 #-----------------------------------------------------------------------------
-def plotBin(source, indices, error_bars = False, type = -1, window = None, clearWindow = False):
+def plotBin(source, indices, error_bars = False, type = -1, window = None, clearWindow = False,
+            waterfall = False):
     """Create a 1D Plot of bin count vs spectrum in a workspace.
 
     This puts the spectrum number as the X variable, and the
@@ -352,6 +338,7 @@ def plotBin(source, indices, error_bars = False, type = -1, window = None, clear
         type: Plot style
         window: window used for plotting. If None a new one will be created
         clearWindow: if is True, the window specified will be cleared before adding new curve
+        waterfall: if True, plot as a waterfall if there is more than 1 curve
     Returns:
         A handle to window if one was specified, otherwise a handle to the created one. None in case of error.
     """
@@ -377,7 +364,7 @@ def plotBin(source, indices, error_bars = False, type = -1, window = None, clear
 
     graph = proxies.Graph(threadsafe_call(_qti.app.mantidUI.plot1D,
                                           workspace_names, index_list, False, error_bars,
-                                          type, window, clearWindow))
+                                          type, window, clearWindow, waterfall))
     if graph._getHeldObject() == None:
         raise RuntimeError("Cannot create graph, see log for details.")
     else:
diff --git a/Code/Mantid/MantidPlot/pymantidplot/future/pyplot.py b/Code/Mantid/MantidPlot/pymantidplot/pyplot.py
similarity index 91%
rename from Code/Mantid/MantidPlot/pymantidplot/future/pyplot.py
rename to Code/Mantid/MantidPlot/pymantidplot/pyplot.py
index 62813a5f99d43a391dd5c40bcca15c5976819cee..78254a217a834b431def7b0f1a414869f43a46fd 100644
--- a/Code/Mantid/MantidPlot/pymantidplot/future/pyplot.py
+++ b/Code/Mantid/MantidPlot/pymantidplot/pyplot.py
@@ -10,17 +10,8 @@ plot options.
 
 The module is at a very early stage of development and provides
 limited functionality. This is very much work in progress at the
-moment. The module is subject to changes and it is for now included in
-Mantid as a 'future' import. Feedback is very much welcome!
-
-To use this new functionality you first need to import the new pyplot module:
-
-.. code-block:: python
-
-    from pymantidplot.future.pyplot import *
-
-Please do not forget this step, otherwise you may get arcane error
-messages from functions of the old mantidplot Python CLI.
+moment. The module is subject to changes and feedback is very much
+welcome!
 
 Simple plots can be created and manipulated with a handul of
 commands. See the following examples.
@@ -65,7 +56,7 @@ Plot a Mantid workspace
 You can pass one or more workspaces to the plot function. By default
 it will plot the spectra of the workspace(s), selecting them by the
 indices specified in the second argument. This behavior is similar to
-he plotSpectrum function of the traditional mantidplot module. This is
+the plotSpectrum function of the traditional mantidplot module. This is
 a simple example that produces plots of spectra:
 
 .. code-block:: python
@@ -77,11 +68,49 @@ a simple example that produces plots of spectra:
     # 3 spectra plot
     plot(ws, [100, 101, 102])
 
+========================
+Different types of plots
+========================
+
+The plot() function provides a unified interface to different types of
+plots, including specific graphs of spectra, bins, multidimensional
+workspaces, etc. These specific types of plots are explained in the
+next sections. plot() makes a guess as to what tool to use to plot a
+workspace. For example, if you pass an MD workspace it will make an MD
+plot. But you can request a specific type of plot by specifying a
+keyword argument ('tool'). The following tools (or different types of
+plots) are supported:
+
++------------------------+------------------------------------------------------------+-----------------------+
+| Tool                   | tool= parameter values (all are equivalent aliases)        | Old similar function  |
++========================+============================================================+=======================+
+| plot spectra (default) | 'plot_spectrum', 'spectrum', 'plot_sp', 'sp'               | plotSpectrum          |
++------------------------+------------------------------------------------------------+-----------------------+
+| plot bins              | 'plot_bin', 'bin'                                          | plotBin               |
++------------------------+------------------------------------------------------------+-----------------------+
+| plot MD                | 'plot_md', 'md'                                            | plotMD                |
++------------------------+------------------------------------------------------------+-----------------------+
+
+The last column of the table lists the functions that produce similar
+plots in the traditional MantidPlot Python plotting interface. For the
+time being this module only supports these types of specific
+plots. Note that the traditional plotting interface of MantidPlot
+provides support for many more specific types of plots. These or
+similar ones will be added in this module in future releases:
+
+* plot2D
+* plot3D
+* plotSlice
+* instrumentWindow
+* waterFallPlot
+* mergePlots
+* stemPlot
+
 Plot spectra using workspace objects and workspace names
 --------------------------------------------------------
 
 It is also possible to pass workspace names to plot, as in the
-following example:
+following example where we plot a few spectra:
 
 .. code-block:: python
 
@@ -108,11 +137,14 @@ names in the list passed to plot:
 
 Here, the plot function is making a guess and plotting the spectra of
 these workspaces (instead of the bins or anything else). You can make
-that choice more explicit by specifying the 'tool' argument:
+that choice more explicit by specifying the 'tool' argument. In this
+case we use 'plot_spectrum' (which also has shorter aliases:
+'spectrum', or simply 'sp' as listed in the table above):
 
 .. code-block:: python
 
     plot(['MAR11060', loq], [800, 900], tool='plot_spectrum')
+    plot(['MAR11060', loq], [801, 901], tool='sp')
 
 Alternatively, you can use the plot_spectrum command, which is
 equivalent to the plot command with the keyword argument
@@ -126,7 +158,7 @@ Plotting bins
 -------------
 
 To plot workspace bins you can use the keyword 'tool' with the value
-'plot_bin', like this:
+'plot_bin' (or equivalent 'bin'), like this:
 
 .. code-block:: python
 
@@ -143,7 +175,7 @@ Plotting MD workspaces
 ----------------------
 
 Similarly, to plot MD workspaces you can use the keyword 'tool' with
-the value 'plot_md', like this:
+the value 'plot_md' (or 'md' as a short alias), like this:
 
 .. code-block:: python
 
@@ -161,8 +193,9 @@ to the Mantid (http://www.mantidproject.org/MBC_MDWorkspaces) for a
 more real example, which necessarily gets more complicated and data
 intensive.
 
+=========================
 Changing style properties
--------------------------
+=========================
 
 You can modify the style of your plots. For example like this (for a
 full list of options currently supported, see below).
@@ -273,9 +306,9 @@ results.
 Multi-plot commands
 -------------------
 
-In this version of future.pyplot there is limited support for
-multi-plot commands (as in pyplot and matlab). For example, you can
-type commands like the following:
+In this version of pyplot there is limited support for multi-plot
+commands (as in pyplot and matlab). For example, you can type commands
+like the following:
 
 .. code-block:: python
 
@@ -368,11 +401,35 @@ to the more object oriented methods described above. For example, the
 function xlabel is equivalent to the method set_xlabel applied on the
 Axes object for the current figure.
 
+This module is by default imported into the standard MantidPlot
+namespace. You can use the functions and classes included here without
+any prefix or adding this module name prefix (pymantidplot.pyplot), as
+in the following example:
+
+.. code-block:: python
+
+    # Two equivalent lines:
+    pymantidplot.pyplot.plot([1, 3, 2])
+    plot([1, 3, 2])
+
+Note that the plot() function of this module has replaced the
+traditional plot() function of MantidPlot which has been moved into a
+package called qtiplot. To use it you can do as follows:
+
+.. code-block:: python
+
+    pymantidplot.qtiplot.plot('MAR11060', [800, 801])
+    # or if you prefer shorter prefixes:
+    import pymantidplot.qtiplot as qtiplt
+    qtiplt.plot('MAR11060', [800, 801])
+
+
 Below is the reference documentation of the classes and functions
 included in this module.
 
 """
-# Copyright &copy; 2007-2014 ISIS Rutherford Appleton Laboratory & NScD Oak Ridge National Laboratory
+# Copyright &copy; 2014-2015 ISIS Rutherford Appleton Laboratory, NScD
+# Oak Ridge National Laboratory & European Spallation Source
 #
 # This file is part of Mantid.
 # Mantid is free software; you can redistribute it and/or modify
@@ -394,7 +451,7 @@ included in this module.
 try:
     import _qti
 except ImportError:
-    raise ImportError('The \'mantidplot\' and \'pymantidplot.future.pyplot\' modules can only be used from within MantidPlot.')
+    raise ImportError('The \'mantidplot\' and \'pymantidplot.pyplot\' modules can only be used from within MantidPlot.')
 
 import numpy as np
 from PyQt4 import Qt, QtGui, QtCore
@@ -404,13 +461,6 @@ from mantid.api import mtd
 from mantid.simpleapi import CreateWorkspace as CreateWorkspace
 import mantidplot  
 
-print ("You are loading '" + __name__ + "', which is an experimental module." +
-"""
-Please note: this module is at a very early stage of development and
-provides limited functionality. It is work in progress and is subject
-to change. Feedback is very much welcome! Please let us know any wishes
-and suggestions.""")
-
 class Line2D():
     """
     A very minimal replica of matplotlib.Line.Line2D. The true Line2D
@@ -1225,19 +1275,21 @@ def __plot_as_array(*args, **kwargs):
     return __list_of_lines_from_graph(graph)
 
 def __plot_with_tool(tool, *args, **kwargs):
-    bin_tool_name = 'plot_bin'
-    spectrum_tool_name = 'plot_spectrum'
-    md_tool_name = 'plot_md'
+    bin_tool_names = ['plot_bin', 'bin']
+    spectrum_tool_names = ['plot_spectrum', 'plot_sp', 'spectrum', 'sp']
+    md_tool_names = ['plot_md', 'md']
 
-    if bin_tool_name == tool or spectrum_tool_name == tool:
-        if len(args) < 2:
-            raise ValueError("To plot using %s as a tool you need to give at least two parameters"%tool)
+    if len(args) < 2:
+        if tool in bin_tool_names:
+            raise ValueError("To plot bins (using '%s' as tool) you need to give at least two parameters, where the second parameter selects the bins"%tool)
+        elif tool in spectrum_tool_names:
+            raise ValueError("To plot spectra (using '%s' as tool) you need to give at least two parameters, where the second parameter selects the spectrum(a)"%tool)
 
-    if bin_tool_name == tool:
+    if tool in bin_tool_names:
         return plot_bin(args[0], args[1], *args[2:], **kwargs)
-    elif md_tool_name == tool:
+    elif tool in md_tool_names:
         return plot_md(args[0], *args[1:], **kwargs)
-    elif spectrum_tool_name == tool:
+    elif tool in spectrum_tool_names:
         return plot_spectrum(args[0], args[1], *args[2:], **kwargs)
     # here you would add slice/spectrum/instrument viewer, etc. and maybe you'll want to put them in a dict
     else:
@@ -1363,11 +1415,11 @@ def plot(*args, **kwargs):
     parameters, for example: linewidth, linestyle, marker, color.
 
     An important keyword argument is tool. At the moment the
-    following values are supported:
+    following values are supported (they have long and short aliases):
 
-    * plot_spectrum  (default for workspaces)
-    * plot_bin
-    * plot_md
+    * To plot spectra: 'plot_spectrum' OR 'spectrum' OR 'plot_sp' OR 'sp'  (default for workspaces).
+    * To plot bins: 'plot_bin' OR 'bin'
+    * To do an MD plot: 'plot_md' OR 'md'
 
     Please see the documentation of this module (use help()) for more details.
 
diff --git a/Code/Mantid/MantidPlot/pymantidplot/qtiplot.py b/Code/Mantid/MantidPlot/pymantidplot/qtiplot.py
new file mode 100644
index 0000000000000000000000000000000000000000..378cfc074d06941b3bc0e49ffadff11c17bfe5ad
--- /dev/null
+++ b/Code/Mantid/MantidPlot/pymantidplot/qtiplot.py
@@ -0,0 +1,35 @@
+"""
+MantidPlot module with functions specific to the traditional,
+qti-based MantidPlot Python plotting interface
+
+As with other MantidPlot modules, this has to run from within MantidPlot
+
+"""
+# Require MantidPlot
+try:
+    import _qti
+except ImportError:
+    raise ImportError('The "mantidplot.qtiplot" module can only be used from within MantidPlot.')
+
+import pymantidplot
+from PyQt4 import QtCore
+
+#-----------------------------------------------------------------------------
+# Intercept qtiplot "plot" command and forward to plotSpectrum for a workspace
+#
+# This function has been moved inside qtiplot when pymantidplot.pyplot (which
+# has another plot() function) was imported into the standard MantidPlot namespace
+def plot(source, *args, **kwargs):
+    """Create a new plot given a workspace, table or matrix.
+
+    Args:
+        source: what to plot; if it is a Workspace, will
+                call plotSpectrum()
+
+    Returns:
+        A handle to the created Graph widget.
+    """
+    if hasattr(source, '_getHeldObject') and isinstance(source._getHeldObject(), QtCore.QObject):
+        return pymantidplot.proxies.new_proxy(pymantidplot.proxies.Graph,_qti.app.plot, source._getHeldObject(), *args, **kwargs)
+    else:
+        return pymantidplot.plotSpectrum(source, *args, **kwargs)
diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp
index 94da5d32031dc63c05e3f20ed6532b8af488aa7a..a0945b25e73e36b23c4f99749c010d41c9d209df 100644
--- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp
+++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp
@@ -185,7 +185,6 @@
 #include "Mantid/ManageCustomMenus.h"
 #include "Mantid/ManageInterfaceCategories.h"
 #include "Mantid/FirstTimeSetup.h"
-#include "Mantid/SetUpParaview.h"
 
 #include "MantidQtAPI/FileDialogHandler.h"
 #include "MantidQtAPI/InterfaceManager.h"
@@ -219,12 +218,15 @@ using namespace Qwt3D;
 using namespace MantidQt::API;
 using Mantid::Kernel::ConfigService;
 
+using Mantid::API::FrameworkManager;
+using Mantid::Kernel::ConfigService;
+using Mantid::Kernel::LibraryManager;
+using Mantid::Kernel::Logger;
+
 namespace
 {
   /// static logger
-  Mantid::Kernel::Logger g_log("ApplicationWindow");
-  /// ParaView plugins key
-  const char * PVPLUGINS_DIR_KEY = "pvplugins.directory";
+  Logger g_log("ApplicationWindow");
 }
 
 extern "C"
@@ -354,11 +356,6 @@ void ApplicationWindow::init(bool factorySettings, const QStringList& args)
   logWindow->setWidget(resultsLog);
   connect(resultsLog, SIGNAL(errorReceived(const QString &)), logWindow, SLOT(show()));
 
-
-  // Start Mantid
-  // Set the Paraview path BEFORE libaries are loaded. Doing it here prevents
-  // the logs being poluted with library loading errors.
-  trySetParaviewPath(args);
   // Process all pending events before loading Mantid
   // Helps particularly on Windows with cleaning up the
   // splash screen after the 3D visualization dialog has closed
@@ -366,13 +363,16 @@ void ApplicationWindow::init(bool factorySettings, const QStringList& args)
 
   auto & config = ConfigService::Instance(); // Starts logging
   resultsLog->attachLoggingChannel(); // Must be done after logging starts
-  using Mantid::API::FrameworkManager;
-  auto & framework = FrameworkManager::Instance(); // Loads framework libraries
+  // Load Mantid core libraries by starting the framework
+  FrameworkManager::Instance();
   // Load Paraview plugin libraries if possible
-  if(config.quickParaViewCheck())
+  if(config.pvPluginsAvailable())
   {
     // load paraview plugins
-    framework.loadPluginsUsingKey(PVPLUGINS_DIR_KEY);
+    if (g_log.getLevel() == Logger::Priority::PRIO_DEBUG) {
+      g_log.debug("Loading libraries from \"" + config.getPVPluginsPath() + "\"");
+    }
+    LibraryManager::Instance().OpenAllLibraries(config.getPVPluginsPath(), false);
   }
 
   // Create UI object
@@ -599,13 +599,6 @@ void ApplicationWindow::init(bool factorySettings, const QStringList& args)
   // Do this as late as possible to avoid unnecessary updates
   AlgorithmFactory::Instance().enableNotifications();
   AlgorithmFactory::Instance().notificationCenter.postNotification(new AlgorithmFactoryUpdateNotification);
-
-  /*
-  The scripting enironment call setScriptingLanguage is trampling over the PATH, so we have to set it again.
-  Here we do not off the setup dialog.
-  */
-  const bool skipDialog = true;
-  trySetParaviewPath(args, skipDialog);
 }
 
 /** Determines if the first time dialog should be shown
@@ -674,79 +667,6 @@ bool ApplicationWindow::shouldWeShowFirstTimeSetup(const QStringList& commandArg
   return false;
 }
 
-/*
-Function tries to set the paraview path.
-
-This is a windows only feature. the PATH enviromental variable can be set at runtime on windows.
-
-- Abort if Vates libraries do not seem to be present.
-- Othwerise, if the paraview.path is already in the properties file, use it.
-- Otherwise, if the user is not using executeandquit command arguments launch the Setup gui.
-
-@param commandArguments : all command line arguments.
-@param noDialog : set to true to skip over the a dialog launch.
-*/
-void ApplicationWindow::trySetParaviewPath(const QStringList& commandArguments, bool noDialog)
-{
-#ifdef _WIN32
-
-    Mantid::Kernel::ConfigServiceImpl& confService = Mantid::Kernel::ConfigService::Instance();
-    //Early check of execute and quit command arguments used by system tests.
-    QString str;
-    bool b_skipDialog = noDialog;
-    foreach(str, commandArguments)
-    {
-      if ((this->shouldExecuteAndQuit(str)) ||
-        (this->isSilentStartup(str)))
-      {
-        b_skipDialog = true;
-        break;
-      }
-    }
-
-    //ONLY If skipping is not already selected
-    if(!b_skipDialog)
-    {
-      //If the ignore property exists and is set to true, then skip the dialog.
-      const std::string paraviewIgnoreProperty = "paraview.ignore";
-      b_skipDialog = confService.hasProperty(paraviewIgnoreProperty) && QString::fromStdString(confService.getString(paraviewIgnoreProperty)).toInt() > 0;
-    }
-
-    if(this->hasParaviewPath())
-    {
-      //Already have a path in the properties file, just apply it.
-      std::string path = confService.getString("paraview.path");
-      confService.setParaviewLibraryPath(path);
-    }
-    else
-    {
-      //Only run the following if skipping is not implied.
-      if(!b_skipDialog)
-      {
-        //Launch the dialog to set the PV path.
-        SetUpParaview pv(SetUpParaview::FirstLaunch);
-        pv.setWindowFlags(Qt::WindowStaysOnTopHint);
-        pv.exec();
-      }
-    }
-
-#else
-  UNUSED_ARG(commandArguments)
-  UNUSED_ARG(noDialog)
-#endif
-}
-
-
-/*
-Getter to determine if the paraview path has been set.
-*/
-bool ApplicationWindow::hasParaviewPath() const
-{
-  const std::string propertyname = "paraview.path";
-  Mantid::Kernel::ConfigServiceImpl& config = Mantid::Kernel::ConfigService::Instance();
-  return config.hasProperty(propertyname) && !config.getString(propertyname).empty() ;
-}
-
 void ApplicationWindow::initWindow()
 {
   switch(d_init_window_type){
@@ -1370,12 +1290,6 @@ void ApplicationWindow::initMainMenu()
   help->addAction(actionFirstTimeSetup);
   help->insertSeparator();
 
-  ///The paraview action should only be available on windows
-#ifdef _WIN32
-  help->addAction(actionSetupParaview);
-  help->insertSeparator();
-#endif
-
   help->addAction(actionAbout);
 
   icat = new QMenu(this);
@@ -9155,7 +9069,9 @@ void ApplicationWindow::minimizeWindow(MdiSubWindow *w)
   auto wli = dynamic_cast<WindowListItem*>(lv->currentItem());
 
   if (!wli)
-    w = wli->window();
+    return;
+
+  w = wli->window();
 
   if (!w)
     return;
@@ -10287,6 +10203,17 @@ void ApplicationWindow::showGraphContextMenu()
     cm.insertItem(tr("&Normalization"), &normalization);
   }
 
+  QMenu plotType(this);
+  if(ag->curves() > 1)
+  {
+    QAction *waterfall = new QAction(tr("&Waterfall"), &plotType);
+    waterfall->setCheckable(true);
+    waterfall->setChecked(ag->isWaterfallPlot());
+    connect(waterfall, SIGNAL(toggled(bool)), plot, SLOT(toggleWaterfall(bool)));
+    plotType.addAction(waterfall);
+    cm.insertItem(tr("&Plot Type"), &plotType);
+  }
+
   cm.insertSeparator();
   copy.insertItem(tr("&Layer"), this, SLOT(copyActiveLayer()));
   copy.insertItem(tr("&Window"), plot, SLOT(copyAllLayers()));
@@ -12127,9 +12054,6 @@ void ApplicationWindow::createActions()
   actionFirstTimeSetup = new QAction(tr("First Time Setup"), this);
   connect(actionFirstTimeSetup, SIGNAL(activated()), this, SLOT(showFirstTimeSetup()));
 
-  actionSetupParaview = new QAction(tr("Setup 3D Visualisation"), this);
-  connect(actionSetupParaview, SIGNAL(activated()), this, SLOT(showSetupParaview()));
-
   actionNewProject = new QAction(QIcon(":/NewProject16x16.png"), tr("New &Project"), this);
   actionNewProject->setShortcut( tr("Ctrl+N") );
   connect(actionNewProject, SIGNAL(activated()), this, SLOT(newProject()));
@@ -14099,14 +14023,6 @@ void ApplicationWindow::showalgorithmDescriptions()
   HelpWindow::showAlgorithm(this);
 }
 
-void ApplicationWindow::showSetupParaview()
-{
-  SetUpParaview* dialog = new SetUpParaview(SetUpParaview::MantidMenu);
-  dialog->setAttribute(Qt::WA_DeleteOnClose);
-  dialog->show();
-  dialog->setFocus();
-}
-
 void ApplicationWindow::showFirstTimeSetup()
 {
   FirstTimeSetup *dialog = new FirstTimeSetup(this);
diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.h b/Code/Mantid/MantidPlot/src/ApplicationWindow.h
index c984bd2ea01a50dddabf69493f1ae6e0bd4cfd17..4b011e51ed005cc442a2d8b0fbd6cae6c95fc8c0 100644
--- a/Code/Mantid/MantidPlot/src/ApplicationWindow.h
+++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.h
@@ -181,7 +181,7 @@ public:
 
   int matrixUndoStackSize(){return d_matrix_undo_stack_size;};
   void setMatrixUndoStackSize(int size);
-    
+
   // Check if delete workspace prompt is enabled
   bool isDeleteWorkspacePromptEnabled();
 
@@ -226,7 +226,7 @@ public slots:
   void onScriptExecuteError(const QString & message, const QString & scriptName, int lineNumber);
   /// Runs an arbitrary lump of python code, return true/false on success/failure.
   bool runPythonScript(const QString & code, bool async = false, bool quiet=false, bool redirect=true);
-  
+
   QList<MdiSubWindow *> windowsList() const;
   QList<MdiSubWindow *> getAllWindows() const;
   void updateWindowLists(MdiSubWindow *w);
@@ -595,8 +595,8 @@ public slots:
   //! Creates a new empty multilayer plot
   MultiLayer* newGraph(const QString& caption = tr("Graph"));
 
-  /// Prepares MultiLayer for plotting - creates if necessary, clears, applies initial settings 
-  MultiLayer* prepareMultiLayer(bool& isNew, MultiLayer* window, const QString& newWindowName = "Graph", 
+  /// Prepares MultiLayer for plotting - creates if necessary, clears, applies initial settings
+  MultiLayer* prepareMultiLayer(bool& isNew, MultiLayer* window, const QString& newWindowName = "Graph",
     bool clearWindow = false);
 
   void openRecentProject(int index);
@@ -1005,12 +1005,12 @@ public slots:
   //@{
   //! show scripting language selection dialog
   void showScriptingLangDialog();
-  //! switches to the given scripting language; 
+  //! switches to the given scripting language;
   bool setScriptingLanguage(const QString &lang);
 
   void scriptsDirPathChanged(const QString& path);
   //@}
-  
+
   void makeToolbarsMenu();
   void savetoNexusFile();
 
@@ -1076,10 +1076,8 @@ private:
   void savedatainNexusFormat(const std::string& wsName,const std::string & fileName);
   QPoint positionNewFloatingWindow(QSize sz) const;
   QPoint mdiAreaTopLeft() const;
-  bool hasParaviewPath() const;
   bool shouldExecuteAndQuit(const QString& arg);
   bool isSilentStartup(const QString& arg);
-  void trySetParaviewPath(const QStringList& commandArguments, bool noDialog=false);
   void handleConfigDir();
 
   //! \name Project File Loading
@@ -1189,9 +1187,6 @@ private slots:
   /// Open up the FirstRunSetup dialog
   void showFirstTimeSetup();
 
-  /// Open up the SetupParaview dialog
-  void showSetupParaview();
-
 public:
   // TODO: a lot of this stuff should be private
   bool d_showFirstTimeSetup;
@@ -1320,7 +1315,7 @@ public:
   bool applyCurveStyleToMantid; ///< if true defaultCurveStyle, defaultSymbolSize are applyed to MantidCurves
   /// if true all errors are drawn on new plots with error bars, for a particular graph can be overridden
   /// form Add Error bars dialog
-  bool drawAllErrors; 
+  bool drawAllErrors;
   QFont appFont, plot3DTitleFont, plot3DNumbersFont, plot3DAxesFont;
   QFont tableTextFont, tableHeaderFont, plotAxesFont, plotLegendFont, plotNumbersFont, plotTitleFont;
   QColor tableBkgdColor, tableTextColor, tableHeaderColor;
@@ -1354,7 +1349,7 @@ public:
   QString defaultScriptingLang;
 
   QDockWidget *m_interpreterDock;
-  
+
   QSet<QString> allCategories() const { return m_allCategories; }
 
 private:
@@ -1400,7 +1395,7 @@ private:
 
   QMenu *windowsMenu, *foldersMenu, *view, *graph, *fileMenu, *format, *edit;
   QMenu *recentProjectsMenu, *recentFilesMenu, *interfaceMenu;
-  
+
   QMenu *help, *plot2DMenu, *analysisMenu, *multiPeakMenu, *icat;
   QMenu *matrixMenu, *plot3DMenu, *plotDataMenu, *tablesDepend, *scriptingMenu;
   QMenu *tableMenu, *fillMenu, *normMenu, *newMenu, *exportPlotMenu, *smoothMenu, *filterMenu, *decayMenu,*saveMenu,*openMenu, *toolbarsMenu;
@@ -1471,7 +1466,7 @@ private:
   QAction *actionMatrixXY, *actionMatrixColumnRow, *actionImagePlot;
   QAction *actionMatrixFFTDirect, *actionMatrixFFTInverse;
   QAction *actionFontBold, *actionFontItalic, *actionFontBox, *actionFontSize;
-  QAction *actionSuperscript, *actionSubscript, *actionUnderline, *actionGreekSymbol, *actionCustomActionDialog, *actionManageDirs, *actionFirstTimeSetup, *actionSetupParaview;
+  QAction *actionSuperscript, *actionSubscript, *actionUnderline, *actionGreekSymbol, *actionCustomActionDialog, *actionManageDirs, *actionFirstTimeSetup;
   QAction *actionGreekMajSymbol, *actionMathSymbol;
   QAction *Box, *Frame, *None;
   QAction *front, *back, *right, *left, *ceil, *floor, *floordata, *flooriso, *floornone;
@@ -1483,7 +1478,7 @@ private:
 
   QList<QAction *> d_user_actions;
   QList<QMenu* > d_user_menus; //Mantid
-  
+
   QList<QAction *> m_interfaceActions;
 
   /// list of mantidmatrix windows opened from project file.
@@ -1502,7 +1497,7 @@ private:
   QList<FloatingWindow*> m_floatingWindows;
   // To block activating new window when a floating window is in process of resetting flags
   bool blockWindowActivation;
-  /// 
+  ///
   bool m_enableQtiPlotFitting;
 
 #ifdef SHARED_MENUBAR
diff --git a/Code/Mantid/MantidPlot/src/ConfigDialog.cpp b/Code/Mantid/MantidPlot/src/ConfigDialog.cpp
index 836e1f1da9219f5e54132f103f69a0528f0fc6e6..0f05e50e681bbeda61323c300b2576507547fe9f 100644
--- a/Code/Mantid/MantidPlot/src/ConfigDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/ConfigDialog.cpp
@@ -728,13 +728,13 @@ void ConfigDialog::initMdPlottingPage()
   // Update the visibility of the Vsi tab if the General Md Color Map was selected the last time
   if (m_mdSettings.getUsageGeneralMdColorMap())
   {
-    changeUsageGeneralMdColorMap(true);
+    changeUsageGeneralMdColorMap();
   }
 
   // Update the visibility of the Vsi tab if the last session checkbox was selected.
   if (m_mdSettings.getUsageLastSession())
   {
-    changeUsageLastSession(true);
+    changeUsageLastSession();
   }
 }
 
@@ -751,7 +751,6 @@ void ConfigDialog::initMdPlottingGeneralTab()
   mdPlottingTabWidget->addTab(mdPlottingGeneralPage, QString());
 
   // Color Map
-  mdPlottingGeneralFrame->setTitle("Use common Color Map for Slice Viewer and VSI");
   mdPlottingGeneralFrame->setCheckable(true);
   mdPlottingGeneralFrame->setChecked(m_mdSettings.getUsageGeneralMdColorMap());
 
@@ -794,39 +793,41 @@ void ConfigDialog::initMdPlottingVsiTab()
 {
   vsiPage = new QWidget();
   QVBoxLayout *vsiTabLayout = new QVBoxLayout(vsiPage);
-  QGroupBox *frame = new QGroupBox();
-  vsiTabLayout->addWidget(frame);
-  QGridLayout *grid = new QGridLayout(frame);
-  mdPlottingTabWidget->addTab(vsiPage, QString());
 
-  // Usage of the last setting
-  vsiLastSession = new QCheckBox();
-  lblVsiLastSession = new QLabel();
-  grid->addWidget(lblVsiLastSession , 0, 0);
-  grid->addWidget(vsiLastSession , 0, 1);
-  vsiLastSession->setChecked(m_mdSettings.getUsageLastSession());
+  // Initial View when loading into the VSI
+  QGroupBox *frameTop = new QGroupBox();
+  vsiTabLayout->addWidget(frameTop);
+  QGridLayout *gridTop = new QGridLayout(frameTop);
+  vsiInitialView = new QComboBox();
+
+  lblVsiInitialView = new QLabel();
+  gridTop->addWidget(lblVsiInitialView, 0, 0);
+  gridTop->addWidget(vsiInitialView, 0, 1);
+
+  mdPlottingVsiFrameBottom = new QGroupBox();
+  mdPlottingVsiFrameBottom->setCheckable(true);
+  mdPlottingVsiFrameBottom->setChecked(!m_mdSettings.getUsageLastSession());
+
+  vsiTabLayout->addWidget(mdPlottingVsiFrameBottom);
+  QGridLayout *grid = new QGridLayout(mdPlottingVsiFrameBottom);
+
+  mdPlottingTabWidget->addTab(vsiPage, QString());
 
   // Color Map
   vsiDefaultColorMap = new QComboBox();
   lblVsiDefaultColorMap = new QLabel();
-  grid->addWidget(lblVsiDefaultColorMap, 1, 0);
-  grid->addWidget(vsiDefaultColorMap, 1, 1);
+  grid->addWidget(lblVsiDefaultColorMap, 0, 0);
+  grid->addWidget(vsiDefaultColorMap, 0, 1);
 
   // Background Color
   vsiDefaultBackground = new ColorButton();
   lblVsiDefaultBackground = new QLabel();
-  grid->addWidget(lblVsiDefaultBackground, 2, 0);
-  grid->addWidget(vsiDefaultBackground, 2, 1);
+  grid->addWidget(lblVsiDefaultBackground, 1, 0);
+  grid->addWidget(vsiDefaultBackground, 1, 1);
 
   const QColor backgroundColor = m_mdSettings.getUserSettingBackgroundColor();
   vsiDefaultBackground->setColor(backgroundColor);
 
-  // Initial View when loading into the VSI
-  vsiInitialView = new QComboBox();
-  lblVsiInitialView = new QLabel();
-  grid->addWidget(lblVsiInitialView, 3, 0);
-  grid->addWidget(vsiInitialView, 3, 1);
-
   grid->setRowStretch(4,1);
 
   QLabel* label1 = new QLabel("<span style=\"font-weight:600;\">Note: The General Tab settings take precedence over the VSI Tab settings.</span>");
@@ -868,37 +869,37 @@ void ConfigDialog::initMdPlottingVsiTab()
  */
 void ConfigDialog::setupMdPlottingConnections()
 {
-  QObject::connect(this->mdPlottingGeneralFrame, SIGNAL(toggled(bool)), this, SLOT(changeUsageGeneralMdColorMap(bool)));
-  QObject::connect(this->vsiLastSession, SIGNAL(toggled(bool)), this, SLOT(changeUsageLastSession(bool)));
+  QObject::connect(this->mdPlottingGeneralFrame, SIGNAL(toggled(bool)), this, SLOT(changeUsageGeneralMdColorMap()));
+  QObject::connect(this->mdPlottingVsiFrameBottom, SIGNAL(toggled(bool)), this, SLOT(changeUsageLastSession()));
 }
 
 /**
  * Handle a change of the General Md Color Map selection.
- * @param The state of the general MD color map checkbox
  */
-void ConfigDialog::changeUsageGeneralMdColorMap(bool state)
+void ConfigDialog::changeUsageGeneralMdColorMap()
 {
-  // Set the visibility of the default color map of the VSI
-  vsiDefaultColorMap->setDisabled(state);
-  lblVsiDefaultColorMap->setDisabled(state);
+  // If the general color map setting is turned off and the vsi colormap is turned on
+  // then we set the default color map to enabled, else we disable it
+  bool isDefaultColorMapSelectable = (!mdPlottingGeneralFrame->isChecked() && mdPlottingVsiFrameBottom->isChecked());
+
+  vsiDefaultColorMap->setEnabled(isDefaultColorMapSelectable);
+  lblVsiDefaultColorMap->setEnabled(isDefaultColorMapSelectable);
+  //vsiDefaultColorMap->setEnabled(true);
+  //lblVsiDefaultColorMap->setEnabled(true);
 }
 
 /**
  * Handle a change of the Last Session selection.
-  * @param The state of the last session checkbox.
+  * @param isDefaultColorMapVsiChecked The state of the vsi default checkbox.
  */
-void ConfigDialog::changeUsageLastSession(bool state)
+void ConfigDialog::changeUsageLastSession()
 {
-  // Set the visibility of the default color map of the VSI
-  if (!mdPlottingGeneralFrame->isChecked())
-  {
-    vsiDefaultColorMap->setDisabled(state);
-    lblVsiDefaultColorMap->setDisabled(state);
-  }
+  // Set the color map of the VSI default
+  changeUsageGeneralMdColorMap();
 
   // Set the visibility of the background color button of the VSI
-  vsiDefaultBackground->setDisabled(state);
-  lblVsiDefaultBackground->setDisabled(state);
+  vsiDefaultBackground->setEnabled(mdPlottingVsiFrameBottom->isChecked());
+  lblVsiDefaultBackground->setEnabled(mdPlottingVsiFrameBottom->isChecked());
 }
 
 
@@ -2188,13 +2189,39 @@ void ConfigDialog::languageChange()
 
   // MDPlotting change
   mdPlottingTabWidget->setTabText(mdPlottingTabWidget->indexOf(vsiPage), tr("VSI"));
-  lblVsiDefaultColorMap->setText(tr("Default Color Map"));
-  lblVsiDefaultBackground->setText(tr("Background Color"));
-  lblVsiLastSession->setText(tr("Use the settings of the last VSI session"));
-  lblVsiInitialView->setText(tr("Initial View"));
-
   mdPlottingTabWidget->setTabText(mdPlottingTabWidget->indexOf(mdPlottingGeneralPage), tr("General"));
-  lblGeneralDefaultColorMap->setText(tr("General Color Map"));
+
+  // Vsi background color
+  QString vsiDefaultBackgroundToolTipText = "Sets the default background color when a new instance of the VSI is opened.";
+  vsiDefaultBackground->setToolTip(vsiDefaultBackgroundToolTipText);
+  lblVsiDefaultBackground->setToolTip(vsiDefaultBackgroundToolTipText);
+  lblVsiDefaultBackground->setText(tr("Background color"));
+
+  // Vsi initial view
+  QString vsiInitialViewToolTipText = "Sets the initial view when loading a new source into the VSI.";
+  lblVsiInitialView->setText(tr("Initial view"));
+  vsiInitialView->setToolTip(vsiInitialViewToolTipText);
+  lblVsiInitialView->setToolTip(vsiInitialViewToolTipText);
+
+  // VSI master default
+  QString vsiMasterDefaultToolTipText = "User master defaults for the color map and the background color. If not checked the settings of the last session are used.";
+  mdPlottingVsiFrameBottom->setTitle(tr("Use defaults for color map and background color"));
+  mdPlottingVsiFrameBottom->setToolTip(vsiMasterDefaultToolTipText);
+
+  // Vsi default color map
+  QString vsiDefaultColorMapToolTipText = "Sets the default color map when a new instance of the VSI is opened.";
+  vsiDefaultColorMap->setToolTip(vsiDefaultColorMapToolTipText);
+  lblVsiDefaultColorMap->setToolTip(vsiDefaultColorMapToolTipText);
+  lblVsiDefaultColorMap->setText(tr("Default color map"));
+
+  // General plotting tab
+  QString vsiGeneralDefaultColorMapToolTipText = "Sets the default color map for both the Slice Viewer and the VSI.";
+  mdPlottingGeneralColorMap->setToolTip(vsiGeneralDefaultColorMapToolTipText);
+  lblGeneralDefaultColorMap->setToolTip(vsiGeneralDefaultColorMapToolTipText);
+  lblGeneralDefaultColorMap->setText(tr("Default color map"));
+
+  mdPlottingGeneralFrame->setTitle("Use same default color map for Slice Viewer and VSI");
+  mdPlottingGeneralFrame->setToolTip("The specifed color map will be available for the Slice Viewer and the VSI when a new instance of either is started.");
 }
 
 void ConfigDialog::accept()
@@ -2465,10 +2492,14 @@ void ConfigDialog::updateMdPlottingSettings()
     m_mdSettings.setUserSettingColorMap(vsiDefaultColorMap->currentText());
   }
 
-  // Read if the usage of the last color map should be performed
-  if (vsiLastSession)
+  // Read if the usage of the last color map and background color should be performed
+  if (mdPlottingVsiFrameBottom->isChecked())
+  {
+    m_mdSettings.setUsageLastSession(false);
+  }
+  else
   {
-    m_mdSettings.setUsageLastSession(vsiLastSession->isChecked());
+    m_mdSettings.setUsageLastSession(true);
   }
 
   // Read the background selection
diff --git a/Code/Mantid/MantidPlot/src/ConfigDialog.h b/Code/Mantid/MantidPlot/src/ConfigDialog.h
index 05f5a7d17d66f48dde8d4ffbaafed6787d67edc8..64f80367c2e9aa5119081d709160ca78fdd0591a 100644
--- a/Code/Mantid/MantidPlot/src/ConfigDialog.h
+++ b/Code/Mantid/MantidPlot/src/ConfigDialog.h
@@ -218,7 +218,7 @@ private:
   QComboBox *vsiDefaultColorMap, *vsiInitialView, *mdPlottingGeneralColorMap;
   QLabel *lblVsiDefaultColorMap, *lblVsiDefaultBackground, *lblGeneralDefaultColorMap, *lblBoxGeneralDefaultColorMap, *lblVsiLastSession, *lblVsiInitialView;
   ColorButton *vsiDefaultBackground;
-  QGroupBox* mdPlottingGeneralFrame;
+  QGroupBox* mdPlottingGeneralFrame, *mdPlottingVsiFrameBottom;
   QCheckBox* vsiLastSession;
   MantidQt::API::MdSettings m_mdSettings;
 
@@ -276,8 +276,8 @@ private:
   QCheckBox *boxUpdateTableValues;
 
   public slots:
-    void changeUsageGeneralMdColorMap(bool state);
-    void changeUsageLastSession(bool state);
+    void changeUsageGeneralMdColorMap();
+    void changeUsageLastSession();
 };
 
 #endif // CONFIGDIALOG_H
diff --git a/Code/Mantid/MantidPlot/src/Mantid/MantidDock.cpp b/Code/Mantid/MantidPlot/src/Mantid/MantidDock.cpp
index 25d0de248961ebaacb6698d26e7fc72bc572b11c..febf051100738ecf83ecd27520ed7863d9bf0fbd 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/MantidDock.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/MantidDock.cpp
@@ -1344,21 +1344,27 @@ void MantidDockWidget::groupingButtonClick()
 /// Plots a single spectrum from each selected workspace
 void MantidDockWidget::plotSpectra()
 {
-  const QMultiMap<QString,std::set<int> > toPlot = m_tree->chooseSpectrumFromSelected();
+  const auto userInput = m_tree->chooseSpectrumFromSelected();
   // An empty map will be returned if the user clicks cancel in the spectrum selection
-  if (toPlot.empty()) return;
+  if (userInput.plots.empty()) return;
 
-  m_mantidUI->plot1D(toPlot, true, MantidQt::DistributionDefault, false);
+  bool spectrumPlot(true), errs(false), clearWindow(false);
+  MultiLayer *window(NULL);
+  m_mantidUI->plot1D(userInput.plots, spectrumPlot, MantidQt::DistributionDefault, errs,
+                     window, clearWindow, userInput.waterfall);
 }
 
 /// Plots a single spectrum from each selected workspace with errors
 void MantidDockWidget::plotSpectraErr()
 {
-  const QMultiMap<QString,std::set<int> > toPlot = m_tree->chooseSpectrumFromSelected();
+  const auto userInput = m_tree->chooseSpectrumFromSelected();
   // An empty map will be returned if the user clicks cancel in the spectrum selection
-  if (toPlot.empty()) return;
+  if (userInput.plots.empty()) return;
 
-  m_mantidUI->plot1D(toPlot, true, MantidQt::DistributionDefault, true);
+  bool spectrumPlot(true), errs(true), clearWindow(false);
+  MultiLayer *window(NULL);
+  m_mantidUI->plot1D(userInput.plots, spectrumPlot, MantidQt::DistributionDefault, errs,
+                     window, clearWindow, userInput.waterfall);
 }
 
 /**
@@ -1671,9 +1677,10 @@ QStringList MantidTreeWidget::getSelectedWorkspaceNames() const
 * TableWorkspaces (which are implicitly excluded).  We only want workspaces we
 * can actually plot!
 *
-* @return :: A map of workspace name to spectrum numbers to plot.
+* @param showWaterfallOpt If true, show the waterfall option on the dialog
+* @return :: A MantidWSIndexDialog::UserInput structure listing the selected options
 */
-QMultiMap<QString,std::set<int> > MantidTreeWidget::chooseSpectrumFromSelected() const
+MantidWSIndexDialog::UserInput MantidTreeWidget::chooseSpectrumFromSelected(bool showWaterfallOpt) const
 {
   // Check for any selected WorkspaceGroup names and replace with the names of
   // their children.
@@ -1731,13 +1738,17 @@ QMultiMap<QString,std::set<int> > MantidTreeWidget::chooseSpectrumFromSelected()
         SINGLE_SPECTRUM
         );
     }
-    return spectrumToPlot;
+    MantidWSIndexDialog::UserInput selections;
+    selections.plots = spectrumToPlot;
+    selections.waterfall = false;
+    return selections;
   }
 
-  // Else, one or more workspaces 
-  MantidWSIndexDialog *dio = new MantidWSIndexDialog(m_mantidUI, 0, selectedMatrixWsNameList);
+  // Else, one or more workspaces
+  MantidWSIndexDialog *dio = new MantidWSIndexDialog(m_mantidUI, 0, selectedMatrixWsNameList,
+                                                     showWaterfallOpt);
   dio->exec();
-  return dio->getPlots();
+  return dio->getSelections();
 }
 
 void MantidTreeWidget::setSortScheme(MantidItemSortScheme sortScheme)
diff --git a/Code/Mantid/MantidPlot/src/Mantid/MantidDock.h b/Code/Mantid/MantidPlot/src/Mantid/MantidDock.h
index af2b1087c93c932bca6f83e20ab04c01c8bb4f38..07eb2e9f8a2b28062a1b81a05246ed828989733d 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/MantidDock.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/MantidDock.h
@@ -11,6 +11,8 @@
 
 #include "MantidQtMantidWidgets/AlgorithmSelectorWidget.h"
 
+#include "Mantid/MantidWSIndexDialog.h"
+
 #include <QActionGroup>
 #include <QAtomicInt>
 #include <QComboBox>
@@ -165,7 +167,7 @@ public:
   void mouseDoubleClickEvent(QMouseEvent *e);
 
   QStringList getSelectedWorkspaceNames() const;
-  QMultiMap<QString,std::set<int> > chooseSpectrumFromSelected() const;
+  MantidWSIndexDialog::UserInput chooseSpectrumFromSelected(bool showWaterfallOpt = true) const;
   void setSortScheme(MantidItemSortScheme);
   void setSortOrder(Qt::SortOrder);
   MantidItemSortScheme getSortScheme() const;
diff --git a/Code/Mantid/MantidPlot/src/Mantid/MantidUI.cpp b/Code/Mantid/MantidPlot/src/Mantid/MantidUI.cpp
index 80adf7e541d2fce4495aefb8cf69883859f85593..80a11e9aa86075b78062b80f29a104fe54340780 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/MantidUI.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/MantidUI.cpp
@@ -18,6 +18,7 @@
 #include "../ScriptingWindow.h"
 #include "../Folder.h"
 #include "../TiledWindow.h"
+#include "../PythonThreading.h"
 
 #include "MantidKernel/Property.h"
 #include "MantidKernel/ConfigService.h"
@@ -110,8 +111,8 @@ MantidUI::MantidUI(ApplicationWindow *aw):
   m_configServiceObserver(*this,&MantidUI::handleConfigServiceUpdate),
   m_appWindow(aw),
   m_lastShownInstrumentWin(NULL), m_lastShownSliceViewWin(NULL), m_lastShownSpectrumViewerWin(NULL), 
-  m_lastShownColorFillWin(NULL), m_lastShown1DPlotWin(NULL), 
-  m_vatesSubWindow(NULL)//, m_spectrumViewWindow(NULL)
+  m_lastShownColorFillWin(NULL), m_lastShown1DPlotWin(NULL), m_vatesSubWindow(NULL)
+  //, m_spectrumViewWindow(NULL)
 {
 
   // To be able to use them in queued signals they need to be registered
@@ -305,8 +306,8 @@ void MantidUI::shutdown()
       Poco::Thread::sleep(100);
     }
   }
-
-  Mantid::API::FrameworkManager::Instance().clear();
+  bool prompt = false;
+  this->clearAllMemory(prompt);
 }
 
 MantidUI::~MantidUI()
@@ -733,7 +734,8 @@ void MantidUI::showVatesSimpleInterface()
     {
       m_vatesSubWindow = new QMdiSubWindow;
       m_vatesSubWindow->setAttribute(Qt::WA_DeleteOnClose, false);
-      QIcon icon; icon.addFile(QString::fromUtf8(":/VatesSimpleGuiViewWidgets/icons/pvIcon.png"), QSize(), QIcon::Normal, QIcon::Off);
+      QIcon icon; 
+      icon.addFile(QString::fromUtf8(":/VatesSimpleGuiViewWidgets/icons/pvIcon.png"), QSize(), QIcon::Normal, QIcon::Off);
       m_vatesSubWindow->setWindowIcon(icon);
       connect(m_appWindow, SIGNAL(shutting_down()), m_vatesSubWindow, SLOT(close()));
 
@@ -746,12 +748,11 @@ void MantidUI::showVatesSimpleInterface()
         connect(vsui, SIGNAL(requestClose()), m_vatesSubWindow, SLOT(close()));
         vsui->setParent(m_vatesSubWindow);
         m_vatesSubWindow->setWindowTitle("Vates Simple Interface");
-
         vsui->setupPluginMode();
         //m_appWindow->setGeometry(m_vatesSubWindow, vsui);
         m_vatesSubWindow->setWidget(vsui);
         m_vatesSubWindow->widget()->show();
-        vsui->renderWorkspace(wsName, wsType, instrumentName);
+        vsui->renderWorkspace(wsName, wsType,instrumentName);
       }
       else
       {
@@ -2121,13 +2122,17 @@ void MantidUI::insertMenu()
   appWindow()->myMenuBar()->insertItem(tr("Man&tid"), mantidMenu);
 }
 
-void MantidUI::clearAllMemory()
+void MantidUI::clearAllMemory(const bool prompt)
 {
+  if(prompt) {
   QMessageBox::StandardButton pressed =
     QMessageBox::question(appWindow(), "MantidPlot", "All workspaces and windows will be removed. Are you sure?", QMessageBox::Ok|QMessageBox::Cancel, QMessageBox::Ok);
 
   if( pressed != QMessageBox::Ok ) return;
-
+  }
+  // If any python objects need to be cleared away then the GIL needs to be held. This doesn't feel like
+  // it is in the right place but it will do no harm
+  GlobalInterpreterLock gil;
   // Relevant notifications are connected to signals that will close all dependent windows
   Mantid::API::FrameworkManager::Instance().clear();
 }
@@ -2176,6 +2181,8 @@ void MantidUI::disableSaveNexus()
 */
 QString MantidUI::saveToString(const std::string& workingDir)
 {
+  using namespace Mantid::API;
+
   QString wsNames;
   wsNames="<mantidworkspaces>\n";
   wsNames+="WorkspaceNames";
@@ -2185,19 +2192,22 @@ QString MantidUI::saveToString(const std::string& workingDir)
   { 
     QTreeWidgetItem* item=tree->topLevelItem(i);
     QString wsName=item->text(0);
-    if (Mantid::API::FrameworkManager::Instance().getWorkspace(wsName.toStdString())->id() == "WorkspaceGroup")
+
+    Workspace_sptr ws = AnalysisDataService::Instance().retrieveWS<Workspace>(wsName.toStdString());
+    WorkspaceGroup_sptr group = boost::dynamic_pointer_cast<Mantid::API::WorkspaceGroup>(ws);
+    // We don't split up multiperiod workspaces for performance reasons.
+    // There's significant optimisations we can perform on load if they're a
+    // single file.
+    if (ws->id() == "WorkspaceGroup" && group && !group->isMultiperiod())
     {
-      Mantid::API::WorkspaceGroup_sptr group = boost::dynamic_pointer_cast<Mantid::API::WorkspaceGroup>(Mantid::API::AnalysisDataService::Instance().retrieve(wsName.toStdString()));
       wsNames+="\t";
-      //wsName is a group, add it to list and indicate what the group contains by a "[" and end the group with a "]"
       wsNames+=wsName;
       std::vector<std::string> secondLevelItems = group->getNames();
-      for(size_t j=0; j<secondLevelItems.size(); j++) //ignore string "WorkspaceGroup at position 0" (start at child '1')
+      for(size_t j=0; j<secondLevelItems.size(); j++)
       {
         wsNames+=",";
         wsNames+=QString::fromStdString(secondLevelItems[j]);
         std::string fileName(workingDir + "//" + secondLevelItems[j] + ".nxs");
-        //saving to  nexus file
         savedatainNexusFormat(fileName,secondLevelItems[j]);
       }
     }
@@ -2207,7 +2217,6 @@ QString MantidUI::saveToString(const std::string& workingDir)
       wsNames+=wsName;
 
       std::string fileName(workingDir + "//" + wsName.toStdString() + ".nxs");
-      //saving to  nexus file
       savedatainNexusFormat(fileName,wsName.toStdString());
     }
   }
@@ -2523,6 +2532,9 @@ void MantidUI::importNumSeriesLog(const QString &wsName, const QString &logName,
     t->setNumericPrecision(16);   //it's the number of all digits
   }
 
+  // The time when the first data was recorded.
+  auto firstTime = time_value_map.begin()->first;
+
   //Make the column header with the units, if any
   QString column1 = label.section("-",1);
   if (logData->units() != "")
@@ -2537,6 +2549,7 @@ void MantidUI::importNumSeriesLog(const QString &wsName, const QString &logName,
     Mantid::Kernel::TimeSeriesProperty<bool>* f = 0;
     if (filter == 1 || filter ==3)
     {
+      // one of the filters is the running status
       try
       {
         f = dynamic_cast<Mantid::Kernel::TimeSeriesProperty<bool> *>(ws->run().getLogData("running"));
@@ -2549,6 +2562,15 @@ void MantidUI::importNumSeriesLog(const QString &wsName, const QString &logName,
           importNumSeriesLog(wsName,logName,0);
           return;
         }
+        // If filter records start later than the data we add a value at the filter's front
+        if ( f->firstTime() > firstTime )
+        {
+          // add a "not running" value to the status filter
+          Mantid::Kernel::TimeSeriesProperty<bool> atStart("tmp");
+          atStart.addValue(firstTime,false);
+          atStart.addValue(f->firstTime(),f->firstValue());
+          flt.addFilter(atStart);
+        }
       }
       catch(...)
       {
@@ -2985,9 +3007,10 @@ Plots the spectra from the given workspaces
 @param style :: Curve style for plot
 @param plotWindow :: Window to plot to. If NULL a new one will be created
 @param clearWindow :: Whether to clear specified plotWindow before plotting. Ignored if plotWindow == NULL
+@param waterfallPlot :: If true create a waterfall type plot
 */
 MultiLayer* MantidUI::plot1D(const QStringList& ws_names, const QList<int>& indexList, bool spectrumPlot, bool errs,
-                             Graph::CurveType style, MultiLayer* plotWindow, bool clearWindow)
+                             Graph::CurveType style, MultiLayer* plotWindow, bool clearWindow, bool waterfallPlot)
 {
   // Convert the list into a map (with the same workspace as key in each case)
   QMultiMap<QString,int> pairs;
@@ -3009,7 +3032,8 @@ MultiLayer* MantidUI::plot1D(const QStringList& ws_names, const QList<int>& inde
   }
 
   // Pass over to the overloaded method
-  return plot1D(pairs,spectrumPlot,MantidQt::DistributionDefault, errs,style,plotWindow, clearWindow);
+  return plot1D(pairs,spectrumPlot,MantidQt::DistributionDefault, errs,style,plotWindow, clearWindow,
+                waterfallPlot);
 }
 /** Create a 1D graph from the specified list of workspaces/spectra.
 @param toPlot :: Map of form ws -> [spectra_list]
@@ -3018,11 +3042,12 @@ MultiLayer* MantidUI::plot1D(const QStringList& ws_names, const QList<int>& inde
 @param errs :: If true include the errors on the graph
 @param plotWindow :: Window to plot to. If NULL a new one will be created
 @param clearWindow :: Whether to clear specified plotWindow before plotting. Ignored if plotWindow == NULL
+@param waterfallPlot :: If true create a waterfall type plot
 @return NULL if failure. Otherwise, if plotWindow == NULL - created window, if not NULL - plotWindow
 */
 MultiLayer* MantidUI::plot1D(const QMultiMap<QString, set<int> >& toPlot, bool spectrumPlot,
                              MantidQt::DistributionFlag distr, bool errs,
-                             MultiLayer* plotWindow, bool clearWindow)
+                             MultiLayer* plotWindow, bool clearWindow, bool waterfallPlot)
 {
   // Convert the list into a map (with the same workspace as key in each case)
   QMultiMap<QString,int> pairs;
@@ -3038,7 +3063,7 @@ MultiLayer* MantidUI::plot1D(const QMultiMap<QString, set<int> >& toPlot, bool s
   }
 
   // Pass over to the overloaded method
-  return plot1D(pairs,spectrumPlot,distr,errs,Graph::Unspecified,plotWindow, clearWindow);
+  return plot1D(pairs,spectrumPlot,distr,errs,Graph::Unspecified,plotWindow, clearWindow, waterfallPlot);
 }
 
 /** Create a 1d graph from the specified spectra in a MatrixWorkspace
@@ -3049,10 +3074,11 @@ MultiLayer* MantidUI::plot1D(const QMultiMap<QString, set<int> >& toPlot, bool s
 @param errs :: If true include the errors on the graph
 @param plotWindow :: Window to plot to. If NULL a new one will be created
 @param clearWindow :: Whether to clear specified plotWindow before plotting. Ignored if plotWindow == NULL
+@param waterfallPlot :: If true create a waterfall type plot
 @return NULL if failure. Otherwise, if plotWindow == NULL - created window, if not NULL - plotWindow
 */
 MultiLayer* MantidUI::plot1D(const QString& wsName, const std::set<int>& indexList, bool spectrumPlot,
-  MantidQt::DistributionFlag distr, bool errs, MultiLayer* plotWindow, bool clearWindow)
+  MantidQt::DistributionFlag distr, bool errs, MultiLayer* plotWindow, bool clearWindow, bool waterfallPlot)
 {
   // Convert the list into a map (with the same workspace as key in each case)
   QMultiMap<QString,int> pairs;
@@ -3064,7 +3090,7 @@ MultiLayer* MantidUI::plot1D(const QString& wsName, const std::set<int>& indexLi
   }
 
   // Pass over to the overloaded method
-  return plot1D(pairs,spectrumPlot,distr,errs,Graph::Unspecified,plotWindow, clearWindow);
+  return plot1D(pairs,spectrumPlot,distr,errs,Graph::Unspecified,plotWindow, clearWindow, waterfallPlot);
 }
 
 /** Create a 1d graph form a set of workspace-spectrum pairs
@@ -3075,11 +3101,13 @@ MultiLayer* MantidUI::plot1D(const QString& wsName, const std::set<int>& indexLi
 @param style :: curve style for plot
 @param plotWindow :: Window to plot to. If NULL a new one will be created
 @param clearWindow :: Whether to clear specified plotWindow before plotting. Ignored if plotWindow == NULL
+@param waterfallPlot :: If true create a waterfall type plot
 @return NULL if failure. Otherwise, if plotWindow == NULL - created window, if not NULL - plotWindow
 */
 MultiLayer* MantidUI::plot1D(const QMultiMap<QString,int>& toPlot, bool spectrumPlot,
                              MantidQt::DistributionFlag distr, bool errs,
-                             Graph::CurveType style, MultiLayer* plotWindow, bool clearWindow)
+                             Graph::CurveType style, MultiLayer* plotWindow,
+                             bool clearWindow, bool waterfallPlot)
 {
   if(toPlot.size() == 0) return NULL;
 
@@ -3094,6 +3122,8 @@ MultiLayer* MantidUI::plot1D(const QMultiMap<QString,int>& toPlot, bool spectrum
     ask.exec();
     if (ask.clickedButton() != confirmButton) return NULL;
   }
+  // Force waterfall option to false if only 1 curve
+  if(toPlot.size() == 1) waterfallPlot = false;
 
   QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
 
@@ -3206,7 +3236,7 @@ MultiLayer* MantidUI::plot1D(const QMultiMap<QString,int>& toPlot, bool spectrum
     // happen, but it does apparently with some muon analyses.
     g->checkValuesInAxisRange(firstCurve);
   }
-
+  ml->toggleWaterfall(waterfallPlot);
   // Check if window does not contain any curves and should be closed
   ml->maybeNeedToClose();
 
diff --git a/Code/Mantid/MantidPlot/src/Mantid/MantidUI.h b/Code/Mantid/MantidPlot/src/Mantid/MantidUI.h
index f1c52ce45f689124bfe4e54a44258b89d4337162..73d70f58bde40bf3fdaa40e60ee1e22d522b710a 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/MantidUI.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/MantidUI.h
@@ -212,23 +212,23 @@ public:
     // Create a 1d graph form specified MatrixWorkspace and index
   MultiLayer* plot1D(const QStringList& wsnames, const QList<int>& indexList, bool spectrumPlot,
                      bool errs=true, Graph::CurveType style = Graph::Unspecified,
-                     MultiLayer* plotWindow = NULL, bool clearWindow = false);
+                     MultiLayer* plotWindow = NULL, bool clearWindow = false, bool waterfallPlot = false);
 
   MultiLayer* plot1D(const QString& wsName, const std::set<int>& indexList, bool spectrumPlot,
                      MantidQt::DistributionFlag distr = MantidQt::DistributionDefault,
                      bool errs=false,
-                     MultiLayer* plotWindow = NULL, bool clearWindow = false);
+                     MultiLayer* plotWindow = NULL, bool clearWindow = false, bool waterfallPlot = false);
 
   MultiLayer* plot1D(const QMultiMap<QString,int>& toPlot, bool spectrumPlot,
                      MantidQt::DistributionFlag distr = MantidQt::DistributionDefault,
                      bool errs=false,
                      Graph::CurveType style = Graph::Unspecified,
-                     MultiLayer* plotWindow = NULL, bool clearWindow = false);
+                     MultiLayer* plotWindow = NULL, bool clearWindow = false, bool waterfallPlot = false);
 
   MultiLayer* plot1D(const QMultiMap<QString,std::set<int> >& toPlot, bool spectrumPlot,
                      MantidQt::DistributionFlag distr = MantidQt::DistributionDefault,
                      bool errs=false,
-                     MultiLayer* plotWindow = NULL, bool clearWindow = false);
+                     MultiLayer* plotWindow = NULL, bool clearWindow = false, bool waterfallPlot = false);
   
     /// Draw a color fill plot for each of the listed workspaces
     void drawColorFillPlots(const QStringList & wsNames, Graph::CurveType curveType = Graph::ColorMap);
@@ -444,7 +444,7 @@ signals:
     void importNumSeriesLog(const QString &wsName, const QString &logname, int filter);
 
     // Clear all Mantid related memory
-    void clearAllMemory();
+    void clearAllMemory(const bool prompt = true);
     void releaseFreeMemory();
     // Ticket #672
     void saveNexusWorkspace();
@@ -563,7 +563,6 @@ private:
 
   // Stores dependent mdi windows. If the 'key' window closes, all 'value' ones must be closed as well.
   std::multimap<MdiSubWindow*,MdiSubWindow*> m_mdiDependency;
-
   QMdiSubWindow *m_vatesSubWindow; ///< Holder for the Vates interface sub-window
 
   //prevents some repeated code realtating to log names
diff --git a/Code/Mantid/MantidPlot/src/Mantid/MantidWSIndexDialog.cpp b/Code/Mantid/MantidPlot/src/Mantid/MantidWSIndexDialog.cpp
index b077f4fed0de2277cedb90b802247356f04ac38c..0fcfda9f743565d3d71f55d8cb6c975a39faf4b4 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/MantidWSIndexDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/MantidWSIndexDialog.cpp
@@ -21,11 +21,13 @@
  * @param mui :: The MantidUI area
  * @param flags :: Window flags that are passed the the QDialog constructor
  * @param wsNames :: the names of the workspaces to be plotted
+ * @param showWaterfallOption :: If true the waterfall checkbox is created
  */
-MantidWSIndexDialog::MantidWSIndexDialog(MantidUI* mui, Qt::WFlags flags, QList<QString> wsNames) 
+MantidWSIndexDialog::MantidWSIndexDialog(MantidUI* mui, Qt::WFlags flags, QList<QString> wsNames, const bool showWaterfallOption) 
   : QDialog(mui->appWindow(), flags), 
   m_mantidUI(mui),
   m_spectra(false),
+  m_waterfall(showWaterfallOption),
   m_wsNames(wsNames),
   m_wsIndexIntervals(),
   m_spectraIdIntervals(),
@@ -44,6 +46,14 @@ MantidWSIndexDialog::MantidWSIndexDialog(MantidUI* mui, Qt::WFlags flags, QList<
   init();
 }
 
+MantidWSIndexDialog::UserInput MantidWSIndexDialog::getSelections() const
+{
+  UserInput options;
+  options.plots = getPlots();
+  options.waterfall = waterfallPlotRequested();
+  return options;
+}
+
 QMultiMap<QString,std::set<int> > MantidWSIndexDialog::getPlots() const
 {
   // Map of workspace names to set of indices to be plotted.
@@ -88,6 +98,11 @@ QMultiMap<QString,std::set<int> > MantidWSIndexDialog::getPlots() const
   return plots;
 }
 
+bool MantidWSIndexDialog::waterfallPlotRequested() const
+{
+  return m_waterfallOpt->isChecked();
+}
+
 //----------------------------------
 // MantidWSIndexDialog private slots
 //----------------------------------
@@ -149,6 +164,7 @@ void MantidWSIndexDialog::init()
   setWindowTitle(tr("MantidPlot"));
   initSpectraBox();
   initWorkspaceBox();
+  initOptionsBoxes();
   initButtons();
   setLayout(m_outer);
 }
@@ -185,6 +201,18 @@ void MantidWSIndexDialog::initSpectraBox()
   connect(m_spectraField->lineEdit(), SIGNAL(textEdited(const QString &)), this, SLOT(editedSpectraField()));
 }
 
+void MantidWSIndexDialog::initOptionsBoxes()
+{
+  m_optionsBox = new QHBoxLayout;
+  m_waterfallOpt = new QCheckBox("Waterfall Plot");
+  if(m_waterfall)
+    m_optionsBox->add(m_waterfallOpt);
+  else
+    m_waterfallOpt->setChecked(true);
+
+  m_outer->addItem(m_optionsBox);
+}
+
 void MantidWSIndexDialog::initButtons()
 {
   m_buttonBox = new QHBoxLayout;
diff --git a/Code/Mantid/MantidPlot/src/Mantid/MantidWSIndexDialog.h b/Code/Mantid/MantidPlot/src/Mantid/MantidWSIndexDialog.h
index b4638c6e9c4755729ed2c3942e290c4a71481174..9ab943480a4c62ab043204c34ca2cfc8ec174665 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/MantidWSIndexDialog.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/MantidWSIndexDialog.h
@@ -4,6 +4,7 @@
 //----------------------------------
 // Includes
 //----------------------------------
+#include <QCheckBox>
 #include <QDialog>
 #include <QString>
 #include <QList>
@@ -188,7 +189,8 @@ private:
 class MantidWSIndexDialog : public QDialog
 {
   Q_OBJECT
-/** Auxiliar class to wrap the QLine allowing to have a warn to the user for
+
+  /** Auxiliar class to wrap the QLine allowing to have a warn to the user for
  *  invalid inputs. 
 */
 class QLineEditWithErrorMark : public QWidget{
@@ -207,13 +209,26 @@ private:
 };
 
 public:
-  /// Constructor - same parameters as one of the parent constructors, along with a 
+  /**
+    * POD structure to hold all user-selected input
+    */
+  struct UserInput {
+    QMultiMap<QString,std::set<int> > plots;
+    bool waterfall;
+  };
+
+/// Constructor - same parameters as one of the parent constructors, along with a 
   /// list of the names of workspaces to be plotted.
-  MantidWSIndexDialog(MantidUI* parent, Qt::WFlags flags, QList<QString> wsNames);
+  MantidWSIndexDialog(MantidUI* parent, Qt::WFlags flags, QList<QString> wsNames,
+                      const bool showWaterfallOption = false);
 
+  /// Returns a structure holding all of the selected options
+  UserInput getSelections() const;
   /// Returns the QMultiMap that contains all the workspaces that are to be plotted, 
   /// mapped to the set of workspace indices.
   QMultiMap<QString,std::set<int> > getPlots() const;
+  /// Returns whether the waterfall option has been selected
+  bool waterfallPlotRequested() const;
 
 private slots:
   /// Called when the OK button is pressed.
@@ -232,6 +247,8 @@ private:
   void initWorkspaceBox();
   /// Initializes the layout of the spectra ID section of the dialog
   void initSpectraBox();
+  /// Initialize the layout of the options check boxes
+  void initOptionsBoxes();
   /// Initializes the layout of the buttons
   void initButtons();
 
@@ -253,13 +270,18 @@ private:
   /// Do we allow the user to ask for a range of spectra IDs or not?
   bool m_spectra;
 
+  /// Do we allow the display of the waterfall option
+  bool m_waterfall;
+  
   /// Pointers to the obligatory Qt objects:
   QLabel *m_wsMessage, *m_spectraMessage, *m_orMessage;
   QLineEditWithErrorMark *m_wsField, *m_spectraField;
   QVBoxLayout *m_outer, *m_wsBox, *m_spectraBox; 
-  QHBoxLayout *m_buttonBox;
+  QHBoxLayout *m_optionsBox, *m_buttonBox;
+  QCheckBox *m_waterfallOpt;
   QPushButton *m_okButton, *m_cancelButton, *m_plotAllButton;
 
+  
   /// A list of names of workspaces which are to be plotted.
   QList<QString> m_wsNames;
   /// IntervalLists for the range of indices/IDs AVAILABLE to the user.
diff --git a/Code/Mantid/MantidPlot/src/Mantid/SetUpParaview.cpp b/Code/Mantid/MantidPlot/src/Mantid/SetUpParaview.cpp
deleted file mode 100644
index 71755d815cf8dfee0c5aa8d71f7e52e635ebd593..0000000000000000000000000000000000000000
--- a/Code/Mantid/MantidPlot/src/Mantid/SetUpParaview.cpp
+++ /dev/null
@@ -1,210 +0,0 @@
-#include "SetUpParaview.h"
-#include "MantidKernel/ConfigService.h"
-#include "MantidKernel/ParaViewVersion.h"
-#include "MantidQtAPI/ManageUserDirectories.h"
-#include "MantidKernel/ConfigService.h"
-#include <boost/regex.hpp>
-#include <QFileDialog>
-#include <QProcess>
-#include <QPalette>
-#include <QDirIterator>
-#include <QDesktopServices>
-#include <QMessageBox>
-#include <iostream> 
-
-
-using Mantid::Kernel::ConfigService;
-using Mantid::Kernel::ConfigServiceImpl;
-
-/**
-Is Paraview at this location.
-@return TRUE if determined to be present.
-*/
-bool isParaviewHere(const QString& location)
-{
-  using boost::regex;
-  using boost::regex_search;
-
-  bool found = false;
-  if(!location.isEmpty())
-  {
-    QDirIterator it(location, QDirIterator::NoIteratorFlags);
-    while (it.hasNext())
-    {
-      it.next();
-      QString file =it.fileName();
-      regex expression("^(paraview.exe)", boost::regex::icase);
-      if(regex_search(file.toStdString(), expression) && it.fileInfo().isFile())
-      {
-        found = true;
-        break;
-      }
-    }
-  }
-  return found;
-}
-
-/// Constructor
-SetUpParaview::SetUpParaview(StartUpFrom from, QWidget *parent) : QDialog(parent), m_from(from)
-{
-  m_uiForm.setupUi(this);
-
-  initLayout();
-
-  QString versionRevision = QString::fromStdString(Mantid::Kernel::ParaViewVersion::targetVersion());
-  if (!versionRevision.contains("3.98"))
-  {
-	// For ParaView 3.10, minor version number is not available
-	versionRevision.append(".1");
-  }
-  const QString predictedLocation = QString("C:/Program Files (x86)/ParaView %1/bin").arg(versionRevision);
-  const QString hintText = QString("Hint: the usual install location for ParaView is: %1").arg(predictedLocation);
-  m_uiForm.lblHint->setText(hintText);
-
-  m_candidateLocation = QString(ConfigService::Instance().getString("paraview.path").c_str());
-  //Do our best to figure out the location based on where paraview normally sits.
-  if(m_candidateLocation.isEmpty())
-  {
-    if(isParaviewHere(predictedLocation))
-    {
-      acceptPotentialLocation(predictedLocation);
-    }
-  }
-  else
-  {
-    if(isParaviewHere(m_candidateLocation))
-    {
-      acceptPotentialLocation(m_candidateLocation);
-    }
-  }
-}
-
-/// Destructor
-SetUpParaview::~SetUpParaview()
-{
-}
-
-/// Initialise the layout of the form
-void SetUpParaview::initLayout()
-{
-  clearStatus();
-
-  //Until the user has provided a location, they will not be able to set the result.
-  m_uiForm.btn_set->setEnabled(false);
-  
-  QPalette plt;
-  plt.setColor(QPalette::WindowText, Qt::red);
-  m_uiForm.lbl_message->setPalette(plt);
-
-  connect(m_uiForm.btn_choose_location, SIGNAL(clicked()), this, SLOT(onChoose()));
-  connect(m_uiForm.btn_set, SIGNAL(clicked()), this, SLOT(onSet()));
-  connect(m_uiForm.btn_cancel, SIGNAL(clicked()), this, SLOT(reject()));
-  connect(m_uiForm.btn_help, SIGNAL(clicked()), this, SLOT(onHelp()));
-  connect(m_uiForm.btn_ignore_paraview, SIGNAL(clicked()), this, SLOT(onIgnoreHenceforth()));
-}
-
-///On help requested.
-void SetUpParaview::onHelp()
-{
-  QDesktopServices::openUrl(QUrl(QString("http://www.mantidproject.org/") +
-				   "Paraview_setup"));
-}
-
-/// Set the result.
-void SetUpParaview::onSet()
-{
-  ConfigServiceImpl& config = ConfigService::Instance();
-  config.setParaviewLibraryPath(m_candidateLocation.toStdString());
-  config.setString("paraview.path", m_candidateLocation.toStdString());
-  config.setString("paraview.ignore", "0"); //In case paraview is currently being ignored.
-  std::string filename = config.getUserFilename();
-  //Save the result so that on the next start up we don't have to bother the user.
-  config.saveConfig(filename);
-
-  //Additional message for mantid menu setup.
-  if(m_from == SetUpParaview::MantidMenu)
-  {
-    QMessageBox msgBox;
-    msgBox.setText("You will need to restart MantidPlot to pick-up these changes.");
-    msgBox.exec();
-  }
-
-  this->close();
-}
-
-/// Event handler for the ignore paraview henceforth event.
-void SetUpParaview::onIgnoreHenceforth()
-{
-  ConfigServiceImpl& config = ConfigService::Instance();
-  config.setString("paraview.ignore", QString::number(true).toStdString());
-  std::string filename = config.getUserFilename();
-  //Save the result so that on the next start up we don't have to bother the user.
-  config.saveConfig(filename);
-  this->close();
-}
-
-/*
-stash location on dialog object and display in ui text box.
-@param location: location to stash before applying.
-*/
-void SetUpParaview::acceptPotentialLocation(const QString& location)
-{
-  m_candidateLocation = location;
-  m_uiForm.txt_location->setText(location);
-  m_uiForm.btn_set->setEnabled(true);
-}
-
-/*
-Handle the rejection of a potential location
-@param location: The rejected location
-*/
-void SetUpParaview::rejectPotentialLocation(const QString& location)
-{
-  m_candidateLocation = "";
-  m_uiForm.txt_location->setText(location); //show the location anyway, good to help the user fix what's wrong
-  m_uiForm.btn_set->setEnabled(false);
-  writeError("Try again. Expected paraview libaries were not found in the location given.");
-}
-
-/// Event handler for the onChoose event.
-void SetUpParaview::onChoose()
-{
-  using boost::regex;
-  using boost::regex_search;
-
-  clearStatus();
-  QString temp = QFileDialog::getExistingDirectory(this, tr("Open Directory"), "/home");
-  temp = QDir::fromNativeSeparators(temp);
-  if(isParaviewHere(temp))
-  {
-    acceptPotentialLocation(temp);
-  }
-  else
-  {
-    //Try to predict the location, since users usually do not give the full path to the bin directory
-    temp += "/bin";
-    if(isParaviewHere(temp))
-    {
-      acceptPotentialLocation(temp);
-    }
-    else
-    {
-      rejectPotentialLocation(temp);
-    }
-  }
-}
-
-/// Clear any existing status messages.
-void SetUpParaview::clearStatus()
-{
-  m_uiForm.lbl_message->clear();
-}
-
-/**
-Passes error information up to UI.
-@param error : error string.
-*/
-void SetUpParaview::writeError(const QString& error)
-{
-  m_uiForm.lbl_message->setText(error);
-}
diff --git a/Code/Mantid/MantidPlot/src/Mantid/SetUpParaview.h b/Code/Mantid/MantidPlot/src/Mantid/SetUpParaview.h
deleted file mode 100644
index af7c79aeb7b64574de2e6ed23edd8c3200c71ec7..0000000000000000000000000000000000000000
--- a/Code/Mantid/MantidPlot/src/Mantid/SetUpParaview.h
+++ /dev/null
@@ -1,38 +0,0 @@
-#ifndef MANTIDPLOT_SETUP_PARAVIEW_WINDOW
-#define MANTIDPLOT_SETUP_PARAVIEW_WINDOW
-
-#include <QDialog>
-#include "ui_SetUpParaview.h"
-
-/**
-* SetUpParaview dialog for MantidPlot.
-*
-*/
-
-
-class SetUpParaview : public QDialog
-{
-  Q_OBJECT
-public:
-  enum StartUpFrom {FirstLaunch, MantidMenu};
-  SetUpParaview(StartUpFrom from, QWidget *parent=0);
-  ~SetUpParaview();
-private:
-  void initLayout();
-  void clearStatus();
-  void writeError(const QString& error);
-  void acceptPotentialLocation(const QString& location);
-  void rejectPotentialLocation(const QString& location);
-private slots:
-  void onChoose();
-  void onSet();
-  void onHelp();
-  void onIgnoreHenceforth();
-private:
-  Ui::SetUpParaview m_uiForm;
-  QString m_candidateLocation;
-  StartUpFrom m_from;
-
-};
-
-#endif
\ No newline at end of file
diff --git a/Code/Mantid/MantidPlot/src/Mantid/SetUpParaview.ui b/Code/Mantid/MantidPlot/src/Mantid/SetUpParaview.ui
deleted file mode 100644
index f2869504ea5c8c4b0345ff9bf084bf88b58bb60c..0000000000000000000000000000000000000000
--- a/Code/Mantid/MantidPlot/src/Mantid/SetUpParaview.ui
+++ /dev/null
@@ -1,179 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>SetUpParaview</class>
- <widget class="QDialog" name="SetUpParaview">
-  <property name="geometry">
-   <rect>
-    <x>0</x>
-    <y>0</y>
-    <width>659</width>
-    <height>465</height>
-   </rect>
-  </property>
-  <property name="sizePolicy">
-   <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
-    <horstretch>0</horstretch>
-    <verstretch>0</verstretch>
-   </sizepolicy>
-  </property>
-  <property name="windowTitle">
-   <string>Setup Paraview</string>
-  </property>
-  <layout class="QVBoxLayout" name="verticalLayout">
-   <item>
-    <layout class="QHBoxLayout" name="layoutInstructions">
-     <item>
-      <widget class="QLabel" name="lbImageLogo">
-       <property name="enabled">
-        <bool>true</bool>
-       </property>
-       <property name="sizePolicy">
-        <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
-         <horstretch>0</horstretch>
-         <verstretch>0</verstretch>
-        </sizepolicy>
-       </property>
-       <property name="maximumSize">
-        <size>
-         <width>120</width>
-         <height>100</height>
-        </size>
-       </property>
-       <property name="text">
-        <string/>
-       </property>
-       <property name="pixmap">
-        <pixmap resource="../../../Images/images.qrc">:/pvIcon.png</pixmap>
-       </property>
-       <property name="scaledContents">
-        <bool>false</bool>
-       </property>
-       <property name="alignment">
-        <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop</set>
-       </property>
-      </widget>
-     </item>
-    </layout>
-   </item>
-   <item>
-    <widget class="QLabel" name="lbl_instructions">
-     <property name="text">
-      <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;span style=&quot; font-size:x-large; font-weight:600;&quot;&gt;Your Mantid installation is nearly ready to use with 3D visualisation&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;span style=&quot; font-size:large; font-weight:600;&quot;&gt;Not interested?&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;If you don't want 3D visualisation at the present time, you may click KEEP IGNORING&lt;/span&gt;.You can enable it later via the help menu.&lt;/p&gt;&lt;p&gt;&lt;span style=&quot; font-size:large; font-weight:600;&quot;&gt;Interested?&lt;/span&gt;&lt;/p&gt;&lt;ol style=&quot;margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; -qt-list-indent: 1;&quot;&gt;&lt;li style=&quot; margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Prerequisite: You must install ParaView from &lt;a href=&quot;http://download.mantidproject.org&quot;&gt;&lt;span style=&quot; text-decoration: underline; color:#0000ff;&quot;&gt;here&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;&lt;li style=&quot; margin-top:0px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;The install location of ParaView must be set in Mantid ...&lt;/li&gt;&lt;/ol&gt;&lt;/body&gt;&lt;/html&gt;</string>
-     </property>
-     <property name="wordWrap">
-      <bool>true</bool>
-     </property>
-     <property name="openExternalLinks">
-      <bool>true</bool>
-     </property>
-    </widget>
-   </item>
-   <item>
-    <widget class="QLabel" name="lblHint">
-     <property name="text">
-      <string/>
-     </property>
-    </widget>
-   </item>
-   <item>
-    <layout class="QHBoxLayout" name="layoutChoose">
-     <item>
-      <widget class="QPushButton" name="btn_choose_location">
-       <property name="text">
-        <string>Choose Location</string>
-       </property>
-      </widget>
-     </item>
-     <item>
-      <widget class="QTextBrowser" name="txt_location">
-       <property name="enabled">
-        <bool>false</bool>
-       </property>
-       <property name="sizePolicy">
-        <sizepolicy hsizetype="Expanding" vsizetype="Maximum">
-         <horstretch>0</horstretch>
-         <verstretch>0</verstretch>
-        </sizepolicy>
-       </property>
-       <property name="maximumSize">
-        <size>
-         <width>16777215</width>
-         <height>20</height>
-        </size>
-       </property>
-      </widget>
-     </item>
-    </layout>
-   </item>
-   <item>
-    <widget class="QLabel" name="lbl_message">
-     <property name="text">
-      <string/>
-     </property>
-    </widget>
-   </item>
-   <item>
-    <layout class="QHBoxLayout" name="layoutCommands">
-     <item>
-      <widget class="QPushButton" name="btn_help">
-       <property name="toolTip">
-        <string>Help</string>
-       </property>
-       <property name="text">
-        <string>?</string>
-       </property>
-      </widget>
-     </item>
-     <item>
-      <spacer name="horizontalSpacer">
-       <property name="orientation">
-        <enum>Qt::Horizontal</enum>
-       </property>
-       <property name="sizeHint" stdset="0">
-        <size>
-         <width>40</width>
-         <height>20</height>
-        </size>
-       </property>
-      </spacer>
-     </item>
-     <item>
-      <widget class="QPushButton" name="btn_cancel">
-       <property name="text">
-        <string>ASK ME NEXT TIME</string>
-       </property>
-      </widget>
-     </item>
-     <item>
-      <widget class="QPushButton" name="btn_ignore_paraview">
-       <property name="text">
-        <string>KEEP IGNORING</string>
-       </property>
-      </widget>
-     </item>
-     <item>
-      <widget class="QPushButton" name="btn_set">
-       <property name="text">
-        <string>SET</string>
-       </property>
-      </widget>
-     </item>
-    </layout>
-   </item>
-  </layout>
- </widget>
- <resources>
-  <include location="../../../Images/images.qrc"/>
-  <include location="../../../Images/images.qrc"/>
-  <include location="../../../Images/images.qrc"/>
-  <include location="../../../Images/images.qrc"/>
-  <include location="../../../Images/images.qrc"/>
-  <include location="../../../Images/images.qrc"/>
-  <include location="../../../Images/images.qrc"/>
-  <include location="../../../Images/images.qrc"/>
-  <include location="../../../Images/images.qrc"/>
-  <include location="../../../Images/images.qrc"/>
-  <include location="../../../Images/images.qrc"/>
- </resources>
- <connections/>
-</ui>
diff --git a/Code/Mantid/MantidPlot/src/MultiLayer.cpp b/Code/Mantid/MantidPlot/src/MultiLayer.cpp
index 74d28299e7d5c187d5ef71b0ffc5821c45b9e8d3..36bf692670f4f0f8e10b7bc219282d995f149a17 100644
--- a/Code/Mantid/MantidPlot/src/MultiLayer.cpp
+++ b/Code/Mantid/MantidPlot/src/MultiLayer.cpp
@@ -67,6 +67,7 @@
 
 #include <gsl/gsl_vector.h>
 #include "Mantid/MantidMDCurveDialog.h"
+#include "Mantid/MantidWSIndexDialog.h"
 #include "MantidQtSliceViewer/LinePlotOptions.h"
 
 #include "TSVSerialiser.h"
@@ -100,7 +101,7 @@ void LayerButton::mouseDoubleClickEvent ( QMouseEvent * )
 	emit showCurvesDialog();
 }
 
-MultiLayer::MultiLayer(ApplicationWindow* parent, int layers, int rows, int cols, 
+MultiLayer::MultiLayer(ApplicationWindow* parent, int layers, int rows, int cols,
                        const QString& label, const char* name, Qt::WFlags f)
                          : MdiSubWindow(parent, label, name, f),
                          active_graph(NULL),
@@ -191,7 +192,7 @@ void MultiLayer::insertCurve(MultiLayer* ml, int i)
   if( ml== this ) return;
   Graph *current = activeGraph();
   if( !current ) return;
-  
+
   current->insertCurve(ml->activeGraph(), i);
   current->updatePlot();
 }
@@ -213,10 +214,10 @@ LayerButton* MultiLayer::addLayerButton()
 Graph* MultiLayer::addLayer(int x, int y, int width, int height)
 {
 	addLayerButton();
-	if (!width && !height){		
-		width =	canvas->width() - left_margin - right_margin - (d_cols - 1)*colsSpace; 
+	if (!width && !height){
+		width =	canvas->width() - left_margin - right_margin - (d_cols - 1)*colsSpace;
 		height = canvas->height() - top_margin - left_margin - (d_rows - 1)*rowsSpace;
-		
+
 		int layers = graphsList.size();
 		x = left_margin + (layers % d_cols)*(width + colsSpace);
 	    y = top_margin + (layers / d_cols)*(height + rowsSpace);
@@ -642,9 +643,9 @@ void MultiLayer::arrangeLayers(bool fit, bool userSize)
 
 		this->showNormal();
 		QSize size = canvas->childrenRect().size();
-		this->resize(canvas->x() + size.width() + left_margin + 2*right_margin, 
+		this->resize(canvas->x() + size.width() + left_margin + 2*right_margin,
 					canvas->y() + size.height() + bottom_margin + 2*LayerButton::btnSize());
-		
+
 		foreach (Graph *gr, graphsList)
 			gr->setIgnoreResizeEvents(ignoreResize);
 	}
@@ -917,7 +918,7 @@ void MultiLayer::printAllLayers(QPainter *painter)
 		}
 	}
 	else
-	{	
+	{
 	   	int x_margin = (pageRect.width() - canvasRect.width())/2;
 	   	int y_margin = (pageRect.height() - canvasRect.height())/2;
 		if (d_print_cropmarks)
@@ -925,7 +926,7 @@ void MultiLayer::printAllLayers(QPainter *painter)
 		int margin = (int)((1/2.54)*printer->logicalDpiY()); // 1 cm margins
 		double scaleFactorX=(double)(paperRect.width()-4*margin)/(double)canvasRect.width();
 		double scaleFactorY=(double)(paperRect.height()-4*margin)/(double)canvasRect.height();
-		
+
 		for (int i=0; i<(int)graphsList.count(); i++)
 		{
             Graph *gr = static_cast<Graph *>(graphsList.at(i));
@@ -937,7 +938,7 @@ void MultiLayer::printAllLayers(QPainter *painter)
 			int width=int(size.width()*scaleFactorX);
 			int height=int(size.height()*scaleFactorY);
 			myPlot->print(painter, QRect(pos, QSize(width,height)));
-		
+
 		}
 	}
 	if (d_print_cropmarks)
@@ -1292,10 +1293,10 @@ void MultiLayer::dragEnterEvent( QDragEnterEvent * event )
 void MultiLayer::dropEvent( QDropEvent * event )
 {
   MantidTreeWidget * tree = dynamic_cast<MantidTreeWidget*>(event->source());
-  
+
   Graph *g = this->activeGraph();
   if (!g) return; // (shouldn't happen either)
-  
+
   if(g->curves() > 0)
   {
     //Do some capability queries on the base curve.
@@ -1383,10 +1384,12 @@ void MultiLayer::dropOntoMatrixCurve(Graph *g, MantidMatrixCurve* originalCurve,
     // Else we'll just have no error bars.
     errorBars = false;
   }
-  
-  if ( tree == NULL ) return; // (shouldn't happen)
-  QMultiMap<QString,std::set<int> > toPlot = tree->chooseSpectrumFromSelected();
 
+  if ( tree == NULL ) return; // (shouldn't happen)
+  bool waterfallOpt = false;
+  const auto userInput = tree->chooseSpectrumFromSelected(waterfallOpt);
+  const auto toPlot = userInput.plots;
+  
   // Iterate through the selected workspaces adding a set of curves from each
   for(QMultiMap<QString,std::set<int> >::const_iterator it=toPlot.begin();it!=toPlot.end();++it)
   {
@@ -1465,6 +1468,47 @@ void MultiLayer::maybeNeedToClose()
   }
 }
 
+void MultiLayer::toggleWaterfall(bool on)
+{
+  if(on) convertToWaterfall();
+  else convertFromWaterfall();
+}
+
+/**
+ * Assume we have a standard 1D plot and convert it to a waterfall layout
+ */
+void MultiLayer::convertToWaterfall()
+{
+  Graph *active = activeGraph();
+  if(!active || active->isWaterfallPlot()) return;
+
+  hide();
+  active->setWaterfallOffset(10,20);
+  setWaterfallLayout(true);
+  // Next two lines replace the legend so that it works on reversing the curve order
+  active->removeLegend();
+  active->newLegend();
+  show();
+}
+
+/**
+ * Assume we have a waterfall 1D plot and convert it to a standard overlayed layout
+ */
+void MultiLayer::convertFromWaterfall()
+{
+  Graph *active = activeGraph();
+  if(!active || !active->isWaterfallPlot()) return;
+
+  hide();
+  const bool updateOffset(true);
+  active->setWaterfallOffset(0, 0, updateOffset);
+  setWaterfallLayout(false);
+  // Next two lines replace the legend
+  active->removeLegend();
+  active->newLegend();
+  show();
+}
+
 void MultiLayer::setWaterfallLayout(bool on)
 {
   if (graphsList.isEmpty())
@@ -1476,13 +1520,7 @@ void MultiLayer::setWaterfallLayout(bool on)
     createWaterfallBox();
     updateWaterfalls();
   } else {
-    for (int i = 0; i < waterfallBox->count(); i++){
-      QLayoutItem *item = waterfallBox->itemAt(i);
-      if (item){
-        waterfallBox->removeItem(item);
-        delete item;
-      }
-    }
+    removeWaterfallBox();
   }
 }
 
@@ -1504,6 +1542,17 @@ void MultiLayer::createWaterfallBox()
   waterfallBox->addWidget(btn);
 }
 
+void MultiLayer::removeWaterfallBox()
+{
+  if (waterfallBox->count() == 0)
+    return;
+
+  QLayoutItem *child;
+  while ((child = waterfallBox->takeAt(0)) != 0) {
+    delete child->widget();
+  }
+}
+
 void MultiLayer::updateWaterfalls()
 {
   if (!d_is_waterfall_plot || graphsList.isEmpty())
@@ -1579,7 +1628,7 @@ void MultiLayer::showWaterfallFillDialog()
   if (active_graph->curvesList().isEmpty())
     return;
 
-  new WaterfallFillDialog(this, active_graph);  
+  new WaterfallFillDialog(this, active_graph);
 }
 
 
@@ -1591,30 +1640,30 @@ void MultiLayer::setWaterfallFillColor(const QColor& c)
 }
 
 
-WaterfallFillDialog::WaterfallFillDialog(MultiLayer *parent, Graph *active_graph) 
+WaterfallFillDialog::WaterfallFillDialog(MultiLayer *parent, Graph *active_graph)
 {
   this->setParent(parent);
   this->m_active_graph = active_graph;
   QDialog *waterfallFillDialog = new QDialog(this);
   waterfallFillDialog->setWindowTitle(tr("Fill Curves"));
-  
+
   QGroupBox *enableFillGroup = new QGroupBox(tr("Enable Fill"), waterfallFillDialog);
   enableFillGroup->setCheckable(true);
-  
-  QGridLayout *enableFillLayout =  new QGridLayout(enableFillGroup);  
+
+  QGridLayout *enableFillLayout =  new QGridLayout(enableFillGroup);
 
   // use line colour
   QRadioButton *rLineC = new QRadioButton("Use Line Colour", enableFillGroup);
   this->m_lineRadioButton = rLineC;
   enableFillLayout->addWidget(rLineC,0,0);
-  
+
   // use solid colour
   QRadioButton *rSolidC = new QRadioButton("Use Solid Colour", enableFillGroup);
   this->m_solidRadioButton = rSolidC;
   enableFillLayout->addWidget(rSolidC, 1,0);
 
-  QGroupBox *colourModeGroup = new QGroupBox( tr("Fill with Colour"), enableFillGroup);  
-  
+  QGroupBox *colourModeGroup = new QGroupBox( tr("Fill with Colour"), enableFillGroup);
+
   QGridLayout *hl1 = new QGridLayout(colourModeGroup);
   hl1->addWidget(new QLabel(tr("Colour")), 0, 0);
   ColorButton *fillColourBox = new ColorButton(colourModeGroup);
@@ -1624,26 +1673,26 @@ WaterfallFillDialog::WaterfallFillDialog(MultiLayer *parent, Graph *active_graph
   enableFillLayout->addWidget(colourModeGroup,2,0);
 
   QCheckBox *sideLinesBox = new QCheckBox(tr("Side Lines"), enableFillGroup);
-  enableFillLayout->addWidget(sideLinesBox, 3, 0); 
+  enableFillLayout->addWidget(sideLinesBox, 3, 0);
 
   QBrush brush = active_graph->curve(0)->brush();
 
   // check if all curve colours are the same (= solid fill)
   bool same = brush.style() != Qt::NoBrush; // check isn't first run against graph
-  
+
   if(same)
   {
     int n = active_graph->curvesList().size();
     for (int i = 0; i < n; i++)
     {
-      same = same && (active_graph->curve(i)->brush().color() == brush.color());    
+      same = same && (active_graph->curve(i)->brush().color() == brush.color());
     }
   }
   // set which is toggled
   enableFillGroup->setChecked(brush.style() != Qt::NoBrush);
 
   if(same)
-  {   
+  {
     rSolidC->toggle();
     if(enableFillGroup->isChecked())
       fillColourBox->setColor(brush.color());
@@ -1652,22 +1701,22 @@ WaterfallFillDialog::WaterfallFillDialog(MultiLayer *parent, Graph *active_graph
   {
     rLineC->toggle();
     if(enableFillGroup->isChecked())
-      active_graph->updateWaterfallFill(true);  
+      active_graph->updateWaterfallFill(true);
   }
 
   // If sidelines previously enabled, check it.
   PlotCurve *c = dynamic_cast<PlotCurve*>(active_graph->curve(0));
-  sideLinesBox->setChecked(c->sideLinesEnabled());   
-  
-  colourModeGroup->setEnabled(rSolidC->isChecked() && enableFillGroup->isChecked());  
-  
-  connect(enableFillGroup, SIGNAL(toggled(bool)), this, SLOT(enableFill(bool))); 
+  sideLinesBox->setChecked(c->sideLinesEnabled());
+
+  colourModeGroup->setEnabled(rSolidC->isChecked() && enableFillGroup->isChecked());
+
+  connect(enableFillGroup, SIGNAL(toggled(bool)), this, SLOT(enableFill(bool)));
   connect(fillColourBox, SIGNAL(colorChanged(const QColor&)), active_graph, SLOT(setWaterfallFillColor(const QColor&)));
-  connect(sideLinesBox, SIGNAL(toggled(bool)), active_graph, SLOT(setWaterfallSideLines(bool)));  
-  connect(rSolidC, SIGNAL(toggled(bool)), colourModeGroup, SLOT(setEnabled(bool)));  
-  connect(rSolidC, SIGNAL(toggled(bool)), this, SLOT(setFillMode())); 
-  connect(rLineC, SIGNAL(toggled(bool)), this, SLOT(setFillMode())); 
-  
+  connect(sideLinesBox, SIGNAL(toggled(bool)), active_graph, SLOT(setWaterfallSideLines(bool)));
+  connect(rSolidC, SIGNAL(toggled(bool)), colourModeGroup, SLOT(setEnabled(bool)));
+  connect(rSolidC, SIGNAL(toggled(bool)), this, SLOT(setFillMode()));
+  connect(rLineC, SIGNAL(toggled(bool)), this, SLOT(setFillMode()));
+
   QPushButton *closeBtn = new QPushButton(tr("&Close"),waterfallFillDialog);
   connect(closeBtn, SIGNAL(clicked()), waterfallFillDialog, SLOT(reject()));
 
@@ -1690,19 +1739,19 @@ void WaterfallFillDialog::enableFill(bool b)
   else
   {
     m_active_graph->curve(0)->setBrush(Qt::BrushStyle::NoBrush);
-    m_active_graph->updateWaterfallFill(false);     
+    m_active_graph->updateWaterfallFill(false);
   }
 }
 
 void WaterfallFillDialog::setFillMode()
 {
-  if( m_solidRadioButton->isChecked() ) 
-  {                  
+  if( m_solidRadioButton->isChecked() )
+  {
     m_active_graph->setWaterfallFillColor(this->m_colourBox->color());
-  }    
+  }
   else if( m_lineRadioButton->isChecked() )
-  {       
-    m_active_graph->updateWaterfallFill(true); 
+  {
+    m_active_graph->updateWaterfallFill(true);
   }
 }
 
diff --git a/Code/Mantid/MantidPlot/src/MultiLayer.h b/Code/Mantid/MantidPlot/src/MultiLayer.h
index cba7586a9b750b181a036cff1dfaf046295f8308..a36fc0502835f588625b8d9384bfaf8e06895e15 100644
--- a/Code/Mantid/MantidPlot/src/MultiLayer.h
+++ b/Code/Mantid/MantidPlot/src/MultiLayer.h
@@ -172,6 +172,9 @@ public slots:
 
   //! \name Waterfall Plots
   //@{
+  void toggleWaterfall(bool on);
+  void convertToWaterfall();
+  void convertFromWaterfall();
   void showWaterfallOffsetDialog();
   void reverseWaterfallOrder();
   void showWaterfallFillDialog();
@@ -227,6 +230,7 @@ private:
   void removeLayerSelectionFrame();
 
   void createWaterfallBox();
+  void removeWaterfallBox();
 
 	Graph* active_graph;
 	//! Used for resizing of layers.
@@ -276,7 +280,7 @@ class WaterfallFillDialog : QDialog
 public:
     WaterfallFillDialog(MultiLayer *parent, Graph *active_graph);
 
-public slots:    
+public slots:
   void setFillMode();
   void enableFill(bool b);
 
diff --git a/Code/Mantid/MantidPlot/src/PlotDialog.cpp b/Code/Mantid/MantidPlot/src/PlotDialog.cpp
index f2519bdc5117641ef344ea6fede0b6f21bbea9ec..1a21ac53825c551856a8309c6c80dce3b2e283c1 100644
--- a/Code/Mantid/MantidPlot/src/PlotDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/PlotDialog.cpp
@@ -1154,11 +1154,14 @@ void PlotDialog::showColorMapEditor(bool)
   if (grayScaleBox->isChecked() || defaultScaleBox->isChecked())
   {
     mSelectColormap->hide();
+    boxSetCMapAsDefault->hide();
   }
   else
   {
+    boxSetCMapAsDefault->show();
     mSelectColormap->show();
   }
+  setColorMapName();
 }
 
 void PlotDialog::initSpectrogramPage()
@@ -1182,13 +1185,23 @@ void PlotDialog::initSpectrogramPage()
   connect(customScaleBox, SIGNAL(toggled(bool)), this, SLOT(showColorMapEditor(bool)));
   vl->addWidget(customScaleBox);
 
-  QHBoxLayout *hl = new QHBoxLayout(imageGroupBox);
-  hl->addLayout(vl);
+  QVBoxLayout *vlCM = new QVBoxLayout();
+
+  mLabelCurrentColormap = new QLabel(tr("Map: "));
+  vlCM->addWidget(mLabelCurrentColormap);
+
+  boxSetCMapAsDefault = new QCheckBox(tr("Set as Default"));
+  vlCM->addWidget(boxSetCMapAsDefault);
+  vlCM->addStretch();
 
   mSelectColormap = new QPushButton(tr("Select ColorMap"));
-  hl->addWidget(mSelectColormap);
+  vlCM->addWidget(mSelectColormap);
   connect(mSelectColormap, SIGNAL(clicked()), this, SLOT(changeColormap()));
 
+  QHBoxLayout *hl = new QHBoxLayout(imageGroupBox);
+  hl->addLayout(vl);
+  hl->addLayout(vlCM);
+
   axisScaleBox = new QGroupBox(tr("Color Bar Scale"));
   axisScaleBox->setCheckable(true);
 
@@ -1211,9 +1224,45 @@ void PlotDialog::initSpectrogramPage()
   vl2->addWidget(axisScaleBox);
   vl2->addStretch();
 
+  setColorMapName();
+
   privateTabWidget->insertTab(spectrogramPage, tr("Contour") + " / " + tr("Image"));
 }
 
+void PlotDialog::setColorMapName()
+{
+  if (grayScaleBox->isChecked()) {
+    mLabelCurrentColormap->setText("Map: Greyscale");
+  } 
+  else {
+    Spectrogram *sp = NULL;
+    QTreeWidgetItem *it = listBox->currentItem();
+    if (it) {
+      CurveTreeItem *item = dynamic_cast<CurveTreeItem*>(it);
+      if (item) {
+        QwtPlotItem *plotItem = dynamic_cast<QwtPlotItem *>(item->plotItem());
+        if (plotItem) {
+          sp = dynamic_cast<Spectrogram*>(plotItem);
+        }
+      }
+    }
+    if (sp) {
+      if (defaultScaleBox->isChecked()) {
+        mLabelCurrentColormap->setText("Map: " + sp->getDefaultColorMap().getName());
+      } 
+      else if (mCurrentColorMap.isEmpty()) {
+        mLabelCurrentColormap->setText("Map: " + sp->getColorMap().getName());
+      } 
+      else
+      {
+          //set the name of the color map to the filename
+        QFileInfo fileinfo(mCurrentColorMap);
+        mLabelCurrentColormap->setText("Map: " + fileinfo.baseName());
+      }
+    }
+  }
+}
+
 void PlotDialog::showBoxSymbols(bool show)
 {
   boxPercFillColor->setEnabled(show);
@@ -1716,6 +1765,7 @@ void PlotDialog::insertTabs(int plot_type)
       || plot_type == Graph::ColorMapContour)
   {
     privateTabWidget->addTab(spectrogramPage, tr("Colors"));
+    setColorMapName();
     privateTabWidget->addTab(contourLinesPage, tr("Contour Lines"));
     privateTabWidget->showPage(spectrogramPage);
     privateTabWidget->addTab(labelsPage, tr("Labels"));
@@ -2397,8 +2447,10 @@ bool PlotDialog::acceptParams()
       sp->setCustomColorMap(sp->mutableColorMap());
       //sets the selected colormapfile name to spectrogram
       sp->setColorMapFileName(mCurrentColorMap);
-      //saves the settings
-      sp->saveSettings();
+      if (boxSetCMapAsDefault->isChecked()) {
+        //saves the settings as default
+        sp->saveSettings();
+      }
     }
 
     sp->showColorScale((QwtPlot::Axis) colorScaleBox->currentItem(), axisScaleBox->isChecked());
@@ -2946,6 +2998,7 @@ void PlotDialog::changeColormap(const QString &filename)
     return;
 
   mCurrentColorMap = fileselection;
+  setColorMapName();
 }
 
 void PlotDialog::showDefaultContourLinesBox(bool)
diff --git a/Code/Mantid/MantidPlot/src/PlotDialog.h b/Code/Mantid/MantidPlot/src/PlotDialog.h
index bd58dfa8dfaaf4db744a12a1a0f60e2e29ede80f..1d1ce3ecbb6e4d1d694462b754a82930f84ddb45 100644
--- a/Code/Mantid/MantidPlot/src/PlotDialog.h
+++ b/Code/Mantid/MantidPlot/src/PlotDialog.h
@@ -165,6 +165,8 @@ private:
 
   void showAllLabelControls(bool show = true);
 
+  void setColorMapName();
+
   double aspect_ratio;
 
   QFont titleFont, legendFont, axesFont, numbersFont;
@@ -179,11 +181,12 @@ private:
 
   QPushButton *btnTitle, *btnAxesLabels, *btnAxesNumbers, *btnLegend;
   ColorMapEditor *colorMapEditor;
+  QLabel *mLabelCurrentColormap;
   QPushButton* mSelectColormap;
   QString mCurrentColorMap;
   QWidget *curvePlotTypeBox, *layerPage, *layerGeometryPage, *piePage, *fontsPage, *printPage, *contourLinesPage;
   QTreeWidget* listBox;
-  QCheckBox *boxAntialiasing, *boxAll, *boxScaleLayers, *boxPrintCrops;
+  QCheckBox *boxAntialiasing, *boxAll, *boxScaleLayers, *boxPrintCrops, *boxSetCMapAsDefault;
   ColorButton *boxBorderColor, *boxBackgroundColor, *boxCanvasColor, *boxCanvasFrameColor;
   QSpinBox *boxBackgroundTransparency, *boxCanvasTransparency, *boxBorderWidth, *boxMargin, *boxCanvasFrameWidth;
   QSpinBox *boxRadius;
diff --git a/Code/Mantid/MantidPlot/src/Spectrogram.cpp b/Code/Mantid/MantidPlot/src/Spectrogram.cpp
index 413ab6d07ea9bafe861bcae1f00c011a6c7c60f4..116cc8d8e9678bd583db3ba369a58764a144fd37 100644
--- a/Code/Mantid/MantidPlot/src/Spectrogram.cpp
+++ b/Code/Mantid/MantidPlot/src/Spectrogram.cpp
@@ -423,25 +423,11 @@ void Spectrogram::setGrayScale()
 
 void Spectrogram::setDefaultColorMap()
 {
-  // option 1 use last used colour map
-  QSettings settings;
-  settings.beginGroup("Mantid/2DPlotSpectrogram");
-  //Load Colormap. If the file is invalid the default stored colour map is used
-  QString lastColormapFile = settings.value("ColormapFile", "").toString();
-  settings.endGroup();
-
-  if (lastColormapFile.size() > 0)
-  {
-      mCurrentColorMap = lastColormapFile;
-      mColorMap.loadMap(lastColormapFile);
-  }
-  else
-  {
-    //option 2 use the default colormap from MantidColorMap.
-    mColorMap.setupDefaultMap();
-  }
+  MantidColorMap map = getDefaultColorMap();
   
-  setColorMap(mColorMap);
+  mCurrentColorMap = map.getFilePath();
+  mColorMap = map;
+  setColorMap(map);
       
   color_map_policy = Default;
 
@@ -455,6 +441,22 @@ void Spectrogram::setDefaultColorMap()
 
 }
 
+
+MantidColorMap Spectrogram::getDefaultColorMap()
+{
+  
+  QSettings settings;
+  settings.beginGroup("Mantid/2DPlotSpectrogram");
+  //Load Colormap. If the file is invalid the default stored colour map is used
+  QString lastColormapFile = settings.value("ColormapFile", "").toString();
+  settings.endGroup();
+
+  //if the file is not valid you will get the default
+  MantidColorMap retColorMap(lastColormapFile,GraphOptions::Linear);
+
+  return retColorMap;
+}
+
 void Spectrogram::loadColorMap(const QString& file)
 {
   mColorMap.loadMap(file);
diff --git a/Code/Mantid/MantidPlot/src/Spectrogram.h b/Code/Mantid/MantidPlot/src/Spectrogram.h
index 893cbfa72704c7c769f2ed14c03c36336b49ac60..ca720aa917d57152afc90d2b04c5efe0b199e629 100644
--- a/Code/Mantid/MantidPlot/src/Spectrogram.h
+++ b/Code/Mantid/MantidPlot/src/Spectrogram.h
@@ -106,6 +106,7 @@ public:
 
   void setGrayScale();
   void setDefaultColorMap();
+  MantidColorMap getDefaultColorMap();
   static QwtLinearColorMap defaultColorMap();
 
   void loadColorMap(const QString& file);
diff --git a/Code/Mantid/MantidPlot/src/qti.sip b/Code/Mantid/MantidPlot/src/qti.sip
index b241c862b0d93b5ec2ed9beecfc4e98f66d41c86..a01d99b11cff9ed687de8c9efc5364c166f35aef 100644
--- a/Code/Mantid/MantidPlot/src/qti.sip
+++ b/Code/Mantid/MantidPlot/src/qti.sip
@@ -1678,7 +1678,8 @@ sipClass=sipFindClass(sipCpp->className());
 public:
   // Plotting methods
   MultiLayer* plot1D(const QList<QString>& wsnames, const QList<int>&, bool spectrumPlot, bool errs=false,
-    Graph::CurveType style = Graph::Unspecified, MultiLayer* window = NULL, bool clearWindow = false);
+    Graph::CurveType style = Graph::Unspecified, MultiLayer* window = NULL,
+                     bool clearWindow = false, bool waterfallPlot = false);
 
   MultiLayer* drawSingleColorFillPlot(const QString & name, Graph::CurveType style = Graph::ColorMap,
                                       MultiLayer* window = NULL);
diff --git a/Code/Mantid/MantidPlot/test/MantidPlot1DPlotTest.py b/Code/Mantid/MantidPlot/test/MantidPlot1DPlotTest.py
index 9f30dff27a0ba10eb14830bade7394e3f902d017..8f8ac606adddecef727912acb44ded5feae4f1ce 100644
--- a/Code/Mantid/MantidPlot/test/MantidPlot1DPlotTest.py
+++ b/Code/Mantid/MantidPlot/test/MantidPlot1DPlotTest.py
@@ -74,7 +74,7 @@ class MantidPlot1DPlotTest(unittest.TestCase):
             t.setCell(3, i, i+2)
             t.setCell(4, i, i+4)
 
-        g = plot(t, (2,3,4), Layer.Line)
+        g = pymantidplot.qtiplot.plot(t, (2,3,4), Layer.Line)
         self.g = g
         l = g.activeLayer() # Plot columns 2, 3 and 4
         for i in range(0, l.numCurves()):
diff --git a/Code/Mantid/MantidPlot/test/MantidPlotProxiesTest.py b/Code/Mantid/MantidPlot/test/MantidPlotProxiesTest.py
index b1c355684955c2ed5555e66e5536ad542573ae6c..31c614b211bae9c580d2becfe6afd402e744add3 100644
--- a/Code/Mantid/MantidPlot/test/MantidPlotProxiesTest.py
+++ b/Code/Mantid/MantidPlot/test/MantidPlotProxiesTest.py
@@ -137,7 +137,7 @@ class MantidPlotProxiesTest(unittest.TestCase):
         self.try_closing(iv, "getInstrumentView()")
 
     def test_convertToWaterfall(self):
-        g = plot(workspace("IRS26173"),(0,1,2,3,4))
+        g = pymantidplot.qtiplot.plot(workspace("IRS26173"),(0,1,2,3,4))
         convertToWaterfall(g)
         self.try_closing(g, "convertToWaterfall()")
 
diff --git a/Code/Mantid/MantidPlot/test/MantidPlotFuturePyplotGeneralTest.py b/Code/Mantid/MantidPlot/test/MantidPlotPyplotGeneralTest.py
similarity index 77%
rename from Code/Mantid/MantidPlot/test/MantidPlotFuturePyplotGeneralTest.py
rename to Code/Mantid/MantidPlot/test/MantidPlotPyplotGeneralTest.py
index ebf9ecafc84242265281fc5d6265f22d8b45144d..e18de9c6307920c4749a63c30dff9ae08f73bc0b 100644
--- a/Code/Mantid/MantidPlot/test/MantidPlotFuturePyplotGeneralTest.py
+++ b/Code/Mantid/MantidPlot/test/MantidPlotPyplotGeneralTest.py
@@ -1,4 +1,4 @@
-"""General tests for the basic interface of mantidplot.future.pyplot
+"""General tests for the basic interface of mantidplot.pyplot
 
 Tests correct creation of output lines from plots (with correct
 Figure, Graph, etc. data), and proper handling (exception) of wrong
@@ -11,9 +11,6 @@ import time
 import numpy as np
 from PyQt4 import QtGui, QtCore
 
-# Future pyplot
-from pymantidplot.future.pyplot import *
-
 # =============== Create fake workspaces to plot =======================
 X1 = np.linspace(0,10, 100)
 Y1 = 1000*(np.sin(X1)**2) + X1*10
@@ -51,7 +48,7 @@ mdSignal = np.sin(range(0,100,1))
 errInput = mdSignal/20.5
 CreateMDHistoWorkspace(Dimensionality="1", Names='x', Units='m', Extents='0,10', NumberOfBins=len(mdSignal), SignalInput=mdSignal, ErrorInput=errInput, OutputWorkspace=MDWWorkspaceName)
 
-class MantidPlotFuturePyplotGeneralTest(unittest.TestCase):
+class MantidPlotPyplotGeneralTest(unittest.TestCase):
 
     def setUp(self):
         self.g = None
@@ -89,32 +86,36 @@ class MantidPlotFuturePyplotGeneralTest(unittest.TestCase):
             self.close_win_by_graph(lines[0]._graph)        
 
     def test_plot_spectrum_ok(self):
-        lines = plot(WorkspaceName2D, [0, 1], tool='plot_spectrum')
-        self.check_output_lines(lines, 2)
-        self.close_win(lines)
-
         lines_spec = plot_spectrum(WorkspaceName2D, [0, 1])
         self.check_output_lines(lines_spec, 2)
         self.close_win(lines_spec)
 
-        if self.assertTrue(len(lines) == len(lines_spec)):
-            for i in range(0, len(lines)):
-                self.assertEqual(lines[i].get_xdata(), lines_spec[i].get_xdata())
-                self.assertEqual(lines[i].get_ydata(), lines_spec[i].get_ydata())
+        tool_names = ['plot_spectrum', 'plot_sp', 'spectrum', 'sp']
+        for tname in tool_names:
+            lines = plot(WorkspaceName2D, [0, 1], tool=tname)
+            self.check_output_lines(lines, 2)
+            self.close_win(lines)
 
-    def test_plot_bin_ok(self):
-        lines = plot(WorkspaceName2D, [0, 1, 2], tool='plot_bin')
-        self.check_output_lines(lines, 3)
-        self.close_win(lines)
+            if self.assertTrue(len(lines) == len(lines_spec)):
+                for i in range(0, len(lines)):
+                    self.assertEqual(lines[i].get_xdata(), lines_spec[i].get_xdata())
+                    self.assertEqual(lines[i].get_ydata(), lines_spec[i].get_ydata())
 
+    def test_plot_bin_ok(self):
         lines_bin = plot_bin(WorkspaceName2D, [0, 1, 2])
         self.check_output_lines(lines_bin, 3)
         self.close_win(lines_bin)
 
-        if self.assertTrue(len(lines) == len(lines_bin)):
-            for i in range(0, len(lines)):
-                self.assertEqual(lines[i].get_xdata(), lines2_bin[i].get_xdata())
-                self.assertEqual(lines[i].get_ydata(), lines2_bin[i].get_ydata())
+        tool_names = ['plot_bin', 'bin']
+        for tname in tool_names:
+            lines = plot(WorkspaceName2D, [0, 1, 2], tool=tname)
+            self.check_output_lines(lines, 3)
+            self.close_win(lines)
+
+            if self.assertTrue(len(lines) == len(lines_bin)):
+                for i in range(0, len(lines)):
+                    self.assertEqual(lines[i].get_xdata(), lines2_bin[i].get_xdata())
+                    self.assertEqual(lines[i].get_ydata(), lines2_bin[i].get_ydata())
 
     def test_lines_get_data(self):
         y = [0.2, 0.5, 0.1, 0.6]
@@ -134,18 +135,20 @@ class MantidPlotFuturePyplotGeneralTest(unittest.TestCase):
         self.assertEqual(len(lines), 1)
         self.close_win(lines)
 
-        lines = plot(MDWWorkspaceName, tool='plot_md')
-        self.assertEqual(len(lines), 1)
-        self.close_win(lines)
+        tool_names = ['plot_md', 'md']
+        for tnames in tool_names:
+            lines = plot(MDWWorkspaceName, tool='plot_md')
+            self.assertEqual(len(lines), 1)
+            self.close_win(lines)
 
         # now see what happens with non-md workspaces
         try:
-            self.assertRaises(ValueError, plot(WorkspaceName2D, tool='plot_md'), "wont see this")
+            self.assertRaises(ValueError, plot(WorkspaceName2D, tool='plot_md'), "won't see this")
         except:
             print "Failed, as it should"
 
         try:
-            self.assertRaises(ValueError, plot_md(WorkspaceName2D), "wont see this")
+            self.assertRaises(ValueError, plot_md(WorkspaceName2D), "won't see this")
         except:
             print "Failed, as it should"
 
@@ -169,20 +172,22 @@ class MantidPlotFuturePyplotGeneralTest(unittest.TestCase):
         self.close_win(lines)
 
     def test_plot_with_style_args(self):
+        # note that these tests also use various aliases for the tool name 'plot_spectrum'
+        # Not adding all the possible combinations here, as this suite is becoming time consuming
         lines = plot(WorkspaceName2D, [0,1], '--g', tool='plot_spectrum')
         self.check_output_lines(lines, 2)
         self.close_win(lines)
 
-        lines = plot(WorkspaceName2D, [0,1], 'y:>', tool='plot_spectrum')
+        lines = plot(WorkspaceName2D, [0,1], 'y:>', tool='plot_sp')
         self.check_output_lines(lines, 2)
         self.close_win(lines)
 
     def test_plot_with_style_args_and_kwargs(self):
-        lines = plot(WorkspaceName2D, [0,1], '-.m', tool='plot_spectrum')
+        lines = plot(WorkspaceName2D, [0,1], '-.m', tool='spectrum')
         self.check_output_lines(lines, 2)
         self.close_win(lines)
 
-        lines = plot(WorkspaceName2D, [0,1], 'r-.>', tool='plot_spectrum')
+        lines = plot(WorkspaceName2D, [0,1], 'r-.>', tool='sp')
         self.check_output_lines(lines, 2)
         self.close_win(lines)
 
@@ -191,11 +196,11 @@ class MantidPlotFuturePyplotGeneralTest(unittest.TestCase):
         self.check_output_lines(lines, 2)
         self.close_win(lines)
 
-        lines = plot(WorkspaceName2D, [0,1], tool='plot_spectrum', linewidth=3, linestyle='-.', marker='v')
+        lines = plot(WorkspaceName2D, [0,1], tool='plot_sp', linewidth=3, linestyle='-.', marker='v')
         self.check_output_lines(lines, 2)
         self.close_win(lines)
 
-        lines = plot(SecondWorkspaceName2D, [0,1, 2], tool='plot_spectrum', linewidth=3, linestyle='-.', marker='v')
+        lines = plot(SecondWorkspaceName2D, [0,1, 2], tool='sp', linewidth=3, linestyle='-.', marker='v')
         self.check_output_lines(lines, 3)
         self.close_win(lines)
 
@@ -221,4 +226,4 @@ class MantidPlotFuturePyplotGeneralTest(unittest.TestCase):
             print "Failed, as it should"
 
 # Run the unit tests
-mantidplottests.runTests(MantidPlotFuturePyplotGeneralTest)
+mantidplottests.runTests(MantidPlotPyplotGeneralTest)
diff --git a/Code/Mantid/MantidQt/API/inc/MantidQtAPI/MantidColorMap.h b/Code/Mantid/MantidQt/API/inc/MantidQtAPI/MantidColorMap.h
index ce06bfe6efeb4c29d32353e4d122859bc9e1e844..65ebd971bcd81b388b7a308d2990df6185bdd09c 100644
--- a/Code/Mantid/MantidQt/API/inc/MantidQtAPI/MantidColorMap.h
+++ b/Code/Mantid/MantidQt/API/inc/MantidQtAPI/MantidColorMap.h
@@ -70,6 +70,24 @@ public:
     return m_scale_type;
   }
 
+   /**
+   * Retrieve the map name
+   * @returns the map name
+   */
+  QString getName() const
+  {
+    return m_name;
+  }
+
+  /**
+   * Retrieve the map name
+   * @returns the map name
+   */
+  QString getFilePath() const
+  {
+    return m_path;
+  }
+
   /**
    * Get the number of colors in this map
    */
@@ -105,6 +123,11 @@ private:
   /// Cached NAN value
   double m_nan;
 
+  ///the name of the color map
+  QString m_name;
+
+  ///the path to the map file
+  QString m_path;
 };
 
 
diff --git a/Code/Mantid/MantidQt/API/inc/MantidQtAPI/MdConstants.h b/Code/Mantid/MantidQt/API/inc/MantidQtAPI/MdConstants.h
index 54c5f903b8dddcd92d6c2854f7011a25ef17dfe8..942967368fd8d81972f1a895b64be2a70aa54e29 100644
--- a/Code/Mantid/MantidQt/API/inc/MantidQtAPI/MdConstants.h
+++ b/Code/Mantid/MantidQt/API/inc/MantidQtAPI/MdConstants.h
@@ -41,6 +41,18 @@ namespace MantidQt
     {
       public:
 
+        // MD ParaView plugin names
+        static const QString MantidParaViewSplatterPlot;
+        static const QString MantidParaViewSpecialCoordinates;
+        static const QString MDPeaksFilter;
+        static const QString MantidParaViewPeaksFilter;
+        static const QString PeakDimensions;
+        static const QString PeaksWorkspace;
+        static const QString Delimiter;
+        static const QString WorkspaceName;
+        static const QString ProbePoint;
+        static const QString Threshold;
+
         MdConstants();
 
         ~MdConstants();
diff --git a/Code/Mantid/MantidQt/API/src/MantidColorMap.cpp b/Code/Mantid/MantidQt/API/src/MantidColorMap.cpp
index ae4f7955aa00c6bc5011521ddbd8cc4fbc6ca9cc..913fcd3b3fb3dc8af53f728934872dc75e0c0084 100644
--- a/Code/Mantid/MantidQt/API/src/MantidColorMap.cpp
+++ b/Code/Mantid/MantidQt/API/src/MantidColorMap.cpp
@@ -32,7 +32,7 @@ namespace
  * Default
  */
 MantidColorMap::MantidColorMap() : QwtColorMap(QwtColorMap::Indexed), m_scale_type(GraphOptions::Log10),
-				     m_colors(0), m_num_colors(0)
+				     m_colors(0), m_num_colors(0), m_name(), m_path()
 {
   m_nan = std::numeric_limits<double>::quiet_NaN();
   this->setNanColor(255,255,255);
@@ -46,7 +46,7 @@ MantidColorMap::MantidColorMap() : QwtColorMap(QwtColorMap::Indexed), m_scale_ty
  * @param type :: The scale type, currently Linear or Log10 
  */
 MantidColorMap::MantidColorMap(const QString & filename, GraphOptions::ScaleType type) : 
-  QwtColorMap(QwtColorMap::Indexed), m_scale_type(type), m_colors(0), m_num_colors(0)
+  QwtColorMap(QwtColorMap::Indexed), m_scale_type(type), m_colors(0), m_num_colors(0), m_name(), m_path()
 {
   m_nan = std::numeric_limits<double>::quiet_NaN();
   this->setNanColor(255,255,255);
@@ -132,7 +132,12 @@ bool MantidColorMap::loadMap(const QString & filename)
     m_colors = new_colormap;
     if (m_num_colors > 1)
       m_colors[0] = m_nan_color;
+    m_path = filename;
+    //set the name of the color map to the filename
+    QFileInfo fileinfo(filename);
+    m_name=fileinfo.baseName(); 
   } 
+
   return is_success;
 }
 
@@ -210,6 +215,7 @@ void MantidColorMap::setupDefaultMap()
 
   m_colors.clear();
   m_num_colors = 256;
+  m_name = QString::fromStdString("Default");
 
   std::stringstream colorstream(colorstring);
   float red(0.0f), green(0.0f), blue(0.0f);
diff --git a/Code/Mantid/MantidQt/API/src/MdConstants.cpp b/Code/Mantid/MantidQt/API/src/MdConstants.cpp
index 5eae091543035e64d667dcf69114833dae30c329..c38f4b06c905834cd5b924cc9da4062b44129ae5 100644
--- a/Code/Mantid/MantidQt/API/src/MdConstants.cpp
+++ b/Code/Mantid/MantidQt/API/src/MdConstants.cpp
@@ -8,6 +8,18 @@ namespace MantidQt
 {
   namespace API
   {
+    // Specifiers for ParaView filters
+    const QString MdConstants::MantidParaViewSplatterPlot = "MantidParaViewSplatterPlot";
+    const QString MdConstants::MantidParaViewSpecialCoordinates = "SpecialCoordinates";
+    const QString MdConstants::MDPeaksFilter = "MDPeaksFilter";
+    const QString MdConstants::MantidParaViewPeaksFilter = "MantidParaViewPeaksFilter";
+    const QString MdConstants::PeakDimensions = "Peak Dimensions";
+    const QString MdConstants::PeaksWorkspace = "PeaksWorkspace";
+    const QString MdConstants::Delimiter = "Delimiter";
+    const QString MdConstants::WorkspaceName = "WorkspaceName";
+    const QString MdConstants::ProbePoint = "ProbePoint";
+    const QString MdConstants::Threshold = "Threshold";
+
     MdConstants::MdConstants() : m_colorScaleStandardMax(0.1), m_logScaleDefaultValue(0.1)
     {
       initializeSettingsConstants();
diff --git a/Code/Mantid/MantidQt/CustomDialogs/CMakeLists.txt b/Code/Mantid/MantidQt/CustomDialogs/CMakeLists.txt
index 0930dd2f30b79120fb3a53571b8fffcfc2fd6cc7..9345f8652d25854e61e4422703f47f44d68a388b 100644
--- a/Code/Mantid/MantidQt/CustomDialogs/CMakeLists.txt
+++ b/Code/Mantid/MantidQt/CustomDialogs/CMakeLists.txt
@@ -6,7 +6,6 @@ set ( SRC_FILES src/CatalogPublishDialog.cpp
                 src/LoadDialog.cpp
                 src/LoadAsciiDialog.cpp
                 src/LoadDAEDialog.cpp
-                src/LoadInstrumentDialog.cpp               
                 src/LoadRawDialog.cpp
                 src/LOQScriptInputDialog.cpp
                 src/MantidGLWidget.cpp
@@ -27,7 +26,6 @@ set ( MOC_FILES inc/MantidQtCustomDialogs/CatalogPublishDialog.h
                 inc/MantidQtCustomDialogs/LoadDialog.h
                 inc/MantidQtCustomDialogs/LoadAsciiDialog.h
                 inc/MantidQtCustomDialogs/LoadDAEDialog.h
-                inc/MantidQtCustomDialogs/LoadInstrumentDialog.h               
                 inc/MantidQtCustomDialogs/LoadRawDialog.h
                 inc/MantidQtCustomDialogs/LOQScriptInputDialog.h
                 inc/MantidQtCustomDialogs/MantidGLWidget.h
@@ -49,7 +47,6 @@ set ( UI_FILES inc/MantidQtCustomDialogs/CatalogPublishDialog.ui
                inc/MantidQtCustomDialogs/LOQScriptInputDialog.ui
                inc/MantidQtCustomDialogs/PlotAsymmetryByLogValueDialog.ui
                inc/MantidQtCustomDialogs/LoadDialog.ui
-               inc/MantidQtCustomDialogs/LoadInstrumentDialog.ui              
                inc/MantidQtCustomDialogs/StartLiveDataDialog.ui
                inc/MantidQtCustomDialogs/FitDialog.ui
                inc/MantidQtCustomDialogs/SortTableWorkspaceDialog.ui
diff --git a/Code/Mantid/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/LoadInstrumentDialog.h b/Code/Mantid/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/LoadInstrumentDialog.h
deleted file mode 100644
index 7c590ba5692ed3db465f7445cd60fb2a9fd390dd..0000000000000000000000000000000000000000
--- a/Code/Mantid/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/LoadInstrumentDialog.h
+++ /dev/null
@@ -1,50 +0,0 @@
-#ifndef MANTIDQTCUSTOMDIALOGS_LOAD_INSTRUMENT_DIALOG_H_
-#define MANTIDQTCUSTOMDIALOGS_LOAD_INSTRUMENT_DIALOG_H_
-
-//----------------------
-// Includes
-//----------------------
-#include "ui_LoadInstrumentDialog.h"
-#include "MantidQtAPI/AlgorithmDialog.h"
-#include "MantidAPI/IAlgorithm.h"
-#include "MantidAPI/Algorithm.h"
-
-namespace MantidQt
-{
-namespace CustomDialogs
-{
-
-/*
-Class SlicingAlgorithmDialog
-
-*/
-class LoadInstrumentDialog : public MantidQt::API::AlgorithmDialog
-{
-  Q_OBJECT
-public:
-
-   /// Default Constructor
-  LoadInstrumentDialog(QWidget *parent = 0);
-
-  /// Destructor
-  ~LoadInstrumentDialog();
-
-protected:
-
-  /// view
-  Ui::LoadInstrumentDialog ui; 
-  
-protected slots:
-
-  void onBrowse();
-  void accept();
-
-private:
-  /// Initialize the layout
-  virtual void initLayout();
-
-};
-}
-}
-
-#endif
diff --git a/Code/Mantid/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/LoadInstrumentDialog.ui b/Code/Mantid/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/LoadInstrumentDialog.ui
deleted file mode 100644
index 593dd25e9b0f1a1fe44f610b2da7de15ed51e388..0000000000000000000000000000000000000000
--- a/Code/Mantid/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/LoadInstrumentDialog.ui
+++ /dev/null
@@ -1,139 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>LoadInstrumentDialog</class>
- <widget class="QDialog" name="LoadInstrumentDialog">
-  <property name="geometry">
-   <rect>
-    <x>0</x>
-    <y>0</y>
-    <width>400</width>
-    <height>300</height>
-   </rect>
-  </property>
-  <property name="windowTitle">
-   <string>LoadInstrument</string>
-  </property>
-  <layout class="QVBoxLayout" name="verticalLayout">
-   <item>
-    <layout class="QGridLayout" name="main_layout">
-     <item row="1" column="0">
-      <widget class="QLabel" name="lbl_workspace">
-       <property name="text">
-        <string>Workspace</string>
-       </property>
-      </widget>
-     </item>
-     <item row="2" column="0">
-      <widget class="QLabel" name="lbl_instrument_file">
-       <property name="text">
-        <string>Instrument Definition File</string>
-       </property>
-      </widget>
-     </item>
-     <item row="3" column="0">
-      <widget class="QLabel" name="lbl_instrument_name">
-       <property name="text">
-        <string>Instrument Name</string>
-       </property>
-      </widget>
-     </item>
-     <item row="4" column="0">
-      <widget class="QLabel" name="lbl_idf_xml">
-       <property name="text">
-        <string>Instrument Definition XML</string>
-       </property>
-      </widget>
-     </item>
-     <item row="2" column="1">
-      <widget class="QLineEdit" name="txt_idf"/>
-     </item>
-     <item row="5" column="0">
-      <widget class="QCheckBox" name="ck_rewrite_spec_map">
-       <property name="layoutDirection">
-        <enum>Qt::RightToLeft</enum>
-       </property>
-       <property name="text">
-        <string>RewriteSpectraMap</string>
-       </property>
-      </widget>
-     </item>
-     <item row="3" column="1">
-      <layout class="QHBoxLayout" name="idf_validator_layout">
-       <item>
-        <widget class="QLineEdit" name="txt_instrument_name"/>
-       </item>
-      </layout>
-     </item>
-     <item row="4" column="1">
-      <widget class="QLineEdit" name="txt_instrument_xml"/>
-     </item>
-     <item row="2" column="2">
-      <widget class="QPushButton" name="btn_idf">
-       <property name="text">
-        <string>Browse</string>
-       </property>
-      </widget>
-     </item>
-     <item row="1" column="1">
-      <widget class="MantidQt::MantidWidgets::WorkspaceSelector" name="workspaceSelector"/>
-     </item>
-     <item row="1" column="2">
-      <layout class="QHBoxLayout" name="ws_validator_layout"/>
-     </item>
-    </layout>
-   </item>
-   <item>
-    <widget class="QDialogButtonBox" name="controls">
-     <property name="orientation">
-      <enum>Qt::Horizontal</enum>
-     </property>
-     <property name="standardButtons">
-      <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
-     </property>
-    </widget>
-   </item>
-  </layout>
- </widget>
- <customwidgets>
-  <customwidget>
-   <class>MantidQt::MantidWidgets::WorkspaceSelector</class>
-   <extends>QComboBox</extends>
-   <header>MantidQtMantidWidgets/WorkspaceSelector.h</header>
-  </customwidget>
- </customwidgets>
- <resources/>
- <connections>
-  <connection>
-   <sender>controls</sender>
-   <signal>accepted()</signal>
-   <receiver>LoadInstrumentDialog</receiver>
-   <slot>accept()</slot>
-   <hints>
-    <hint type="sourcelabel">
-     <x>248</x>
-     <y>254</y>
-    </hint>
-    <hint type="destinationlabel">
-     <x>157</x>
-     <y>274</y>
-    </hint>
-   </hints>
-  </connection>
-  <connection>
-   <sender>controls</sender>
-   <signal>rejected()</signal>
-   <receiver>LoadInstrumentDialog</receiver>
-   <slot>reject()</slot>
-   <hints>
-    <hint type="sourcelabel">
-     <x>316</x>
-     <y>260</y>
-    </hint>
-    <hint type="destinationlabel">
-     <x>286</x>
-     <y>274</y>
-    </hint>
-   </hints>
-  </connection>
- </connections>
-</ui>
diff --git a/Code/Mantid/MantidQt/CustomDialogs/src/LoadInstrumentDialog.cpp b/Code/Mantid/MantidQt/CustomDialogs/src/LoadInstrumentDialog.cpp
deleted file mode 100644
index 5716406111d92270b3c458c55d12be125a332c2b..0000000000000000000000000000000000000000
--- a/Code/Mantid/MantidQt/CustomDialogs/src/LoadInstrumentDialog.cpp
+++ /dev/null
@@ -1,93 +0,0 @@
-#include "MantidQtCustomDialogs/LoadInstrumentDialog.h"
-
-#include <QFileDialog>
-#include <QDir>
-#include <QBoxLayout>
-#include <QMessageBox>
-
-using namespace Mantid::API;
-
-namespace MantidQt
-{
-  namespace CustomDialogs
-  {
-    DECLARE_DIALOG(LoadInstrumentDialog)
-
-    /**
-    Constructor
-    @param parent : parent widget
-    */
-    LoadInstrumentDialog::LoadInstrumentDialog(QWidget* parent) : AlgorithmDialog(parent)
-    {
-    }
-
-
-    /// Set up the dialog layout
-    void LoadInstrumentDialog::initLayout()
-    {
-      ui.setupUi(this);
-      this->setWindowTitle(m_algName);
-
-      // Add the description of the algorithm text to the dialog.
-      QVBoxLayout* tempLayout = new QVBoxLayout;
-      this->addOptionalMessage(tempLayout);
-      ui.main_layout->addLayout(tempLayout, 0, 0, 1, 3);
-
-      tie(ui.workspaceSelector, "Workspace", ui.ws_validator_layout);
-      tie(ui.txt_idf, "Filename", ui.idf_validator_layout);
-      tie(ui.txt_instrument_name, "InstrumentName");
-      tie(ui.txt_instrument_xml, "InstrumentXML");
-      tie(ui.ck_rewrite_spec_map, "RewriteSpectraMap");
-      
-      ui.workspaceSelector->setValidatingAlgorithm(m_algName);
-
-      connect(ui.controls, SIGNAL(accepted()), this, SLOT(accept()));
-
-      connect(ui.btn_idf, SIGNAL(clicked()), this, SLOT(onBrowse()));
-    }
-
-    /**
-    Event handler for the browsing click event. 
-    */
-    void LoadInstrumentDialog::onBrowse()
-    {
-      QFileDialog dialog;
-      dialog.setDirectory(QDir::homePath());
-      dialog.setNameFilter("IDF (*.xml)");
-      if (dialog.exec())
-      {
-        ui.txt_idf->setText(dialog.selectedFile());
-      }
-    }
-
-    /**
-    Event handler for the accepted slot. Called when the user wishes to execute the algorithm.
-
-    Provides additional confirmation that the spectra-detector map will be overwritten if selected.
-    */
-    void LoadInstrumentDialog::accept()
-    {
-      if(ui.ck_rewrite_spec_map->isChecked())
-      {
-        QMessageBox warningBox;
-        warningBox.setText("Are you sure you want to re-write the spectra detector map with a 1:1 mapping?.");
-        warningBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
-        int result = warningBox.exec();
-        if(result == QMessageBox::Cancel)
-        {
-          ui.ck_rewrite_spec_map->setChecked(false);
-          return;
-        }
-      }
-      AlgorithmDialog::accept();
-    }
-    
-    /**
-    Destructor
-    */
-    LoadInstrumentDialog::~LoadInstrumentDialog()
-    {
-    }
-
-  }
-}
\ No newline at end of file
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/CMakeLists.txt b/Code/Mantid/MantidQt/CustomInterfaces/CMakeLists.txt
index 48746b193aa7d48d72f3bb5e7929c26f6ae8a2c5..10da5fd1200fe84548d22d4cdb6b471f54f25f05 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/CMakeLists.txt
+++ b/Code/Mantid/MantidQt/CustomInterfaces/CMakeLists.txt
@@ -1,5 +1,7 @@
 set ( SRC_FILES
+	src/background.cpp
   src/DataComparison.cpp
+	src/deltaECalc.cpp
 	src/DirectConvertToEnergy.cpp
 	src/Homer.cpp
 	src/Indirect/AbsorptionCorrections.cpp
@@ -79,15 +81,18 @@ set ( SRC_FILES
 	src/SANSPlotSpecial.cpp
 	src/SANSRunWindow.cpp
 	src/StepScan.cpp
+	src/TomoReconstruction/SavuConfigDialog.cpp
+	src/TomoReconstruction/TomoReconstruction.cpp
+	src/TomoReconstruction/TomoToolConfigDialog.cpp
+	src/TomoReconstruction/ToolSettings.cpp
 	src/UserInputValidator.cpp
-	src/background.cpp
-	src/deltaECalc.cpp
 )
 
 # Include files aren't required, but this makes them appear in Visual Studio
 set ( INC_FILES
 	inc/MantidQtCustomInterfaces/Background.h
   inc/MantidQtCustomInterfaces/DataComparison.h
+	inc/MantidQtCustomInterfaces/deltaECalc.h
 	inc/MantidQtCustomInterfaces/DirectConvertToEnergy.h
 	inc/MantidQtCustomInterfaces/DllConfig.h
 	inc/MantidQtCustomInterfaces/Homer.h
@@ -170,16 +175,18 @@ set ( INC_FILES
 	inc/MantidQtCustomInterfaces/QReflTableModel.h
 	inc/MantidQtCustomInterfaces/QtReflMainView.h
 	inc/MantidQtCustomInterfaces/QtReflOptionsDialog.h
-  inc/MantidQtCustomInterfaces/SampleTransmission.h
+        inc/MantidQtCustomInterfaces/SampleTransmission.h
 	inc/MantidQtCustomInterfaces/SANSAddFiles.h
 	inc/MantidQtCustomInterfaces/SANSDiagnostics.h
 	inc/MantidQtCustomInterfaces/SANSEventSlicing.h
 	inc/MantidQtCustomInterfaces/SANSPlotSpecial.h
 	inc/MantidQtCustomInterfaces/SANSRunWindow.h
 	inc/MantidQtCustomInterfaces/StepScan.h
+	inc/MantidQtCustomInterfaces/TomoReconstruction/TomoReconstruction.h
+	inc/MantidQtCustomInterfaces/TomoReconstruction/TomoToolConfigDialog.h
+	inc/MantidQtCustomInterfaces/TomoReconstruction/ToolSettings.h
 	inc/MantidQtCustomInterfaces/Updateable.h
 	inc/MantidQtCustomInterfaces/UserInputValidator.h
-	inc/MantidQtCustomInterfaces/deltaECalc.h
 )
 
 set ( SRC_UNITY_IGNORE_FILES )
@@ -225,13 +232,14 @@ set ( MOC_FILES inc/MantidQtCustomInterfaces/Background.h
                 inc/MantidQtCustomInterfaces/Indirect/ISISCalibration.h
                 inc/MantidQtCustomInterfaces/Indirect/ISISDiagnostics.h
                 inc/MantidQtCustomInterfaces/Indirect/ISISEnergyTransfer.h
+                inc/MantidQtCustomInterfaces/MantidEV.h
                 inc/MantidQtCustomInterfaces/MultiDatasetFit/MultiDatasetFit.h
-				inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFAddWorkspaceDialog.h
-				inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFDataController.h
-				inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFPlotController.h
-				inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFLocalParameterEditor.h
-				inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFLocalParameterItemDelegate.h
-				inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFEditLocalParameterDialog.h
+		inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFAddWorkspaceDialog.h
+		inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFDataController.h
+		inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFPlotController.h
+		inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFLocalParameterEditor.h
+		inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFLocalParameterItemDelegate.h
+		inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFEditLocalParameterDialog.h
                 inc/MantidQtCustomInterfaces/Muon/ALCBaselineModellingPresenter.h
                 inc/MantidQtCustomInterfaces/Muon/ALCBaselineModellingView.h
                 inc/MantidQtCustomInterfaces/Muon/ALCDataLoadingPresenter.h
@@ -257,8 +265,9 @@ set ( MOC_FILES inc/MantidQtCustomInterfaces/Background.h
                 inc/MantidQtCustomInterfaces/SANSRunWindow.h
                 inc/MantidQtCustomInterfaces/SANSEventSlicing.h              
                 inc/MantidQtCustomInterfaces/SANSDiagnostics.h
-                inc/MantidQtCustomInterfaces/MantidEV.h
                 inc/MantidQtCustomInterfaces/StepScan.h
+                inc/MantidQtCustomInterfaces/TomoReconstruction/TomoReconstruction.h
+                inc/MantidQtCustomInterfaces/TomoReconstruction/TomoToolConfigDialog.h
 )
 
 set ( UI_FILES inc/MantidQtCustomInterfaces/DataComparison.ui
@@ -294,9 +303,10 @@ set ( UI_FILES inc/MantidQtCustomInterfaces/DataComparison.ui
                inc/MantidQtCustomInterfaces/Indirect/ISISCalibration.ui
                inc/MantidQtCustomInterfaces/Indirect/ISISDiagnostics.ui
                inc/MantidQtCustomInterfaces/Indirect/ISISEnergyTransfer.ui
+               inc/MantidQtCustomInterfaces/MantidEV.ui
                inc/MantidQtCustomInterfaces/MultiDatasetFit/MultiDatasetFit.ui
-			   inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFAddWorkspaceDialog.ui
-			   inc/MantidQtCustomInterfaces/MultiDatasetFit/EditLocalParameterDialog.ui
+	       inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFAddWorkspaceDialog.ui
+	       inc/MantidQtCustomInterfaces/MultiDatasetFit/EditLocalParameterDialog.ui
                inc/MantidQtCustomInterfaces/Muon/ALCBaselineModellingView.ui
                inc/MantidQtCustomInterfaces/Muon/ALCDataLoadingView.ui
                inc/MantidQtCustomInterfaces/Muon/ALCInterface.ui
@@ -309,19 +319,24 @@ set ( UI_FILES inc/MantidQtCustomInterfaces/DataComparison.ui
                inc/MantidQtCustomInterfaces/SANSPlotSpecial.ui
                inc/MantidQtCustomInterfaces/SANSRunWindow.ui  
                inc/MantidQtCustomInterfaces/SANSEventSlicing.ui
-               inc/MantidQtCustomInterfaces/MantidEV.ui
                inc/MantidQtCustomInterfaces/StepScan.ui
+               inc/MantidQtCustomInterfaces/TomoReconstruction/TomoReconstruction.ui
+               inc/MantidQtCustomInterfaces/TomoReconstruction/TomoToolConfigAstra.ui
+               inc/MantidQtCustomInterfaces/TomoReconstruction/TomoToolConfigCustom.ui
+               inc/MantidQtCustomInterfaces/TomoReconstruction/TomoToolConfigSavu.ui
+               inc/MantidQtCustomInterfaces/TomoReconstruction/TomoToolConfigTomoPy.ui
 )
 
 set ( TEST_FILES
-	ALCBaselineModellingModelTest.h
-	ALCBaselineModellingPresenterTest.h
-	ALCDataLoadingPresenterTest.h
-	ALCPeakFittingPresenterTest.h
-	IO_MuonGroupingTest.h
-	MuonAnalysisHelperTest.h
-	ReflLegacyTransferStrategyTest.h
-	ReflMainViewPresenterTest.h
+  ALCBaselineModellingModelTest.h
+  ALCBaselineModellingPresenterTest.h
+  ALCDataLoadingPresenterTest.h
+  ALCPeakFittingModelTest.h
+  ALCPeakFittingPresenterTest.h
+  IO_MuonGroupingTest.h
+  MuonAnalysisHelperTest.h
+  ReflLegacyTransferStrategyTest.h
+  ReflMainViewPresenterTest.h
   UserInputValidatorTest.h
 )
 
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/AbsorptionCorrections.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/AbsorptionCorrections.ui
index 24dcd40d736b1b745a2f825dfadcfc6b76d750fe..9cfad94684194980d1186f0019026cf69a2c4acc 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/AbsorptionCorrections.ui
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/AbsorptionCorrections.ui
@@ -6,7 +6,7 @@
    <rect>
     <x>0</x>
     <y>0</y>
-    <width>575</width>
+    <width>587</width>
     <height>488</height>
    </rect>
   </property>
@@ -786,5 +786,21 @@
     </hint>
    </hints>
   </connection>
+  <connection>
+   <sender>spFlatCanFrontThickness</sender>
+   <signal>valueChanged(double)</signal>
+   <receiver>spFlatCanBackThickness</receiver>
+   <slot>setValue(double)</slot>
+   <hints>
+    <hint type="sourcelabel">
+     <x>238</x>
+     <y>212</y>
+    </hint>
+    <hint type="destinationlabel">
+     <x>514</x>
+     <y>212</y>
+    </hint>
+   </hints>
+  </connection>
  </connections>
 </ui>
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/CalcCorr.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/CalcCorr.ui
index ec972ba9ccacd6f8faac49e279bdb32a32f92fa4..1321aa249e9a16dd3014f78af999cfeb062ad5bf 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/CalcCorr.ui
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/CalcCorr.ui
@@ -296,14 +296,14 @@
            </widget>
           </item>
           <item row="0" column="0">
-           <widget class="QLabel" name="lbCylSampleInnerRadius">
+           <widget class="QLabel" name="lbCylSampleOuterRadius">
             <property name="text">
-             <string>Sample Inner Radius:</string>
+             <string>Sample Radius:</string>
             </property>
            </widget>
           </item>
           <item row="0" column="1">
-           <widget class="QDoubleSpinBox" name="spCylSampleInnerRadius">
+           <widget class="QDoubleSpinBox" name="spCylSampleOuterRadius">
             <property name="decimals">
              <number>3</number>
             </property>
@@ -316,7 +316,10 @@
            </widget>
           </item>
           <item row="0" column="3">
-           <widget class="QDoubleSpinBox" name="spCylSampleOuterRadius">
+           <widget class="QDoubleSpinBox" name="spCylCanOuterRadius">
+            <property name="enabled">
+             <bool>false</bool>
+            </property>
             <property name="decimals">
              <number>3</number>
             </property>
@@ -329,35 +332,12 @@
            </widget>
           </item>
           <item row="0" column="2">
-           <widget class="QLabel" name="lbCylSampleOuterRadius">
-            <property name="text">
-             <string>Sample Outer Radius:</string>
-            </property>
-           </widget>
-          </item>
-          <item row="1" column="0">
            <widget class="QLabel" name="lbCylCanOuterRadius">
             <property name="enabled">
              <bool>false</bool>
             </property>
             <property name="text">
-             <string>Container Outer Radius:</string>
-            </property>
-           </widget>
-          </item>
-          <item row="1" column="1">
-           <widget class="QDoubleSpinBox" name="spCylCanOuterRadius">
-            <property name="enabled">
-             <bool>false</bool>
-            </property>
-            <property name="decimals">
-             <number>3</number>
-            </property>
-            <property name="maximum">
-             <double>9999.989999999999782</double>
-            </property>
-            <property name="singleStep">
-             <double>0.100000000000000</double>
+             <string>Container Radius:</string>
             </property>
            </widget>
           </item>
@@ -422,15 +402,21 @@
             </property>
            </widget>
           </item>
-          <item row="0" column="0">
-           <widget class="QLabel" name="lbAnnSampleOuterRadius">
+          <item row="1" column="0">
+           <widget class="QLabel" name="lbAnnCanOuterRadius">
+            <property name="enabled">
+             <bool>false</bool>
+            </property>
             <property name="text">
-             <string>Sample Outer Radius:</string>
+             <string>Container Outer Radius:</string>
             </property>
            </widget>
           </item>
-          <item row="0" column="1">
-           <widget class="QDoubleSpinBox" name="spAnnSampleOuterRadius">
+          <item row="1" column="1">
+           <widget class="QDoubleSpinBox" name="spAnnCanOuterRadius">
+            <property name="enabled">
+             <bool>false</bool>
+            </property>
             <property name="decimals">
              <number>3</number>
             </property>
@@ -443,10 +429,7 @@
            </widget>
           </item>
           <item row="0" column="3">
-           <widget class="QDoubleSpinBox" name="spAnnCanOuterRadius">
-            <property name="enabled">
-             <bool>false</bool>
-            </property>
+           <widget class="QDoubleSpinBox" name="spAnnSampleOuterRadius">
             <property name="decimals">
              <number>3</number>
             </property>
@@ -459,12 +442,29 @@
            </widget>
           </item>
           <item row="0" column="2">
-           <widget class="QLabel" name="lbAnnCanOuterRadius">
-            <property name="enabled">
-             <bool>false</bool>
+           <widget class="QLabel" name="lbAnnSampleOuterRadius">
+            <property name="text">
+             <string>Sample Outer Radius:</string>
             </property>
+           </widget>
+          </item>
+          <item row="0" column="0">
+           <widget class="QLabel" name="lbAnnSampleInnerRadius">
             <property name="text">
-             <string>Container Outer Radius:</string>
+             <string>Sample Inner Radius:</string>
+            </property>
+           </widget>
+          </item>
+          <item row="0" column="1">
+           <widget class="QDoubleSpinBox" name="spAnnSampleInnerRadius">
+            <property name="decimals">
+             <number>3</number>
+            </property>
+            <property name="maximum">
+             <double>9999.989999999999782</double>
+            </property>
+            <property name="singleStep">
+             <double>0.100000000000000</double>
             </property>
            </widget>
           </item>
@@ -687,12 +687,12 @@
   <tabstop>spFlatSampleAngle</tabstop>
   <tabstop>spFlatCanFrontThickness</tabstop>
   <tabstop>spFlatCanBackThickness</tabstop>
-  <tabstop>spCylSampleInnerRadius</tabstop>
   <tabstop>spCylSampleOuterRadius</tabstop>
   <tabstop>spCylCanOuterRadius</tabstop>
   <tabstop>spCylBeamHeight</tabstop>
   <tabstop>spCylBeamWidth</tabstop>
   <tabstop>spCylStepSize</tabstop>
+  <tabstop>spAnnSampleInnerRadius</tabstop>
   <tabstop>spAnnSampleOuterRadius</tabstop>
   <tabstop>spAnnCanOuterRadius</tabstop>
   <tabstop>spAnnBeamHeight</tabstop>
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ConvFit.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ConvFit.h
index 4c08a72458bba6ec029da0160d35377a29b90358..9dc32f42959be89955a977fafc41ae7083f2601e 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ConvFit.h
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ConvFit.h
@@ -29,6 +29,7 @@ namespace IDA
     void typeSelection(int index);
     void bgTypeSelection(int index);
     void newDataLoaded(const QString wsName);
+    void extendResolutionWorkspace();
     void updatePlot();
     void plotGuess();
     void singleFit();
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ISISEnergyTransfer.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ISISEnergyTransfer.h
index 167b3f9c1e28be3ba9e6b52e011af4fc15cdfb55..d164fa8aa6aae3a65e4c873d541e6d5527df0039 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ISISEnergyTransfer.h
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ISISEnergyTransfer.h
@@ -63,7 +63,7 @@ namespace CustomInterfaces
   private:
     Ui::ISISEnergyTransfer m_uiForm;
 
-    QString createMapFile(const QString& groupType); ///< create the mapping file with which to group results
+    QPair<QString, QString> createMapFile(const QString& groupType); ///< create the mapping file with which to group results
     std::vector<std::string> getSaveFormats(); ///< get a vector of save formats
 
   };
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ISISEnergyTransfer.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ISISEnergyTransfer.ui
index e53c1319081ead9934fe2ec4154761eff166696a..e74fc8a361fc8a66aa3c8ae0531bf4c1b9e8d002 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ISISEnergyTransfer.ui
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ISISEnergyTransfer.ui
@@ -6,8 +6,8 @@
    <rect>
     <x>0</x>
     <y>0</y>
-    <width>611</width>
-    <height>670</height>
+    <width>617</width>
+    <height>755</height>
    </rect>
   </property>
   <property name="minimumSize">
@@ -25,89 +25,67 @@
      <property name="title">
       <string>Input</string>
      </property>
-     <layout class="QVBoxLayout" name="verticalLayout">
-      <property name="spacing">
-       <number>0</number>
-      </property>
-      <item>
-       <layout class="QHBoxLayout" name="loInput">
-        <item>
-         <layout class="QVBoxLayout" name="loInputSources">
-          <item>
-           <widget class="MantidQt::MantidWidgets::MWRunFiles" name="dsRunFiles" native="true">
-            <property name="sizePolicy">
-             <sizepolicy hsizetype="Preferred" vsizetype="Fixed">
-              <horstretch>0</horstretch>
-              <verstretch>41</verstretch>
-             </sizepolicy>
-            </property>
-            <property name="label" stdset="0">
-             <string>Run Files</string>
-            </property>
-            <property name="multipleFiles" stdset="0">
-             <bool>true</bool>
-            </property>
-           </widget>
-          </item>
-          <item>
-           <widget class="MantidQt::MantidWidgets::DataSelector" name="dsCalibrationFile" native="true">
-            <property name="enabled">
-             <bool>false</bool>
-            </property>
-            <property name="sizePolicy">
-             <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
-              <horstretch>0</horstretch>
-              <verstretch>0</verstretch>
-             </sizepolicy>
-            </property>
-            <property name="autoLoad" stdset="0">
-             <bool>true</bool>
-            </property>
-            <property name="showLoad" stdset="0">
-             <bool>false</bool>
-            </property>
-            <property name="workspaceSuffixes" stdset="0">
-             <string>_calib</string>
-            </property>
-            <property name="fileBrowserSuffixes" stdset="0">
-             <string>_calib.nxs</string>
-            </property>
-           </widget>
-          </item>
-         </layout>
-        </item>
-        <item>
-         <layout class="QVBoxLayout" name="loInputOptions">
-          <item>
-           <widget class="QCheckBox" name="ckSumFiles">
-            <property name="toolTip">
-             <string>Sum multiple files together.</string>
-            </property>
-            <property name="text">
-             <string>Sum Files</string>
-            </property>
-           </widget>
-          </item>
-          <item>
-           <widget class="QCheckBox" name="ckLoadLogs">
-            <property name="text">
-             <string>Load Logs</string>
-            </property>
-           </widget>
-          </item>
-          <item>
-           <widget class="QCheckBox" name="ckUseCalib">
-            <property name="toolTip">
-             <string>Use calibration file to adjust for detector efficiency.</string>
-            </property>
-            <property name="text">
-             <string>Use Calib File</string>
-            </property>
-           </widget>
-          </item>
-         </layout>
-        </item>
-       </layout>
+     <layout class="QGridLayout" name="gridLayout">
+      <item row="0" column="1">
+       <widget class="QCheckBox" name="ckSumFiles">
+        <property name="toolTip">
+         <string>Sum multiple files together.</string>
+        </property>
+        <property name="text">
+         <string>Sum Files</string>
+        </property>
+       </widget>
+      </item>
+      <item row="1" column="0">
+       <widget class="MantidQt::MantidWidgets::DataSelector" name="dsCalibrationFile" native="true">
+        <property name="enabled">
+         <bool>false</bool>
+        </property>
+        <property name="sizePolicy">
+         <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
+          <horstretch>0</horstretch>
+          <verstretch>0</verstretch>
+         </sizepolicy>
+        </property>
+        <property name="autoLoad" stdset="0">
+         <bool>true</bool>
+        </property>
+        <property name="showLoad" stdset="0">
+         <bool>false</bool>
+        </property>
+        <property name="workspaceSuffixes" stdset="0">
+         <string>_calib</string>
+        </property>
+        <property name="fileBrowserSuffixes" stdset="0">
+         <string>_calib.nxs</string>
+        </property>
+       </widget>
+      </item>
+      <item row="1" column="1">
+       <widget class="QCheckBox" name="ckUseCalib">
+        <property name="toolTip">
+         <string>Use calibration file to adjust for detector efficiency.</string>
+        </property>
+        <property name="text">
+         <string>Use Calib File</string>
+        </property>
+       </widget>
+      </item>
+      <item row="0" column="0">
+       <widget class="MantidQt::MantidWidgets::MWRunFiles" name="dsRunFiles" native="true">
+        <property name="sizePolicy">
+         <sizepolicy hsizetype="Preferred" vsizetype="Fixed">
+          <horstretch>0</horstretch>
+          <verstretch>41</verstretch>
+         </sizepolicy>
+        </property>
+        <property name="label" stdset="0">
+         <string>Run Files</string>
+        </property>
+        <property name="multipleFiles" stdset="0">
+         <bool>true</bool>
+        </property>
+       </widget>
       </item>
      </layout>
     </widget>
@@ -256,9 +234,6 @@
       <property name="sizeConstraint">
        <enum>QLayout::SetDefaultConstraint</enum>
       </property>
-      <property name="spacing">
-       <number>0</number>
-      </property>
       <item row="0" column="0">
        <widget class="QCheckBox" name="ckDetailedBalance">
         <property name="text">
@@ -336,9 +311,6 @@
       <string>Conversion to Energy Transfer</string>
      </property>
      <layout class="QHBoxLayout" name="horizontalLayout">
-      <property name="spacing">
-       <number>6</number>
-      </property>
       <item>
        <widget class="QLabel" name="lbEFixed">
         <property name="text">
@@ -422,12 +394,6 @@
       <string>Rebin (meV)</string>
      </property>
      <layout class="QVBoxLayout" name="verticalLayout_14">
-      <property name="spacing">
-       <number>6</number>
-      </property>
-      <property name="margin">
-       <number>6</number>
-      </property>
       <item>
        <layout class="QHBoxLayout" name="loRebin">
         <property name="spacing">
@@ -822,18 +788,6 @@
       <string>Output</string>
      </property>
      <layout class="QGridLayout" name="gridLayout_8">
-      <property name="leftMargin">
-       <number>6</number>
-      </property>
-      <property name="topMargin">
-       <number>6</number>
-      </property>
-      <property name="rightMargin">
-       <number>6</number>
-      </property>
-      <property name="horizontalSpacing">
-       <number>0</number>
-      </property>
       <item row="1" column="0">
        <layout class="QHBoxLayout" name="loSaveFormats">
         <item>
@@ -1126,25 +1080,25 @@
    </hints>
   </connection>
   <connection>
-   <sender>ckUseCalib</sender>
+   <sender>ckBackgroundRemoval</sender>
    <signal>toggled(bool)</signal>
-   <receiver>dsCalibrationFile</receiver>
+   <receiver>spBackgroundStart</receiver>
    <slot>setEnabled(bool)</slot>
    <hints>
     <hint type="sourcelabel">
-     <x>441</x>
-     <y>98</y>
+     <x>96</x>
+     <y>237</y>
     </hint>
     <hint type="destinationlabel">
-     <x>159</x>
-     <y>86</y>
+     <x>476</x>
+     <y>238</y>
     </hint>
    </hints>
   </connection>
   <connection>
    <sender>ckBackgroundRemoval</sender>
    <signal>toggled(bool)</signal>
-   <receiver>spBackgroundStart</receiver>
+   <receiver>spBackgroundEnd</receiver>
    <slot>setEnabled(bool)</slot>
    <hints>
     <hint type="sourcelabel">
@@ -1152,24 +1106,24 @@
      <y>237</y>
     </hint>
     <hint type="destinationlabel">
-     <x>476</x>
+     <x>554</x>
      <y>238</y>
     </hint>
    </hints>
   </connection>
   <connection>
-   <sender>ckBackgroundRemoval</sender>
+   <sender>ckUseCalib</sender>
    <signal>toggled(bool)</signal>
-   <receiver>spBackgroundEnd</receiver>
+   <receiver>dsCalibrationFile</receiver>
    <slot>setEnabled(bool)</slot>
    <hints>
     <hint type="sourcelabel">
-     <x>96</x>
-     <y>237</y>
+     <x>454</x>
+     <y>86</y>
     </hint>
     <hint type="destinationlabel">
-     <x>554</x>
-     <y>238</y>
+     <x>162</x>
+     <y>86</y>
     </hint>
    </hints>
   </connection>
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSqw.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSqw.ui
index 5c4178324e9b1ef9e201554f7e541fb8a153b734..960e1417b160c8adf44c461b2d3adef32553f139 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSqw.ui
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSqw.ui
@@ -369,12 +369,12 @@
           </property>
           <item>
            <property name="text">
-            <string>Parallelepiped (SofQW2)</string>
+            <string>Parallelepiped</string>
            </property>
           </item>
           <item>
            <property name="text">
-            <string>Parallelepiped/Fractional Area (SofQW3)</string>
+            <string>Parallelepiped/Fractional Area</string>
            </property>
           </item>
          </widget>
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCBaselineModellingModel.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCBaselineModellingModel.h
index ec5eb64f333af2751c42cb06890ed637bd8a7685..5391083016a74eecbda66e6da25ed1477582f529 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCBaselineModellingModel.h
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCBaselineModellingModel.h
@@ -39,13 +39,15 @@ namespace CustomInterfaces
   public:
     // -- IALCBaselineModellingModel interface -----------------------------------------------------
 
-    MatrixWorkspace_const_sptr data() const { return m_data; }
+    MatrixWorkspace_const_sptr data() const;
 
     void fit(IFunction_const_sptr function, const std::vector<Section> &sections);
 
     IFunction_const_sptr fittedFunction() const { return m_fittedFunction; }
 
-    MatrixWorkspace_const_sptr correctedData() const { return m_correctedData; }
+    MatrixWorkspace_const_sptr correctedData() const;
+
+    ITableWorkspace_sptr parameterTable() const { return m_parameterTable; }
 
     const std::vector<Section>& sections() const { return m_sections; }
 
@@ -65,15 +67,15 @@ namespace CustomInterfaces
 
 
   private:
-    /// Data to use for fitting
+    /// Data used for fitting
     MatrixWorkspace_const_sptr m_data;
 
-    /// Corrected data of the last fit
-    MatrixWorkspace_const_sptr m_correctedData;
-
     /// Result function of the last fit
     IFunction_const_sptr m_fittedFunction;
 
+    /// Fit table containing parameters and errors
+    ITableWorkspace_sptr m_parameterTable;
+
     /// Sections used for the last fit
     std::vector<Section> m_sections;
 
@@ -84,6 +86,9 @@ namespace CustomInterfaces
     /// Disables points which shouldn't be used for fitting
     static void disableUnwantedPoints(MatrixWorkspace_sptr ws, const std::vector<Section>& sections);
 
+    /// Enable previously disabled points
+    static void enableDisabledPoints(MatrixWorkspace_sptr destWs, MatrixWorkspace_const_sptr sourceWs);
+
   };
 
 } // namespace CustomInterfaces
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCBaselineModellingPresenter.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCBaselineModellingPresenter.h
index 8c4e4925ea3b0fd2b0258ea988786bd090504168..9b4b13970b18b0d29beb784b8d0d993f64b47008 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCBaselineModellingPresenter.h
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCBaselineModellingPresenter.h
@@ -73,9 +73,6 @@ namespace CustomInterfaces
     /// Updates function in the view from the model
     void updateFunction();
 
-    /// Removes all section rows / section selectors
-    void clearSections();
-
   private:
     /// Associated view
     IALCBaselineModellingView* const m_view;
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCPeakFittingModel.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCPeakFittingModel.h
index d5510f182c5ce8cd90962a76abce0c054bf3365f..91fff1ba9c3f22397b7784497700236a41b42fa5 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCPeakFittingModel.h
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCPeakFittingModel.h
@@ -41,6 +41,7 @@ namespace CustomInterfaces
     // -- IALCPeakFittingModel interface -----------------------------------------------------------
     IFunction_const_sptr fittedPeaks() const { return m_fittedPeaks; }
     MatrixWorkspace_const_sptr data() const { return m_data; }
+    ITableWorkspace_sptr parameterTable() const { return m_parameterTable; }
 
     void fitPeaks(IFunction_const_sptr peaks);
     // -- End of IALCPeakFittingModel interface ----------------------------------------------------
@@ -58,6 +59,9 @@ namespace CustomInterfaces
     /// The data we are fitting peaks to
     MatrixWorkspace_const_sptr m_data;
 
+    /// Parameter table containing fit results
+    ITableWorkspace_sptr m_parameterTable;
+
     /// Setter for convenience
     void setFittedPeaks(IFunction_const_sptr fittedPeaks);
 
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSAddFiles.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSAddFiles.h
index fd9c38103569307cbc1d17089c9757d6d709b663..0a7847201897c41c6a9e1f990950e1b9ec66d8dc 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSAddFiles.h
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSAddFiles.h
@@ -63,6 +63,8 @@ private slots:
   void removeSelected();
   /// Enables/disables the "Sum" button based on whether there are files to sum.
   void enableSumming();
+  /// reacts to changges of the combo box selection for the histogram options for event data
+  void onCurrentIndexChangedForHistogramChoice(int index);
 };
 
 }
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSRunWindow.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSRunWindow.ui
index 5bf81709ed931565f8042721350cb1e673672f07..9a082fef7812177da8cfbfa1c58082f6fa59bda3 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSRunWindow.ui
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSRunWindow.ui
@@ -32,4141 +32,4186 @@
    <string>ISIS SANS</string>
   </property>
   <widget class="QWidget" name="centralwidget">
-  <layout class="QGridLayout" name="gridLayout_27">
-   <item row="1" column="0">
-    <layout class="QHBoxLayout" name="horizontalLayout_20">
-     <item>
-      <widget class="QPushButton" name="pushButton_Help">
-       <property name="maximumSize">
-        <size>
-         <width>23</width>
-         <height>23</height>
-        </size>
-       </property>
-       <property name="text">
-        <string>?</string>
-       </property>
-      </widget>
-     </item>
-     <item>
-      <spacer name="horizontalSpacer_19">
-       <property name="orientation">
-        <enum>Qt::Horizontal</enum>
-       </property>
-       <property name="sizeHint" stdset="0">
-        <size>
-         <width>40</width>
-         <height>20</height>
-        </size>
-       </property>
-      </spacer>
-     </item>
-    </layout>
-   </item>
-   <item row="0" column="0">
-    <widget class="QTabWidget" name="tabWidget">
-     <property name="enabled">
-      <bool>true</bool>
-     </property>
-     <property name="sizePolicy">
-      <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
-       <horstretch>0</horstretch>
-       <verstretch>0</verstretch>
-      </sizepolicy>
-     </property>
-     <property name="minimumSize">
-      <size>
-       <width>0</width>
-       <height>0</height>
-      </size>
-     </property>
-     <property name="maximumSize">
-      <size>
-       <width>16777215</width>
-       <height>16777215</height>
-      </size>
-     </property>
-     <property name="autoFillBackground">
-      <bool>false</bool>
-     </property>
-     <property name="styleSheet">
-      <string notr="true"/>
-     </property>
-     <property name="currentIndex">
-      <number>0</number>
-     </property>
-     <property name="elideMode">
-      <enum>Qt::ElideNone</enum>
-     </property>
-     <property name="usesScrollButtons">
-      <bool>true</bool>
-     </property>
-     <widget class="QWidget" name="runNumbers">
-      <attribute name="title">
-       <string>Run Numbers</string>
-      </attribute>
-      <layout class="QGridLayout" name="gridLayout_28">
-       <item row="0" column="0" colspan="2">
-        <layout class="QGridLayout" name="gridLayout_46">
-         <item row="0" column="0">
-          <widget class="QLabel" name="label_11">
-           <property name="sizePolicy">
-            <sizepolicy hsizetype="Maximum" vsizetype="Maximum">
-             <horstretch>39</horstretch>
-             <verstretch>0</verstretch>
-            </sizepolicy>
-           </property>
-           <property name="minimumSize">
-            <size>
-             <width>39</width>
-             <height>0</height>
-            </size>
-           </property>
-           <property name="text">
-            <string>User file: </string>
-           </property>
-          </widget>
-         </item>
-         <item row="0" column="1" colspan="2">
-          <widget class="QLineEdit" name="userfile_edit">
-           <property name="sizePolicy">
-            <sizepolicy hsizetype="Preferred" vsizetype="Maximum">
-             <horstretch>0</horstretch>
-             <verstretch>0</verstretch>
-            </sizepolicy>
-           </property>
-           <property name="minimumSize">
-            <size>
-             <width>200</width>
-             <height>0</height>
-            </size>
-           </property>
-          </widget>
-         </item>
-         <item row="0" column="3">
-          <widget class="QPushButton" name="userfileBtn">
-           <property name="sizePolicy">
-            <sizepolicy hsizetype="Minimum" vsizetype="Maximum">
-             <horstretch>0</horstretch>
-             <verstretch>0</verstretch>
-            </sizepolicy>
-           </property>
-           <property name="text">
-            <string>Load Mask</string>
-           </property>
-           <property name="autoDefault">
-            <bool>false</bool>
-           </property>
-          </widget>
-         </item>
-         <item row="1" column="0">
-          <widget class="QLabel" name="outDirs_lb">
-           <property name="sizePolicy">
-            <sizepolicy hsizetype="Minimum" vsizetype="Preferred">
-             <horstretch>50</horstretch>
-             <verstretch>0</verstretch>
-            </sizepolicy>
-           </property>
-           <property name="minimumSize">
-            <size>
-             <width>0</width>
-             <height>0</height>
-            </size>
-           </property>
-           <property name="maximumSize">
-            <size>
-             <width>16777215</width>
-             <height>16777215</height>
-            </size>
-           </property>
-           <property name="text">
-            <string>Data Directory:</string>
-           </property>
-          </widget>
-         </item>
-         <item row="1" column="1">
-          <widget class="QLabel" name="loadDir_lb">
-           <property name="text">
-            <string>TextLabel</string>
-           </property>
-          </widget>
-         </item>
-         <item row="1" column="2">
-          <widget class="QLabel" name="plusDirs_lb">
-           <property name="sizePolicy">
-            <sizepolicy hsizetype="Minimum" vsizetype="Minimum">
-             <horstretch>55</horstretch>
-             <verstretch>0</verstretch>
-            </sizepolicy>
-           </property>
-           <property name="minimumSize">
-            <size>
-             <width>55</width>
-             <height>0</height>
-            </size>
-           </property>
-           <property name="text">
-            <string>+? others</string>
-           </property>
-          </widget>
-         </item>
-         <item row="1" column="3">
-          <widget class="QPushButton" name="data_dirBtn">
-           <property name="sizePolicy">
-            <sizepolicy hsizetype="Minimum" vsizetype="Maximum">
-             <horstretch>0</horstretch>
-             <verstretch>0</verstretch>
-            </sizepolicy>
-           </property>
-           <property name="text">
-            <string>Manage Directories</string>
-           </property>
-           <property name="autoDefault">
-            <bool>false</bool>
-           </property>
-          </widget>
-         </item>
-        </layout>
-       </item>
-       <item row="1" column="0">
-        <widget class="QGroupBox" name="groupBox_16">
-         <property name="title">
-          <string/>
-         </property>
-         <layout class="QHBoxLayout" name="horizontalLayout_2">
-          <item>
-           <widget class="QRadioButton" name="single_mode_btn">
+   <layout class="QGridLayout" name="gridLayout_27">
+    <item row="1" column="0">
+     <layout class="QHBoxLayout" name="horizontalLayout_20">
+      <item>
+       <widget class="QPushButton" name="pushButton_Help">
+        <property name="maximumSize">
+         <size>
+          <width>23</width>
+          <height>23</height>
+         </size>
+        </property>
+        <property name="text">
+         <string>?</string>
+        </property>
+       </widget>
+      </item>
+      <item>
+       <spacer name="horizontalSpacer_19">
+        <property name="orientation">
+         <enum>Qt::Horizontal</enum>
+        </property>
+        <property name="sizeHint" stdset="0">
+         <size>
+          <width>40</width>
+          <height>20</height>
+         </size>
+        </property>
+       </spacer>
+      </item>
+     </layout>
+    </item>
+    <item row="0" column="0">
+     <widget class="QTabWidget" name="tabWidget">
+      <property name="enabled">
+       <bool>true</bool>
+      </property>
+      <property name="sizePolicy">
+       <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+        <horstretch>0</horstretch>
+        <verstretch>0</verstretch>
+       </sizepolicy>
+      </property>
+      <property name="minimumSize">
+       <size>
+        <width>0</width>
+        <height>0</height>
+       </size>
+      </property>
+      <property name="maximumSize">
+       <size>
+        <width>16777215</width>
+        <height>16777215</height>
+       </size>
+      </property>
+      <property name="autoFillBackground">
+       <bool>false</bool>
+      </property>
+      <property name="styleSheet">
+       <string notr="true"/>
+      </property>
+      <property name="currentIndex">
+       <number>5</number>
+      </property>
+      <property name="elideMode">
+       <enum>Qt::ElideNone</enum>
+      </property>
+      <property name="usesScrollButtons">
+       <bool>true</bool>
+      </property>
+      <widget class="QWidget" name="runNumbers">
+       <attribute name="title">
+        <string>Run Numbers</string>
+       </attribute>
+       <layout class="QGridLayout" name="gridLayout_28">
+        <item row="0" column="0" colspan="2">
+         <layout class="QGridLayout" name="gridLayout_46">
+          <item row="0" column="0">
+           <widget class="QLabel" name="label_11">
+            <property name="sizePolicy">
+             <sizepolicy hsizetype="Maximum" vsizetype="Maximum">
+              <horstretch>39</horstretch>
+              <verstretch>0</verstretch>
+             </sizepolicy>
+            </property>
+            <property name="minimumSize">
+             <size>
+              <width>39</width>
+              <height>0</height>
+             </size>
+            </property>
             <property name="text">
-             <string>Single run mode</string>
+             <string>User file: </string>
+            </property>
+           </widget>
+          </item>
+          <item row="0" column="1" colspan="2">
+           <widget class="QLineEdit" name="userfile_edit">
+            <property name="sizePolicy">
+             <sizepolicy hsizetype="Preferred" vsizetype="Maximum">
+              <horstretch>0</horstretch>
+              <verstretch>0</verstretch>
+             </sizepolicy>
             </property>
-            <property name="checked">
-             <bool>true</bool>
+            <property name="minimumSize">
+             <size>
+              <width>200</width>
+              <height>0</height>
+             </size>
             </property>
            </widget>
           </item>
-          <item>
-           <widget class="QRadioButton" name="batch_mode_btn">
-            <property name="enabled">
-             <bool>true</bool>
+          <item row="0" column="3">
+           <widget class="QPushButton" name="userfileBtn">
+            <property name="sizePolicy">
+             <sizepolicy hsizetype="Minimum" vsizetype="Maximum">
+              <horstretch>0</horstretch>
+              <verstretch>0</verstretch>
+             </sizepolicy>
+            </property>
+            <property name="text">
+             <string>Load Mask</string>
+            </property>
+            <property name="autoDefault">
+             <bool>false</bool>
+            </property>
+           </widget>
+          </item>
+          <item row="1" column="0">
+           <widget class="QLabel" name="outDirs_lb">
+            <property name="sizePolicy">
+             <sizepolicy hsizetype="Minimum" vsizetype="Preferred">
+              <horstretch>50</horstretch>
+              <verstretch>0</verstretch>
+             </sizepolicy>
+            </property>
+            <property name="minimumSize">
+             <size>
+              <width>0</width>
+              <height>0</height>
+             </size>
+            </property>
+            <property name="maximumSize">
+             <size>
+              <width>16777215</width>
+              <height>16777215</height>
+             </size>
+            </property>
+            <property name="text">
+             <string>Data Directory:</string>
+            </property>
+           </widget>
+          </item>
+          <item row="1" column="1">
+           <widget class="QLabel" name="loadDir_lb">
+            <property name="text">
+             <string>TextLabel</string>
+            </property>
+           </widget>
+          </item>
+          <item row="1" column="2">
+           <widget class="QLabel" name="plusDirs_lb">
+            <property name="sizePolicy">
+             <sizepolicy hsizetype="Minimum" vsizetype="Minimum">
+              <horstretch>55</horstretch>
+              <verstretch>0</verstretch>
+             </sizepolicy>
+            </property>
+            <property name="minimumSize">
+             <size>
+              <width>55</width>
+              <height>0</height>
+             </size>
+            </property>
+            <property name="text">
+             <string>+? others</string>
+            </property>
+           </widget>
+          </item>
+          <item row="1" column="3">
+           <widget class="QPushButton" name="data_dirBtn">
+            <property name="sizePolicy">
+             <sizepolicy hsizetype="Minimum" vsizetype="Maximum">
+              <horstretch>0</horstretch>
+              <verstretch>0</verstretch>
+             </sizepolicy>
             </property>
             <property name="text">
-             <string>Batch mode</string>
+             <string>Manage Directories</string>
+            </property>
+            <property name="autoDefault">
+             <bool>false</bool>
             </property>
            </widget>
           </item>
          </layout>
-        </widget>
-       </item>
-       <item row="1" column="1">
-        <layout class="QHBoxLayout" name="horizontalLayout_16">
-         <item>
-          <widget class="QCheckBox" name="allowPeriods_ck">
-           <property name="toolTip">
-            <string>Show the multi-period entry boxes</string>
-           </property>
-           <property name="text">
-            <string>Multi-period</string>
-           </property>
-          </widget>
-         </item>
-         <item>
-          <spacer name="horizontalSpacer_16">
-           <property name="orientation">
-            <enum>Qt::Horizontal</enum>
-           </property>
-           <property name="sizeHint" stdset="0">
-            <size>
-             <width>40</width>
-             <height>20</height>
-            </size>
-           </property>
-          </spacer>
-         </item>
-         <item>
-          <widget class="QPushButton" name="slicePb">
-           <property name="text">
-            <string>Time slicing:</string>
-           </property>
-          </widget>
-         </item>
-         <item>
-          <widget class="QLineEdit" name="sliceEvent">
-           <property name="toolTip">
-            <string>Define the slices for the event. Valid inputs: min-max, start:step:stop, &gt;min, &lt;max. Combinations of those as well.</string>
-           </property>
-          </widget>
-         </item>
-         <item>
-          <spacer name="horizontalSpacer_4">
-           <property name="orientation">
-            <enum>Qt::Horizontal</enum>
-           </property>
-           <property name="sizeHint" stdset="0">
-            <size>
-             <width>0</width>
-             <height>0</height>
-            </size>
-           </property>
-          </spacer>
-         </item>
-         <item>
-          <widget class="QLabel" name="label_34">
-           <property name="text">
-            <string>Instrument:</string>
-           </property>
-          </widget>
-         </item>
-         <item>
-          <widget class="QComboBox" name="inst_opt"/>
-         </item>
-        </layout>
-       </item>
-       <item row="2" column="0" colspan="2">
-        <widget class="Line" name="line_2">
-         <property name="orientation">
-          <enum>Qt::Horizontal</enum>
-         </property>
-        </widget>
-       </item>
-       <item row="3" column="0" colspan="2">
-        <widget class="QStackedWidget" name="mode_stack">
-         <property name="lineWidth">
-          <number>0</number>
-         </property>
-         <property name="currentIndex">
-          <number>0</number>
-         </property>
-         <widget class="QWidget" name="page_5">
-          <layout class="QVBoxLayout" name="verticalLayout_9">
+        </item>
+        <item row="1" column="0">
+         <widget class="QGroupBox" name="groupBox_16">
+          <property name="title">
+           <string/>
+          </property>
+          <layout class="QHBoxLayout" name="horizontalLayout_2">
            <item>
-            <layout class="QHBoxLayout" name="horizontalLayout_14">
-             <property name="sizeConstraint">
-              <enum>QLayout::SetNoConstraint</enum>
+            <widget class="QRadioButton" name="single_mode_btn">
+             <property name="text">
+              <string>Single run mode</string>
              </property>
-             <item>
-              <widget class="QGroupBox" name="groupbox">
-               <property name="sizePolicy">
-                <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
-                 <horstretch>0</horstretch>
-                 <verstretch>0</verstretch>
-                </sizepolicy>
-               </property>
-               <property name="minimumSize">
-                <size>
-                 <width>0</width>
-                 <height>0</height>
-                </size>
-               </property>
-               <property name="title">
-                <string>Scattering</string>
-               </property>
-               <layout class="QGridLayout" name="gridLayout_10">
-                <item row="0" column="0">
-                 <widget class="MantidQt::MantidWidgets::MWRunFiles" name="scatterSample" native="true">
-                  <property name="toolTip">
-                   <string>The run with the sample under investigation</string>
-                  </property>
-                  <property name="label" stdset="0">
-                   <string>Sample</string>
-                  </property>
-                  <property name="multipleFiles" stdset="0">
-                   <bool>false</bool>
-                  </property>
-                  <property name="multiEntry" stdset="0">
-                   <bool>false</bool>
-                  </property>
-                 </widget>
-                </item>
-                <item row="1" column="0">
-                 <widget class="MantidQt::MantidWidgets::MWRunFiles" name="scatCan" native="true">
-                  <property name="toolTip">
-                   <string>The run with the sample under investigation</string>
-                  </property>
-                  <property name="label" stdset="0">
-                   <string>Can     </string>
-                  </property>
-                  <property name="multipleFiles" stdset="0">
-                   <bool>false</bool>
-                  </property>
-                  <property name="optional" stdset="0">
-                   <bool>true</bool>
-                  </property>
-                  <property name="multiEntry" stdset="0">
-                   <bool>false</bool>
-                  </property>
-                 </widget>
-                </item>
-               </layout>
-              </widget>
-             </item>
-             <item>
-              <spacer name="horizontalSpacer_9">
-               <property name="orientation">
-                <enum>Qt::Horizontal</enum>
-               </property>
-               <property name="sizeHint" stdset="0">
-                <size>
-                 <width>40</width>
-                 <height>20</height>
-                </size>
-               </property>
-              </spacer>
-             </item>
-             <item>
-              <widget class="QGroupBox" name="groupBox">
-               <property name="title">
-                <string>Transmission</string>
-               </property>
-               <layout class="QGridLayout" name="gridLayout_11">
-                <item row="0" column="0">
-                 <widget class="MantidQt::MantidWidgets::MWRunFiles" name="transmis" native="true">
-                  <property name="toolTip">
-                   <string>The run with the sample under investigation</string>
-                  </property>
-                  <property name="label" stdset="0">
-                   <string>Sample</string>
-                  </property>
-                  <property name="multipleFiles" stdset="0">
-                   <bool>false</bool>
-                  </property>
-                  <property name="optional" stdset="0">
-                   <bool>true</bool>
-                  </property>
-                  <property name="multiEntry" stdset="0">
-                   <bool>false</bool>
-                  </property>
-                 </widget>
-                </item>
-                <item row="1" column="0">
-                 <widget class="MantidQt::MantidWidgets::MWRunFiles" name="transCan" native="true">
-                  <property name="toolTip">
-                   <string>The run with the sample under investigation</string>
-                  </property>
-                  <property name="label" stdset="0">
-                   <string>Can     </string>
-                  </property>
-                  <property name="multipleFiles" stdset="0">
-                   <bool>false</bool>
-                  </property>
-                  <property name="optional" stdset="0">
-                   <bool>true</bool>
-                  </property>
-                  <property name="multiEntry" stdset="0">
-                   <bool>false</bool>
-                  </property>
-                 </widget>
-                </item>
-               </layout>
-              </widget>
-             </item>
-             <item>
-              <spacer name="horizontalSpacer_10">
-               <property name="orientation">
-                <enum>Qt::Horizontal</enum>
-               </property>
-               <property name="sizeHint" stdset="0">
-                <size>
-                 <width>40</width>
-                 <height>20</height>
-                </size>
-               </property>
-              </spacer>
-             </item>
-             <item>
-              <widget class="QGroupBox" name="groupBox_2">
-               <property name="title">
-                <string>Direct</string>
-               </property>
-               <layout class="QGridLayout" name="gridLayout_12">
-                <item row="0" column="0">
-                 <widget class="MantidQt::MantidWidgets::MWRunFiles" name="direct" native="true">
-                  <property name="toolTip">
-                   <string>The run with the sample under investigation</string>
-                  </property>
-                  <property name="label" stdset="0">
-                   <string>Sample</string>
-                  </property>
-                  <property name="multipleFiles" stdset="0">
-                   <bool>false</bool>
-                  </property>
-                  <property name="optional" stdset="0">
-                   <bool>true</bool>
-                  </property>
-                  <property name="multiEntry" stdset="0">
-                   <bool>false</bool>
-                  </property>
-                 </widget>
-                </item>
-                <item row="1" column="0">
-                 <widget class="MantidQt::MantidWidgets::MWRunFiles" name="dirCan" native="true">
-                  <property name="toolTip">
-                   <string>The run with the sample under investigation</string>
-                  </property>
-                  <property name="label" stdset="0">
-                   <string>Can     </string>
-                  </property>
-                  <property name="multipleFiles" stdset="0">
-                   <bool>false</bool>
-                  </property>
-                  <property name="optional" stdset="0">
-                   <bool>true</bool>
-                  </property>
-                  <property name="multiEntry" stdset="0">
-                   <bool>false</bool>
-                  </property>
-                 </widget>
-                </item>
-               </layout>
-              </widget>
-             </item>
-            </layout>
+             <property name="checked">
+              <bool>true</bool>
+             </property>
+            </widget>
+           </item>
+           <item>
+            <widget class="QRadioButton" name="batch_mode_btn">
+             <property name="enabled">
+              <bool>true</bool>
+             </property>
+             <property name="text">
+              <string>Batch mode</string>
+             </property>
+            </widget>
            </item>
           </layout>
          </widget>
-         <widget class="QWidget" name="page_6">
-          <layout class="QVBoxLayout" name="verticalLayout_5">
-           <item>
-            <layout class="QHBoxLayout" name="horizontalLayout_9">
-             <item>
-              <widget class="QLabel" name="label_13">
-               <property name="sizePolicy">
-                <sizepolicy hsizetype="Preferred" vsizetype="Maximum">
-                 <horstretch>0</horstretch>
-                 <verstretch>0</verstretch>
-                </sizepolicy>
-               </property>
-               <property name="text">
-                <string>CSV File</string>
-               </property>
-              </widget>
-             </item>
-             <item>
-              <widget class="QLineEdit" name="csv_filename">
-               <property name="sizePolicy">
-                <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
-                 <horstretch>0</horstretch>
-                 <verstretch>0</verstretch>
-                </sizepolicy>
-               </property>
-               <property name="minimumSize">
-                <size>
-                 <width>200</width>
-                 <height>0</height>
-                </size>
-               </property>
-              </widget>
-             </item>
-             <item>
-              <widget class="QPushButton" name="csv_browse_btn">
-               <property name="text">
-                <string>Browse</string>
-               </property>
-              </widget>
-             </item>
-             <item>
-              <spacer name="horizontalSpacer_17">
-               <property name="orientation">
-                <enum>Qt::Horizontal</enum>
-               </property>
-               <property name="sizeHint" stdset="0">
-                <size>
-                 <width>40</width>
-                 <height>20</height>
-                </size>
-               </property>
-              </spacer>
-             </item>
-             <item>
-              <widget class="QLabel" name="label_26">
-               <property name="text">
-                <string>Run file type:</string>
-               </property>
-              </widget>
-             </item>
-             <item>
-              <widget class="QComboBox" name="file_opt"/>
-             </item>
-            </layout>
-           </item>
-           <item>
-            <spacer name="verticalSpacer_6">
-             <property name="orientation">
-              <enum>Qt::Vertical</enum>
-             </property>
-             <property name="sizeHint" stdset="0">
-              <size>
-               <width>20</width>
-               <height>40</height>
-              </size>
-             </property>
-            </spacer>
-           </item>
-           <item>
-            <widget class="QTableWidget" name="batch_table">
-             <property name="editTriggers">
-              <set>QAbstractItemView::NoEditTriggers</set>
-             </property>
-             <property name="selectionMode">
-              <enum>QAbstractItemView::MultiSelection</enum>
-             </property>
-             <property name="selectionBehavior">
-              <enum>QAbstractItemView::SelectRows</enum>
-             </property>
-             <property name="textElideMode">
-              <enum>Qt::ElideRight</enum>
-             </property>
-             <column>
-              <property name="text">
-               <string>Sans Sample</string>
+        </item>
+        <item row="1" column="1">
+         <layout class="QHBoxLayout" name="horizontalLayout_16">
+          <item>
+           <widget class="QCheckBox" name="allowPeriods_ck">
+            <property name="toolTip">
+             <string>Show the multi-period entry boxes</string>
+            </property>
+            <property name="text">
+             <string>Multi-period</string>
+            </property>
+           </widget>
+          </item>
+          <item>
+           <spacer name="horizontalSpacer_16">
+            <property name="orientation">
+             <enum>Qt::Horizontal</enum>
+            </property>
+            <property name="sizeHint" stdset="0">
+             <size>
+              <width>40</width>
+              <height>20</height>
+             </size>
+            </property>
+           </spacer>
+          </item>
+          <item>
+           <widget class="QPushButton" name="slicePb">
+            <property name="text">
+             <string>Time slicing:</string>
+            </property>
+           </widget>
+          </item>
+          <item>
+           <widget class="QLineEdit" name="sliceEvent">
+            <property name="toolTip">
+             <string>Define the slices for the event. Valid inputs: min-max, start:step:stop, &gt;min, &lt;max. Combinations of those as well.</string>
+            </property>
+           </widget>
+          </item>
+          <item>
+           <spacer name="horizontalSpacer_4">
+            <property name="orientation">
+             <enum>Qt::Horizontal</enum>
+            </property>
+            <property name="sizeHint" stdset="0">
+             <size>
+              <width>0</width>
+              <height>0</height>
+             </size>
+            </property>
+           </spacer>
+          </item>
+          <item>
+           <widget class="QLabel" name="label_34">
+            <property name="text">
+             <string>Instrument:</string>
+            </property>
+           </widget>
+          </item>
+          <item>
+           <widget class="QComboBox" name="inst_opt"/>
+          </item>
+         </layout>
+        </item>
+        <item row="2" column="0" colspan="2">
+         <widget class="Line" name="line_2">
+          <property name="orientation">
+           <enum>Qt::Horizontal</enum>
+          </property>
+         </widget>
+        </item>
+        <item row="3" column="0" colspan="2">
+         <widget class="QStackedWidget" name="mode_stack">
+          <property name="lineWidth">
+           <number>0</number>
+          </property>
+          <property name="currentIndex">
+           <number>0</number>
+          </property>
+          <widget class="QWidget" name="page_5">
+           <layout class="QVBoxLayout" name="verticalLayout_9">
+            <item>
+             <layout class="QHBoxLayout" name="horizontalLayout_14">
+              <property name="sizeConstraint">
+               <enum>QLayout::SetNoConstraint</enum>
               </property>
-             </column>
-             <column>
-              <property name="text">
-               <string>Trans Sample</string>
+              <item>
+               <widget class="QGroupBox" name="groupbox">
+                <property name="sizePolicy">
+                 <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+                  <horstretch>0</horstretch>
+                  <verstretch>0</verstretch>
+                 </sizepolicy>
+                </property>
+                <property name="minimumSize">
+                 <size>
+                  <width>0</width>
+                  <height>0</height>
+                 </size>
+                </property>
+                <property name="title">
+                 <string>Scattering</string>
+                </property>
+                <layout class="QGridLayout" name="gridLayout_10">
+                 <item row="0" column="0">
+                  <widget class="MantidQt::MantidWidgets::MWRunFiles" name="scatterSample" native="true">
+                   <property name="toolTip">
+                    <string>The run with the sample under investigation</string>
+                   </property>
+                   <property name="label" stdset="0">
+                    <string>Sample</string>
+                   </property>
+                   <property name="multipleFiles" stdset="0">
+                    <bool>false</bool>
+                   </property>
+                   <property name="multiEntry" stdset="0">
+                    <bool>false</bool>
+                   </property>
+                  </widget>
+                 </item>
+                 <item row="1" column="0">
+                  <widget class="MantidQt::MantidWidgets::MWRunFiles" name="scatCan" native="true">
+                   <property name="toolTip">
+                    <string>The run with the sample under investigation</string>
+                   </property>
+                   <property name="label" stdset="0">
+                    <string>Can     </string>
+                   </property>
+                   <property name="multipleFiles" stdset="0">
+                    <bool>false</bool>
+                   </property>
+                   <property name="optional" stdset="0">
+                    <bool>true</bool>
+                   </property>
+                   <property name="multiEntry" stdset="0">
+                    <bool>false</bool>
+                   </property>
+                  </widget>
+                 </item>
+                </layout>
+               </widget>
+              </item>
+              <item>
+               <spacer name="horizontalSpacer_9">
+                <property name="orientation">
+                 <enum>Qt::Horizontal</enum>
+                </property>
+                <property name="sizeHint" stdset="0">
+                 <size>
+                  <width>40</width>
+                  <height>20</height>
+                 </size>
+                </property>
+               </spacer>
+              </item>
+              <item>
+               <widget class="QGroupBox" name="groupBox">
+                <property name="title">
+                 <string>Transmission</string>
+                </property>
+                <layout class="QGridLayout" name="gridLayout_11">
+                 <item row="0" column="0">
+                  <widget class="MantidQt::MantidWidgets::MWRunFiles" name="transmis" native="true">
+                   <property name="toolTip">
+                    <string>The run with the sample under investigation</string>
+                   </property>
+                   <property name="label" stdset="0">
+                    <string>Sample</string>
+                   </property>
+                   <property name="multipleFiles" stdset="0">
+                    <bool>false</bool>
+                   </property>
+                   <property name="optional" stdset="0">
+                    <bool>true</bool>
+                   </property>
+                   <property name="multiEntry" stdset="0">
+                    <bool>false</bool>
+                   </property>
+                  </widget>
+                 </item>
+                 <item row="1" column="0">
+                  <widget class="MantidQt::MantidWidgets::MWRunFiles" name="transCan" native="true">
+                   <property name="toolTip">
+                    <string>The run with the sample under investigation</string>
+                   </property>
+                   <property name="label" stdset="0">
+                    <string>Can     </string>
+                   </property>
+                   <property name="multipleFiles" stdset="0">
+                    <bool>false</bool>
+                   </property>
+                   <property name="optional" stdset="0">
+                    <bool>true</bool>
+                   </property>
+                   <property name="multiEntry" stdset="0">
+                    <bool>false</bool>
+                   </property>
+                  </widget>
+                 </item>
+                </layout>
+               </widget>
+              </item>
+              <item>
+               <spacer name="horizontalSpacer_10">
+                <property name="orientation">
+                 <enum>Qt::Horizontal</enum>
+                </property>
+                <property name="sizeHint" stdset="0">
+                 <size>
+                  <width>40</width>
+                  <height>20</height>
+                 </size>
+                </property>
+               </spacer>
+              </item>
+              <item>
+               <widget class="QGroupBox" name="groupBox_2">
+                <property name="title">
+                 <string>Direct</string>
+                </property>
+                <layout class="QGridLayout" name="gridLayout_12">
+                 <item row="0" column="0">
+                  <widget class="MantidQt::MantidWidgets::MWRunFiles" name="direct" native="true">
+                   <property name="toolTip">
+                    <string>The run with the sample under investigation</string>
+                   </property>
+                   <property name="label" stdset="0">
+                    <string>Sample</string>
+                   </property>
+                   <property name="multipleFiles" stdset="0">
+                    <bool>false</bool>
+                   </property>
+                   <property name="optional" stdset="0">
+                    <bool>true</bool>
+                   </property>
+                   <property name="multiEntry" stdset="0">
+                    <bool>false</bool>
+                   </property>
+                  </widget>
+                 </item>
+                 <item row="1" column="0">
+                  <widget class="MantidQt::MantidWidgets::MWRunFiles" name="dirCan" native="true">
+                   <property name="toolTip">
+                    <string>The run with the sample under investigation</string>
+                   </property>
+                   <property name="label" stdset="0">
+                    <string>Can     </string>
+                   </property>
+                   <property name="multipleFiles" stdset="0">
+                    <bool>false</bool>
+                   </property>
+                   <property name="optional" stdset="0">
+                    <bool>true</bool>
+                   </property>
+                   <property name="multiEntry" stdset="0">
+                    <bool>false</bool>
+                   </property>
+                  </widget>
+                 </item>
+                </layout>
+               </widget>
+              </item>
+             </layout>
+            </item>
+           </layout>
+          </widget>
+          <widget class="QWidget" name="page_6">
+           <layout class="QVBoxLayout" name="verticalLayout_5">
+            <item>
+             <layout class="QHBoxLayout" name="horizontalLayout_9">
+              <item>
+               <widget class="QLabel" name="label_13">
+                <property name="sizePolicy">
+                 <sizepolicy hsizetype="Preferred" vsizetype="Maximum">
+                  <horstretch>0</horstretch>
+                  <verstretch>0</verstretch>
+                 </sizepolicy>
+                </property>
+                <property name="text">
+                 <string>CSV File</string>
+                </property>
+               </widget>
+              </item>
+              <item>
+               <widget class="QLineEdit" name="csv_filename">
+                <property name="sizePolicy">
+                 <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
+                  <horstretch>0</horstretch>
+                  <verstretch>0</verstretch>
+                 </sizepolicy>
+                </property>
+                <property name="minimumSize">
+                 <size>
+                  <width>200</width>
+                  <height>0</height>
+                 </size>
+                </property>
+               </widget>
+              </item>
+              <item>
+               <widget class="QPushButton" name="csv_browse_btn">
+                <property name="text">
+                 <string>Browse</string>
+                </property>
+               </widget>
+              </item>
+              <item>
+               <spacer name="horizontalSpacer_17">
+                <property name="orientation">
+                 <enum>Qt::Horizontal</enum>
+                </property>
+                <property name="sizeHint" stdset="0">
+                 <size>
+                  <width>40</width>
+                  <height>20</height>
+                 </size>
+                </property>
+               </spacer>
+              </item>
+              <item>
+               <widget class="QLabel" name="label_26">
+                <property name="text">
+                 <string>Run file type:</string>
+                </property>
+               </widget>
+              </item>
+              <item>
+               <widget class="QComboBox" name="file_opt"/>
+              </item>
+             </layout>
+            </item>
+            <item>
+             <spacer name="verticalSpacer_6">
+              <property name="orientation">
+               <enum>Qt::Vertical</enum>
               </property>
-             </column>
-             <column>
-              <property name="text">
-               <string>Direct Sample</string>
+              <property name="sizeHint" stdset="0">
+               <size>
+                <width>20</width>
+                <height>40</height>
+               </size>
               </property>
-             </column>
-             <column>
-              <property name="text">
-               <string>Sans Can</string>
+             </spacer>
+            </item>
+            <item>
+             <widget class="QTableWidget" name="batch_table">
+              <property name="editTriggers">
+               <set>QAbstractItemView::NoEditTriggers</set>
               </property>
-             </column>
-             <column>
-              <property name="text">
-               <string>Trans Can</string>
+              <property name="selectionMode">
+               <enum>QAbstractItemView::MultiSelection</enum>
               </property>
-             </column>
-             <column>
-              <property name="text">
-               <string>Direct Can</string>
+              <property name="selectionBehavior">
+               <enum>QAbstractItemView::SelectRows</enum>
               </property>
-             </column>
-             <column>
-              <property name="text">
-               <string>Output Name</string>
+              <property name="textElideMode">
+               <enum>Qt::ElideRight</enum>
               </property>
-             </column>
-            </widget>
-           </item>
-          </layout>
-         </widget>
-        </widget>
-       </item>
-       <item row="4" column="0" colspan="2">
-        <layout class="QGridLayout" name="gridLayout_44">
-         <item row="0" column="0">
-          <widget class="QGroupBox" name="groupBox_4">
-           <property name="title">
-            <string>Options</string>
-           </property>
-           <layout class="QGridLayout" name="gridLayout_20">
-            <item row="0" column="1">
-             <widget class="QCheckBox" name="verbose_check">
-              <property name="text">
-               <string>Verbose</string>
-              </property>
-             </widget>
-            </item>
-            <item row="0" column="2">
-             <widget class="QCheckBox" name="log_colette">
-              <property name="text">
-               <string>Log Colette cmds</string>
-              </property>
-             </widget>
-            </item>
-            <item row="0" column="0">
-             <widget class="QCheckBox" name="plot_check">
-              <property name="text">
-               <string>Plot Result</string>
-              </property>
-             </widget>
-            </item>
-           </layout>
-          </widget>
-         </item>
-         <item row="1" column="0">
-          <widget class="QGroupBox" name="groupBox_7">
-           <property name="title">
-            <string>Reduce</string>
-           </property>
-           <property name="flat">
-            <bool>false</bool>
-           </property>
-           <layout class="QGridLayout" name="gridLayout_19">
-            <item row="0" column="0">
-             <widget class="QPushButton" name="load_dataBtn">
-              <property name="text">
-               <string>Load Data</string>
-              </property>
-             </widget>
-            </item>
-            <item row="0" column="1">
-             <widget class="QPushButton" name="oneDBtn">
-              <property name="text">
-               <string>1D Reduce</string>
-              </property>
-             </widget>
-            </item>
-            <item row="0" column="2">
-             <widget class="QPushButton" name="twoDBtn">
-              <property name="text">
-               <string>2D Reduce</string>
-              </property>
-             </widget>
-            </item>
-           </layout>
-          </widget>
-         </item>
-         <item row="0" column="1" rowspan="2">
-          <widget class="QGroupBox" name="groupBox_5">
-           <property name="title">
-            <string>Save</string>
-           </property>
-           <layout class="QGridLayout" name="gridLayout">
-            <item row="0" column="5" rowspan="2">
-             <widget class="QPushButton" name="saveFilename_btn">
-              <property name="minimumSize">
-               <size>
-                <width>0</width>
-                <height>0</height>
-               </size>
-              </property>
-              <property name="toolTip">
-               <string>Save the output workspace to this file</string>
-              </property>
-              <property name="text">
-               <string>Browse</string>
-              </property>
-             </widget>
-            </item>
-            <item row="3" column="5">
-             <widget class="QCheckBox" name="saveCSV_check">
-              <property name="toolTip">
-               <string>Select one or more file formats</string>
-              </property>
-              <property name="text">
-               <string>CSV</string>
-              </property>
-             </widget>
-            </item>
-            <item row="3" column="4">
-             <widget class="QCheckBox" name="saveRKH_check">
-              <property name="toolTip">
-               <string>Select one or more file formats</string>
-              </property>
-              <property name="text">
-               <string>RKH</string>
-              </property>
-             </widget>
-            </item>
-            <item row="3" column="3">
-             <widget class="QCheckBox" name="saveCan_check">
-              <property name="toolTip">
-               <string>Select one or more file formats</string>
-              </property>
-              <property name="text">
-               <string>CanSAS</string>
-              </property>
-             </widget>
-            </item>
-            <item row="3" column="1">
-             <widget class="QCheckBox" name="saveNex_check">
-              <property name="toolTip">
-               <string>Select one or more file formats</string>
-              </property>
-              <property name="text">
-               <string>Nexus</string>
-              </property>
-             </widget>
-            </item>
-            <item row="0" column="0" rowspan="2">
-             <widget class="QLabel" name="label_58">
-              <property name="toolTip">
-               <string>Save the output workspace to this file</string>
-              </property>
-              <property name="text">
-               <string>Filename:</string>
-              </property>
-             </widget>
-            </item>
-            <item row="2" column="0" rowspan="2">
-             <widget class="QLabel" name="label_64">
-              <property name="toolTip">
-               <string>Select one or more file formats</string>
-              </property>
-              <property name="text">
-               <string>Formats:</string>
-              </property>
-             </widget>
-            </item>
-            <item row="4" column="1" colspan="2">
-             <widget class="QPushButton" name="saveDefault_btn">
-              <property name="toolTip">
-               <string>Save the workspace from a single run file reduction</string>
-              </property>
-              <property name="text">
-               <string>Save Result</string>
-              </property>
-             </widget>
-            </item>
-            <item row="1" column="1" colspan="4">
-             <widget class="QLineEdit" name="outfile_edit">
-              <property name="toolTip">
-               <string>Save the output workspace to this file</string>
-              </property>
-             </widget>
-            </item>
-            <item row="4" column="4" colspan="2">
-             <widget class="QPushButton" name="saveSel_btn">
-              <property name="toolTip">
-               <string>Save multiple workspaces</string>
-              </property>
-              <property name="text">
-               <string>Save Other</string>
-              </property>
-             </widget>
-            </item>
-            <item row="3" column="2">
-             <widget class="QCheckBox" name="saveNIST_Qxy_check">
-              <property name="text">
-               <string>NIST Qxy</string>
-              </property>
-             </widget>
-            </item>
-           </layout>
-          </widget>
-         </item>
-        </layout>
-       </item>
-      </layout>
-     </widget>
-     <widget class="QWidget" name="tab_2">
-      <attribute name="title">
-       <string>Reduction Settings</string>
-      </attribute>
-      <layout class="QGridLayout" name="gridLayout_13">
-       <item row="0" column="0">
-        <layout class="QHBoxLayout" name="horizontalLayout">
-         <item>
-          <widget class="QLabel" name="label_23">
-           <property name="text">
-            <string>Account for gravity</string>
-           </property>
-           <property name="alignment">
-            <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
-           </property>
-          </widget>
-         </item>
-         <item>
-          <widget class="QCheckBox" name="gravity_check">
-           <property name="text">
-            <string/>
-           </property>
-          </widget>
-         </item>
-         <item>
-          <spacer name="horizontalSpacer">
-           <property name="orientation">
-            <enum>Qt::Horizontal</enum>
-           </property>
-           <property name="sizeHint" stdset="0">
-            <size>
-             <width>40</width>
-             <height>20</height>
-            </size>
-           </property>
-          </spacer>
-         </item>
-        </layout>
-       </item>
-       <item row="1" column="0" rowspan="2">
-        <layout class="QHBoxLayout" name="horizontalLayout_4">
-         <item>
-          <widget class="QGroupBox" name="limits_group">
-           <property name="sizePolicy">
-            <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
-             <horstretch>0</horstretch>
-             <verstretch>0</verstretch>
-            </sizepolicy>
-           </property>
-           <property name="layoutDirection">
-            <enum>Qt::LeftToRight</enum>
-           </property>
-           <property name="title">
-            <string>Limits</string>
-           </property>
-           <property name="checkable">
-            <bool>false</bool>
-           </property>
-           <layout class="QGridLayout" name="gridLayout_4">
-            <property name="verticalSpacing">
-             <number>5</number>
-            </property>
-            <item row="0" column="0">
-             <spacer name="horizontalSpacer_2">
-              <property name="orientation">
-               <enum>Qt::Horizontal</enum>
-              </property>
-              <property name="sizeHint" stdset="0">
-               <size>
-                <width>40</width>
-                <height>20</height>
-               </size>
-              </property>
-             </spacer>
-            </item>
-            <item row="0" column="1">
-             <widget class="QLabel" name="limits_min_lbl">
-              <property name="sizePolicy">
-               <sizepolicy hsizetype="Preferred" vsizetype="Maximum">
-                <horstretch>0</horstretch>
-                <verstretch>0</verstretch>
-               </sizepolicy>
-              </property>
-              <property name="text">
-               <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
-&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
-p, li { white-space: pre-wrap; }
-&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;
-&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:8pt;&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;Min&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
-              </property>
-              <property name="alignment">
-               <set>Qt::AlignCenter</set>
-              </property>
-             </widget>
-            </item>
-            <item row="0" column="2">
-             <widget class="QLabel" name="limits_max_lbl">
-              <property name="sizePolicy">
-               <sizepolicy hsizetype="Preferred" vsizetype="Maximum">
-                <horstretch>0</horstretch>
-                <verstretch>0</verstretch>
-               </sizepolicy>
-              </property>
-              <property name="text">
-               <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
-&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
-p, li { white-space: pre-wrap; }
-&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;
-&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:8pt;&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;Max&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
-              </property>
-              <property name="alignment">
-               <set>Qt::AlignCenter</set>
-              </property>
-             </widget>
-            </item>
-            <item row="1" column="0">
-             <widget class="QLabel" name="label_3">
-              <property name="text">
-               <string>Radius (mm)</string>
-              </property>
-             </widget>
-            </item>
-            <item row="1" column="1">
-             <widget class="QLineEdit" name="rad_min">
-              <property name="sizePolicy">
-               <sizepolicy hsizetype="Preferred" vsizetype="Maximum">
-                <horstretch>0</horstretch>
-                <verstretch>0</verstretch>
-               </sizepolicy>
-              </property>
-              <property name="maximumSize">
-               <size>
-                <width>70</width>
-                <height>16777215</height>
-               </size>
-              </property>
-             </widget>
-            </item>
-            <item row="1" column="2">
-             <widget class="QLineEdit" name="rad_max">
-              <property name="sizePolicy">
-               <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
-                <horstretch>0</horstretch>
-                <verstretch>0</verstretch>
-               </sizepolicy>
-              </property>
-              <property name="maximumSize">
-               <size>
-                <width>70</width>
-                <height>16777215</height>
-               </size>
-              </property>
-             </widget>
-            </item>
-            <item row="3" column="0">
-             <widget class="QLabel" name="wavlength_lb">
-              <property name="toolTip">
-               <string>Controls the output from convert to wavelength</string>
-              </property>
-              <property name="text">
-               <string>Wavelength (A)</string>
-              </property>
-             </widget>
-            </item>
-            <item row="3" column="1" colspan="2">
-             <widget class="QStackedWidget" name="wav_stack">
-              <property name="autoFillBackground">
-               <bool>false</bool>
-              </property>
-              <property name="lineWidth">
-               <number>1</number>
-              </property>
-              <property name="currentIndex">
-               <number>0</number>
-              </property>
-              <widget class="QWidget" name="page_7">
-               <layout class="QGridLayout" name="gridLayout_21">
-                <property name="margin">
-                 <number>0</number>
-                </property>
-                <item row="0" column="1">
-                 <widget class="QLineEdit" name="wav_min">
-                  <property name="sizePolicy">
-                   <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
-                    <horstretch>0</horstretch>
-                    <verstretch>0</verstretch>
-                   </sizepolicy>
-                  </property>
-                  <property name="maximumSize">
-                   <size>
-                    <width>70</width>
-                    <height>16777215</height>
-                   </size>
-                  </property>
-                  <property name="toolTip">
-                   <string>Start and end wavelengths used by convert to wavelengh</string>
-                  </property>
-                 </widget>
-                </item>
-                <item row="0" column="2">
-                 <widget class="QLineEdit" name="wav_max">
-                  <property name="sizePolicy">
-                   <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
-                    <horstretch>0</horstretch>
-                    <verstretch>0</verstretch>
-                   </sizepolicy>
-                  </property>
-                  <property name="maximumSize">
-                   <size>
-                    <width>70</width>
-                    <height>16777215</height>
-                   </size>
-                  </property>
-                 </widget>
-                </item>
-               </layout>
-              </widget>
-              <widget class="QWidget" name="page_8">
-               <layout class="QHBoxLayout" name="horizontalLayout_18">
-                <property name="margin">
-                 <number>0</number>
-                </property>
-                <item>
-                 <widget class="QLineEdit" name="wavRanges">
-                  <property name="toolTip">
-                   <string>Comma separated list of wavelength ranges. One reduction
-will always be done between the first and last ranges the
-intermediate ranges are there for comparison</string>
-                  </property>
-                 </widget>
-                </item>
-                <item>
-                 <widget class="QLabel" name="wavRanVal_lb">
-                  <property name="text">
-                   <string>*</string>
-                  </property>
-                  <property name="textFormat">
-                   <enum>Qt::AutoText</enum>
-                  </property>
-                 </widget>
-                </item>
-               </layout>
-              </widget>
-             </widget>
-            </item>
-            <item row="3" column="3">
-             <widget class="QLabel" name="wav_step_lbl">
-              <property name="text">
-               <string>step</string>
-              </property>
-             </widget>
-            </item>
-            <item row="3" column="4">
-             <widget class="QLineEdit" name="wav_dw">
-              <property name="sizePolicy">
-               <sizepolicy hsizetype="Maximum" vsizetype="Maximum">
-                <horstretch>0</horstretch>
-                <verstretch>0</verstretch>
-               </sizepolicy>
-              </property>
-              <property name="maximumSize">
-               <size>
-                <width>70</width>
-                <height>16777215</height>
-               </size>
-              </property>
-              <property name="toolTip">
-               <string>The bin width of the output from convert to wavelength</string>
-              </property>
-             </widget>
-            </item>
-            <item row="3" column="5">
-             <widget class="QComboBox" name="wav_dw_opt">
-              <property name="sizePolicy">
-               <sizepolicy hsizetype="Maximum" vsizetype="Maximum">
-                <horstretch>0</horstretch>
-                <verstretch>0</verstretch>
-               </sizepolicy>
-              </property>
-              <property name="minimumSize">
-               <size>
-                <width>0</width>
-                <height>0</height>
-               </size>
-              </property>
-              <property name="toolTip">
-               <string>Use Plot Result (in first tab) to check overlapping</string>
-              </property>
-              <item>
+              <column>
                <property name="text">
-                <string>Linear</string>
+                <string>Sans Sample</string>
                </property>
-              </item>
-              <item>
+              </column>
+              <column>
                <property name="text">
-                <string>Logarithmic</string>
+                <string>Trans Sample</string>
                </property>
-              </item>
-              <item>
+              </column>
+              <column>
                <property name="text">
-                <string>Ranges Lin</string>
+                <string>Direct Sample</string>
                </property>
-              </item>
-              <item>
+              </column>
+              <column>
                <property name="text">
-                <string>Ranges Log</string>
+                <string>Sans Can</string>
                </property>
-              </item>
-             </widget>
-            </item>
-            <item row="4" column="0" colspan="5">
-             <widget class="QStackedWidget" name="q_stack">
-              <property name="autoFillBackground">
-               <bool>false</bool>
-              </property>
-              <property name="lineWidth">
-               <number>1</number>
-              </property>
-              <property name="currentIndex">
-               <number>0</number>
-              </property>
-              <widget class="QWidget" name="page_2">
-               <layout class="QGridLayout" name="gridLayout_16">
-                <property name="margin">
-                 <number>0</number>
-                </property>
-                <item row="0" column="2">
-                 <widget class="QLineEdit" name="q_min">
-                  <property name="sizePolicy">
-                   <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
-                    <horstretch>0</horstretch>
-                    <verstretch>0</verstretch>
-                   </sizepolicy>
-                  </property>
-                  <property name="maximumSize">
-                   <size>
-                    <width>70</width>
-                    <height>16777215</height>
-                   </size>
-                  </property>
-                 </widget>
-                </item>
-                <item row="0" column="3">
-                 <widget class="QLineEdit" name="q_max">
-                  <property name="sizePolicy">
-                   <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
-                    <horstretch>0</horstretch>
-                    <verstretch>0</verstretch>
-                   </sizepolicy>
-                  </property>
-                  <property name="maximumSize">
-                   <size>
-                    <width>70</width>
-                    <height>16777215</height>
-                   </size>
-                  </property>
-                 </widget>
-                </item>
-                <item row="0" column="4">
-                 <widget class="QLabel" name="q_step_lbl">
-                  <property name="text">
-                   <string>stepping</string>
-                  </property>
-                 </widget>
-                </item>
-                <item row="0" column="5">
-                 <widget class="QLineEdit" name="q_dq">
-                  <property name="sizePolicy">
-                   <sizepolicy hsizetype="Maximum" vsizetype="Maximum">
-                    <horstretch>0</horstretch>
-                    <verstretch>0</verstretch>
-                   </sizepolicy>
-                  </property>
-                  <property name="maximumSize">
-                   <size>
-                    <width>70</width>
-                    <height>16777215</height>
-                   </size>
-                  </property>
-                 </widget>
-                </item>
-                <item row="0" column="1">
-                 <widget class="QLabel" name="qx_lb">
-                  <property name="sizePolicy">
-                   <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
-                    <horstretch>0</horstretch>
-                    <verstretch>0</verstretch>
-                   </sizepolicy>
-                  </property>
-                  <property name="minimumSize">
-                   <size>
-                    <width>120</width>
-                    <height>0</height>
-                   </size>
-                  </property>
-                  <property name="text">
-                   <string>Qx (A^-1)</string>
-                  </property>
-                 </widget>
-                </item>
-               </layout>
-              </widget>
-              <widget class="QWidget" name="page_4">
-               <layout class="QHBoxLayout" name="horizontalLayout_17">
-                <property name="margin">
-                 <number>0</number>
-                </property>
-                <item>
-                 <widget class="QLabel" name="label_37">
-                  <property name="minimumSize">
-                   <size>
-                    <width>120</width>
-                    <height>0</height>
-                   </size>
-                  </property>
-                  <property name="text">
-                   <string>Qx (Ã…^-1)</string>
-                  </property>
-                 </widget>
-                </item>
-                <item>
-                 <widget class="QLineEdit" name="q_rebin"/>
-                </item>
-               </layout>
-              </widget>
-             </widget>
-            </item>
-            <item row="4" column="5">
-             <widget class="QComboBox" name="q_dq_opt">
-              <property name="sizePolicy">
-               <sizepolicy hsizetype="Maximum" vsizetype="Maximum">
-                <horstretch>0</horstretch>
-                <verstretch>0</verstretch>
-               </sizepolicy>
-              </property>
-              <property name="minimumSize">
-               <size>
-                <width>0</width>
-                <height>0</height>
-               </size>
-              </property>
-              <property name="maximumSize">
-               <size>
-                <width>95</width>
-                <height>16777215</height>
-               </size>
-              </property>
-              <property name="currentIndex">
-               <number>0</number>
-              </property>
-              <item>
+              </column>
+              <column>
                <property name="text">
-                <string>Linear</string>
+                <string>Trans Can</string>
                </property>
-              </item>
-              <item>
+              </column>
+              <column>
                <property name="text">
-                <string>Logarithmic</string>
+                <string>Direct Can</string>
                </property>
-              </item>
-              <item>
+              </column>
+              <column>
                <property name="text">
-                <string>Variable</string>
+                <string>Output Name</string>
                </property>
-              </item>
-             </widget>
-            </item>
-            <item row="5" column="0">
-             <widget class="QLabel" name="qxy_lb">
-              <property name="text">
-               <string>Qxy (A^-1)</string>
-              </property>
-             </widget>
-            </item>
-            <item row="5" column="1">
-             <widget class="QLineEdit" name="qy_max">
-              <property name="sizePolicy">
-               <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
-                <horstretch>0</horstretch>
-                <verstretch>0</verstretch>
-               </sizepolicy>
-              </property>
-              <property name="maximumSize">
-               <size>
-                <width>70</width>
-                <height>16777215</height>
-               </size>
-              </property>
-             </widget>
-            </item>
-            <item row="5" column="3">
-             <widget class="QLabel" name="qy_step_lbl">
-              <property name="text">
-               <string>step</string>
-              </property>
-             </widget>
-            </item>
-            <item row="5" column="4">
-             <widget class="QLineEdit" name="qy_dqy">
-              <property name="sizePolicy">
-               <sizepolicy hsizetype="Expanding" vsizetype="Maximum">
-                <horstretch>0</horstretch>
-                <verstretch>0</verstretch>
-               </sizepolicy>
-              </property>
-              <property name="maximumSize">
-               <size>
-                <width>70</width>
-                <height>16777215</height>
-               </size>
-              </property>
+              </column>
              </widget>
             </item>
-            <item row="5" column="5">
-             <widget class="QComboBox" name="qy_dqy_opt">
-              <property name="sizePolicy">
-               <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
-                <horstretch>0</horstretch>
-                <verstretch>0</verstretch>
-               </sizepolicy>
-              </property>
-              <item>
+           </layout>
+          </widget>
+         </widget>
+        </item>
+        <item row="4" column="0" colspan="2">
+         <layout class="QGridLayout" name="gridLayout_44">
+          <item row="0" column="0">
+           <widget class="QGroupBox" name="groupBox_4">
+            <property name="title">
+             <string>Options</string>
+            </property>
+            <layout class="QGridLayout" name="gridLayout_20">
+             <item row="0" column="1">
+              <widget class="QCheckBox" name="verbose_check">
                <property name="text">
-                <string>Linear</string>
+                <string>Verbose</string>
                </property>
-              </item>
-             </widget>
-            </item>
-            <item row="6" column="0">
-             <widget class="QComboBox" name="trans_selector_opt">
-              <item>
+              </widget>
+             </item>
+             <item row="0" column="2">
+              <widget class="QCheckBox" name="log_colette">
                <property name="text">
-                <string>Both</string>
+                <string>Log Colette cmds</string>
                </property>
-              </item>
-              <item>
+              </widget>
+             </item>
+             <item row="0" column="0">
+              <widget class="QCheckBox" name="plot_check">
                <property name="text">
-                <string>Separate</string>
+                <string>Plot Result</string>
                </property>
-              </item>
-             </widget>
-            </item>
-            <item row="6" column="1">
-             <widget class="QCheckBox" name="transFitOnOff">
-              <property name="text">
-               <string>Trans Fit</string>
-              </property>
-             </widget>
-            </item>
-            <item row="6" column="2">
-             <widget class="QCheckBox" name="transFit_ck">
-              <property name="text">
-               <string>Use</string>
-              </property>
-             </widget>
-            </item>
-            <item row="6" column="3">
-             <widget class="QLineEdit" name="trans_min"/>
-            </item>
-            <item row="6" column="4">
-             <widget class="QLineEdit" name="trans_max"/>
-            </item>
-            <item row="6" column="5">
-             <widget class="QComboBox" name="trans_opt">
-              <item>
+              </widget>
+             </item>
+            </layout>
+           </widget>
+          </item>
+          <item row="1" column="0">
+           <widget class="QGroupBox" name="groupBox_7">
+            <property name="title">
+             <string>Reduce</string>
+            </property>
+            <property name="flat">
+             <bool>false</bool>
+            </property>
+            <layout class="QGridLayout" name="gridLayout_19">
+             <item row="0" column="0">
+              <widget class="QPushButton" name="load_dataBtn">
                <property name="text">
-                <string>Logarithmic</string>
+                <string>Load Data</string>
                </property>
-              </item>
-              <item>
+              </widget>
+             </item>
+             <item row="0" column="1">
+              <widget class="QPushButton" name="oneDBtn">
                <property name="text">
-                <string>Linear</string>
+                <string>1D Reduce</string>
                </property>
-              </item>
-              <item>
+              </widget>
+             </item>
+             <item row="0" column="2">
+              <widget class="QPushButton" name="twoDBtn">
                <property name="text">
-                <string>Polynomial2</string>
+                <string>2D Reduce</string>
                </property>
-              </item>
-              <item>
-               <property name="text">
-                <string>Polynomial3</string>
+              </widget>
+             </item>
+            </layout>
+           </widget>
+          </item>
+          <item row="0" column="1" rowspan="2">
+           <widget class="QGroupBox" name="groupBox_5">
+            <property name="title">
+             <string>Save</string>
+            </property>
+            <layout class="QGridLayout" name="gridLayout">
+             <item row="0" column="5" rowspan="2">
+              <widget class="QPushButton" name="saveFilename_btn">
+               <property name="minimumSize">
+                <size>
+                 <width>0</width>
+                 <height>0</height>
+                </size>
+               </property>
+               <property name="toolTip">
+                <string>Save the output workspace to this file</string>
                </property>
-              </item>
-              <item>
                <property name="text">
-                <string>Polynomial4</string>
+                <string>Browse</string>
+               </property>
+              </widget>
+             </item>
+             <item row="3" column="5">
+              <widget class="QCheckBox" name="saveCSV_check">
+               <property name="toolTip">
+                <string>Select one or more file formats</string>
                </property>
-              </item>
-              <item>
                <property name="text">
-                <string>Polynomial5</string>
+                <string>CSV</string>
+               </property>
+              </widget>
+             </item>
+             <item row="3" column="4">
+              <widget class="QCheckBox" name="saveRKH_check">
+               <property name="toolTip">
+                <string>Select one or more file formats</string>
                </property>
-              </item>
-              <item>
                <property name="text">
-                <string>Polynomial6</string>
+                <string>RKH</string>
+               </property>
+              </widget>
+             </item>
+             <item row="3" column="3">
+              <widget class="QCheckBox" name="saveCan_check">
+               <property name="toolTip">
+                <string>Select one or more file formats</string>
                </property>
-              </item>
-             </widget>
-            </item>
-            <item row="7" column="5">
-             <widget class="QComboBox" name="trans_opt_can">
-              <item>
                <property name="text">
-                <string>Logarithmic</string>
+                <string>CanSAS</string>
+               </property>
+              </widget>
+             </item>
+             <item row="3" column="1">
+              <widget class="QCheckBox" name="saveNex_check">
+               <property name="toolTip">
+                <string>Select one or more file formats</string>
                </property>
-              </item>
-              <item>
                <property name="text">
-                <string>Linear</string>
+                <string>Nexus</string>
+               </property>
+              </widget>
+             </item>
+             <item row="0" column="0" rowspan="2">
+              <widget class="QLabel" name="label_58">
+               <property name="toolTip">
+                <string>Save the output workspace to this file</string>
                </property>
-              </item>
-              <item>
                <property name="text">
-                <string>Polynomial2</string>
+                <string>Filename:</string>
+               </property>
+              </widget>
+             </item>
+             <item row="2" column="0" rowspan="2">
+              <widget class="QLabel" name="label_64">
+               <property name="toolTip">
+                <string>Select one or more file formats</string>
                </property>
-              </item>
-              <item>
                <property name="text">
-                <string>Polynomial3</string>
+                <string>Formats:</string>
+               </property>
+              </widget>
+             </item>
+             <item row="4" column="1" colspan="2">
+              <widget class="QPushButton" name="saveDefault_btn">
+               <property name="toolTip">
+                <string>Save the workspace from a single run file reduction</string>
                </property>
-              </item>
-              <item>
                <property name="text">
-                <string>Polynomial4</string>
+                <string>Save Result</string>
+               </property>
+              </widget>
+             </item>
+             <item row="1" column="1" colspan="4">
+              <widget class="QLineEdit" name="outfile_edit">
+               <property name="toolTip">
+                <string>Save the output workspace to this file</string>
+               </property>
+              </widget>
+             </item>
+             <item row="4" column="4" colspan="2">
+              <widget class="QPushButton" name="saveSel_btn">
+               <property name="toolTip">
+                <string>Save multiple workspaces</string>
                </property>
-              </item>
-              <item>
                <property name="text">
-                <string>Polynomial5</string>
+                <string>Save Other</string>
                </property>
-              </item>
-              <item>
+              </widget>
+             </item>
+             <item row="3" column="2">
+              <widget class="QCheckBox" name="saveNIST_Qxy_check">
                <property name="text">
-                <string>Polynomial6</string>
+                <string>NIST Qxy</string>
                </property>
-              </item>
-             </widget>
-            </item>
-            <item row="7" column="4">
-             <widget class="QLineEdit" name="trans_max_can"/>
-            </item>
-            <item row="7" column="3">
-             <widget class="QLineEdit" name="trans_min_can"/>
-            </item>
-            <item row="7" column="2">
-             <widget class="QCheckBox" name="transFit_ck_can">
-              <property name="text">
-               <string>Use</string>
-              </property>
-              <property name="checked">
-               <bool>true</bool>
-              </property>
-             </widget>
-            </item>
-            <item row="7" column="1">
-             <widget class="QCheckBox" name="transFitOnOff_can">
-              <property name="text">
-               <string>Trans Fit</string>
-              </property>
-             </widget>
-            </item>
-            <item row="7" column="0">
-             <widget class="QLabel" name="trans_can_label">
-              <property name="text">
-               <string>Can</string>
-              </property>
-             </widget>
-            </item>
-            <item row="1" column="3">
-             <widget class="QLabel" name="l_events_label">
-              <property name="text">
-               <string>Events</string>
-              </property>
-             </widget>
-            </item>
-            <item row="1" column="4" colspan="2">
-             <widget class="QLineEdit" name="l_events_binning"/>
-            </item>
-           </layout>
-          </widget>
-         </item>
-        </layout>
-       </item>
-       <item row="1" column="1">
-        <layout class="QVBoxLayout" name="verticalLayout_8">
-         <item>
-          <widget class="QGroupBox" name="groupBox_14">
-           <property name="title">
-            <string>Incident Monitors</string>
-           </property>
-           <layout class="QGridLayout" name="gridLayout_9">
-            <item row="0" column="0">
-             <widget class="QLabel" name="label_41">
-              <property name="text">
-               <string>For scattering</string>
-              </property>
-             </widget>
-            </item>
-            <item row="0" column="1">
-             <widget class="QLineEdit" name="monitor_spec">
-              <property name="sizePolicy">
-               <sizepolicy hsizetype="Expanding" vsizetype="Maximum">
-                <horstretch>0</horstretch>
-                <verstretch>0</verstretch>
-               </sizepolicy>
-              </property>
-              <property name="maximumSize">
-               <size>
-                <width>40</width>
-                <height>16777215</height>
-               </size>
-              </property>
-             </widget>
-            </item>
-            <item row="0" column="3">
-             <spacer name="horizontalSpacer_6">
-              <property name="orientation">
-               <enum>Qt::Horizontal</enum>
-              </property>
-              <property name="sizeHint" stdset="0">
-               <size>
-                <width>40</width>
-                <height>20</height>
-               </size>
-              </property>
-             </spacer>
-            </item>
-            <item row="0" column="2">
-             <widget class="QCheckBox" name="monitor_interp">
-              <property name="text">
-               <string>Interpolate</string>
-              </property>
-             </widget>
-            </item>
-            <item row="1" column="0">
-             <widget class="QLabel" name="label_39">
-              <property name="text">
-               <string>For transmissions</string>
-              </property>
-             </widget>
-            </item>
-            <item row="1" column="1">
-             <widget class="QLineEdit" name="trans_monitor">
-              <property name="sizePolicy">
-               <sizepolicy hsizetype="Maximum" vsizetype="Fixed">
-                <horstretch>0</horstretch>
-                <verstretch>0</verstretch>
-               </sizepolicy>
-              </property>
-              <property name="maximumSize">
-               <size>
-                <width>40</width>
-                <height>16777215</height>
-               </size>
-              </property>
-             </widget>
-            </item>
-            <item row="1" column="2">
-             <widget class="QCheckBox" name="trans_interp">
-              <property name="text">
-               <string>Interpolate</string>
-              </property>
-             </widget>
-            </item>
-           </layout>
-          </widget>
-         </item>
-        </layout>
-       </item>
-       <item row="2" column="1" rowspan="3">
-        <layout class="QVBoxLayout" name="verticalLayout_11">
-         <item>
-          <widget class="QGroupBox" name="groupBox_15">
-           <property name="sizePolicy">
-            <sizepolicy hsizetype="Preferred" vsizetype="Expanding">
-             <horstretch>0</horstretch>
-             <verstretch>0</verstretch>
-            </sizepolicy>
-           </property>
-           <property name="title">
-            <string>Detector</string>
-           </property>
-           <layout class="QGridLayout" name="gridLayout_17">
-            <item row="4" column="1" colspan="2">
-             <widget class="QCheckBox" name="mirror_phi">
-              <property name="text">
-               <string>Use mirror sector</string>
-              </property>
-              <property name="checked">
-               <bool>true</bool>
-              </property>
-             </widget>
-            </item>
-            <item row="1" column="0" colspan="4">
-             <layout class="QHBoxLayout" name="horizontalLayout_10">
-              <item>
-               <widget class="QLabel" name="label_43">
-                <property name="text">
-                 <string>Detector bank</string>
-                </property>
-               </widget>
-              </item>
-              <item>
-               <widget class="QComboBox" name="detbank_sel">
-                <property name="sizePolicy">
-                 <sizepolicy hsizetype="Preferred" vsizetype="Maximum">
-                  <horstretch>0</horstretch>
-                  <verstretch>0</verstretch>
-                 </sizepolicy>
-                </property>
-                <item>
-                 <property name="text">
-                  <string>main-detector-bank</string>
-                 </property>
-                </item>
-                <item>
-                 <property name="text">
-                  <string>HAB</string>
-                 </property>
-                </item>
-                <item>
-                 <property name="text">
-                  <string>both</string>
-                 </property>
-                </item>
-                <item>
-                 <property name="text">
-                  <string>merged</string>
-                 </property>
-                </item>
-               </widget>
-              </item>
-             </layout>
-            </item>
-            <item row="3" column="0" colspan="4">
-             <layout class="QHBoxLayout" name="horizontalLayout_11">
-              <item>
-               <widget class="QLabel" name="label_45">
-                <property name="text">
-                 <string>Limit Phi (degrees)</string>
-                </property>
-               </widget>
-              </item>
-              <item>
-               <widget class="QLineEdit" name="phi_min">
-                <property name="enabled">
-                 <bool>true</bool>
-                </property>
-                <property name="sizePolicy">
-                 <sizepolicy hsizetype="Expanding" vsizetype="Maximum">
-                  <horstretch>0</horstretch>
-                  <verstretch>0</verstretch>
-                 </sizepolicy>
-                </property>
-                <property name="maximumSize">
-                 <size>
-                  <width>50</width>
-                  <height>16777215</height>
-                 </size>
-                </property>
-               </widget>
-              </item>
-              <item>
-               <widget class="QLabel" name="label_33">
-                <property name="text">
-                 <string>to</string>
-                </property>
-               </widget>
-              </item>
-              <item>
-               <widget class="QLineEdit" name="phi_max">
-                <property name="enabled">
-                 <bool>true</bool>
-                </property>
-                <property name="sizePolicy">
-                 <sizepolicy hsizetype="Expanding" vsizetype="Maximum">
-                  <horstretch>0</horstretch>
-                  <verstretch>0</verstretch>
-                 </sizepolicy>
-                </property>
-                <property name="maximumSize">
-                 <size>
-                  <width>50</width>
-                  <height>16777215</height>
-                 </size>
-                </property>
-               </widget>
-              </item>
-             </layout>
-            </item>
-            <item row="6" column="0">
-             <layout class="QHBoxLayout" name="horizontalLayout_12">
-              <item>
-               <layout class="QGridLayout" name="gridLayout_29">
-                <item row="0" column="0">
-                 <widget class="QLabel" name="label_2">
-                  <property name="text">
-                   <string>Rescale</string>
-                  </property>
-                 </widget>
-                </item>
-                <item row="0" column="1">
-                 <widget class="QLineEdit" name="frontDetRescale"/>
-                </item>
-                <item row="0" column="2">
-                 <widget class="QCheckBox" name="frontDetRescaleCB">
-                  <property name="enabled">
-                   <bool>true</bool>
-                  </property>
-                  <property name="text">
-                   <string/>
-                  </property>
-                 </widget>
-                </item>
-                <item row="1" column="0">
-                 <widget class="QLabel" name="label_4">
-                  <property name="text">
-                   <string>Shift</string>
-                  </property>
-                 </widget>
-                </item>
-                <item row="1" column="1">
-                 <widget class="QLineEdit" name="frontDetShift"/>
-                </item>
-                <item row="1" column="2">
-                 <widget class="QCheckBox" name="frontDetShiftCB">
-                  <property name="enabled">
-                   <bool>true</bool>
-                  </property>
-                  <property name="text">
-                   <string/>
-                  </property>
-                 </widget>
-                </item>
-               </layout>
-              </item>
-             </layout>
-            </item>
-            <item row="5" column="0">
-             <layout class="QHBoxLayout" name="horizontalLayout_15">
-              <item>
-               <widget class="QLabel" name="label_6">
-                <property name="text">
-                 <string>Front detector</string>
-                </property>
-               </widget>
-              </item>
-              <item>
-               <widget class="QLabel" name="label_10">
-                <property name="text">
-                 <string>Fit</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
-                </property>
-               </widget>
-              </item>
-             </layout>
-            </item>
-            <item row="6" column="1" colspan="3">
-             <layout class="QGridLayout" name="gridLayout_30">
-              <item row="0" column="2">
-               <widget class="QLineEdit" name="frontDetQmax"/>
-              </item>
-              <item row="1" column="0">
-               <spacer name="horizontalSpacer_8">
-                <property name="orientation">
-                 <enum>Qt::Horizontal</enum>
-                </property>
-                <property name="sizeHint" stdset="0">
-                 <size>
-                  <width>40</width>
-                  <height>20</height>
-                 </size>
-                </property>
-               </spacer>
-              </item>
-              <item row="0" column="0">
-               <widget class="QLineEdit" name="frontDetQmin"/>
-              </item>
-              <item row="0" column="1">
-               <widget class="QLabel" name="label_8">
-                <property name="text">
-                 <string>to</string>
-                </property>
-               </widget>
-              </item>
-              <item row="0" column="3">
-               <widget class="QCheckBox" name="frontDetQrangeOnOff">
-                <property name="enabled">
-                 <bool>true</bool>
-                </property>
-                <property name="text">
-                 <string/>
-                </property>
-               </widget>
-              </item>
-             </layout>
-            </item>
-            <item row="5" column="1" colspan="2">
-             <widget class="QLabel" name="label_12">
-              <property name="text">
-               <string>Q range</string>
-              </property>
-              <property name="alignment">
-               <set>Qt::AlignCenter</set>
-              </property>
-             </widget>
-            </item>
-           </layout>
-          </widget>
-         </item>
-        </layout>
-       </item>
-       <item row="3" column="0">
-        <widget class="QGroupBox" name="groupBox_6">
-         <property name="title">
-          <string>Efficiency correction</string>
-         </property>
-         <layout class="QGridLayout" name="gridLayout_2">
-          <item row="0" column="1">
-           <widget class="QLabel" name="label_27">
-            <property name="text">
-             <string>Rear</string>
-            </property>
+              </widget>
+             </item>
+            </layout>
            </widget>
           </item>
-          <item row="0" column="2">
-           <widget class="QLineEdit" name="direct_file">
-            <property name="enabled">
-             <bool>false</bool>
-            </property>
-            <property name="sizePolicy">
-             <sizepolicy hsizetype="Preferred" vsizetype="Maximum">
-              <horstretch>0</horstretch>
-              <verstretch>0</verstretch>
-             </sizepolicy>
-            </property>
-            <property name="minimumSize">
-             <size>
-              <width>275</width>
-              <height>0</height>
-             </size>
+         </layout>
+        </item>
+       </layout>
+      </widget>
+      <widget class="QWidget" name="tab_2">
+       <attribute name="title">
+        <string>Reduction Settings</string>
+       </attribute>
+       <layout class="QGridLayout" name="gridLayout_13">
+        <item row="0" column="0">
+         <layout class="QHBoxLayout" name="horizontalLayout">
+          <item>
+           <widget class="QLabel" name="label_23">
+            <property name="text">
+             <string>Account for gravity</string>
             </property>
             <property name="alignment">
-             <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+             <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
             </property>
            </widget>
           </item>
-          <item row="1" column="1">
-           <widget class="QLabel" name="label_28">
+          <item>
+           <widget class="QCheckBox" name="gravity_check">
             <property name="text">
-             <string>Front</string>
+             <string/>
             </property>
            </widget>
           </item>
-          <item row="1" column="2">
-           <widget class="QLineEdit" name="front_direct_file">
-            <property name="enabled">
-             <bool>false</bool>
+          <item>
+           <spacer name="horizontalSpacer">
+            <property name="orientation">
+             <enum>Qt::Horizontal</enum>
+            </property>
+            <property name="sizeHint" stdset="0">
+             <size>
+              <width>40</width>
+              <height>20</height>
+             </size>
             </property>
+           </spacer>
+          </item>
+         </layout>
+        </item>
+        <item row="1" column="0" rowspan="2">
+         <layout class="QHBoxLayout" name="horizontalLayout_4">
+          <item>
+           <widget class="QGroupBox" name="limits_group">
             <property name="sizePolicy">
-             <sizepolicy hsizetype="Preferred" vsizetype="Maximum">
+             <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
               <horstretch>0</horstretch>
               <verstretch>0</verstretch>
              </sizepolicy>
             </property>
-            <property name="alignment">
-             <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+            <property name="layoutDirection">
+             <enum>Qt::LeftToRight</enum>
             </property>
-           </widget>
-          </item>
+            <property name="title">
+             <string>Limits</string>
+            </property>
+            <property name="checkable">
+             <bool>false</bool>
+            </property>
+            <layout class="QGridLayout" name="gridLayout_4">
+             <property name="verticalSpacing">
+              <number>5</number>
+             </property>
+             <item row="0" column="0">
+              <spacer name="horizontalSpacer_2">
+               <property name="orientation">
+                <enum>Qt::Horizontal</enum>
+               </property>
+               <property name="sizeHint" stdset="0">
+                <size>
+                 <width>40</width>
+                 <height>20</height>
+                </size>
+               </property>
+              </spacer>
+             </item>
+             <item row="0" column="1">
+              <widget class="QLabel" name="limits_min_lbl">
+               <property name="sizePolicy">
+                <sizepolicy hsizetype="Preferred" vsizetype="Maximum">
+                 <horstretch>0</horstretch>
+                 <verstretch>0</verstretch>
+                </sizepolicy>
+               </property>
+               <property name="text">
+                <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
+&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
+p, li { white-space: pre-wrap; }
+&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;
+&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:8pt;&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;Min&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+               </property>
+               <property name="alignment">
+                <set>Qt::AlignCenter</set>
+               </property>
+              </widget>
+             </item>
+             <item row="0" column="2">
+              <widget class="QLabel" name="limits_max_lbl">
+               <property name="sizePolicy">
+                <sizepolicy hsizetype="Preferred" vsizetype="Maximum">
+                 <horstretch>0</horstretch>
+                 <verstretch>0</verstretch>
+                </sizepolicy>
+               </property>
+               <property name="text">
+                <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
+&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
+p, li { white-space: pre-wrap; }
+&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;
+&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:8pt;&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;Max&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+               </property>
+               <property name="alignment">
+                <set>Qt::AlignCenter</set>
+               </property>
+              </widget>
+             </item>
+             <item row="1" column="0">
+              <widget class="QLabel" name="label_3">
+               <property name="text">
+                <string>Radius (mm)</string>
+               </property>
+              </widget>
+             </item>
+             <item row="1" column="1">
+              <widget class="QLineEdit" name="rad_min">
+               <property name="sizePolicy">
+                <sizepolicy hsizetype="Preferred" vsizetype="Maximum">
+                 <horstretch>0</horstretch>
+                 <verstretch>0</verstretch>
+                </sizepolicy>
+               </property>
+               <property name="maximumSize">
+                <size>
+                 <width>70</width>
+                 <height>16777215</height>
+                </size>
+               </property>
+              </widget>
+             </item>
+             <item row="1" column="2">
+              <widget class="QLineEdit" name="rad_max">
+               <property name="sizePolicy">
+                <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+                 <horstretch>0</horstretch>
+                 <verstretch>0</verstretch>
+                </sizepolicy>
+               </property>
+               <property name="maximumSize">
+                <size>
+                 <width>70</width>
+                 <height>16777215</height>
+                </size>
+               </property>
+              </widget>
+             </item>
+             <item row="3" column="0">
+              <widget class="QLabel" name="wavlength_lb">
+               <property name="toolTip">
+                <string>Controls the output from convert to wavelength</string>
+               </property>
+               <property name="text">
+                <string>Wavelength (A)</string>
+               </property>
+              </widget>
+             </item>
+             <item row="3" column="1" colspan="2">
+              <widget class="QStackedWidget" name="wav_stack">
+               <property name="autoFillBackground">
+                <bool>false</bool>
+               </property>
+               <property name="lineWidth">
+                <number>1</number>
+               </property>
+               <property name="currentIndex">
+                <number>0</number>
+               </property>
+               <widget class="QWidget" name="page_7">
+                <layout class="QGridLayout" name="gridLayout_21">
+                 <property name="leftMargin">
+                  <number>0</number>
+                 </property>
+                 <property name="topMargin">
+                  <number>0</number>
+                 </property>
+                 <property name="rightMargin">
+                  <number>0</number>
+                 </property>
+                 <property name="bottomMargin">
+                  <number>0</number>
+                 </property>
+                 <item row="0" column="1">
+                  <widget class="QLineEdit" name="wav_min">
+                   <property name="sizePolicy">
+                    <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+                     <horstretch>0</horstretch>
+                     <verstretch>0</verstretch>
+                    </sizepolicy>
+                   </property>
+                   <property name="maximumSize">
+                    <size>
+                     <width>70</width>
+                     <height>16777215</height>
+                    </size>
+                   </property>
+                   <property name="toolTip">
+                    <string>Start and end wavelengths used by convert to wavelengh</string>
+                   </property>
+                  </widget>
+                 </item>
+                 <item row="0" column="2">
+                  <widget class="QLineEdit" name="wav_max">
+                   <property name="sizePolicy">
+                    <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+                     <horstretch>0</horstretch>
+                     <verstretch>0</verstretch>
+                    </sizepolicy>
+                   </property>
+                   <property name="maximumSize">
+                    <size>
+                     <width>70</width>
+                     <height>16777215</height>
+                    </size>
+                   </property>
+                  </widget>
+                 </item>
+                </layout>
+               </widget>
+               <widget class="QWidget" name="page_8">
+                <layout class="QHBoxLayout" name="horizontalLayout_18">
+                 <property name="leftMargin">
+                  <number>0</number>
+                 </property>
+                 <property name="topMargin">
+                  <number>0</number>
+                 </property>
+                 <property name="rightMargin">
+                  <number>0</number>
+                 </property>
+                 <property name="bottomMargin">
+                  <number>0</number>
+                 </property>
+                 <item>
+                  <widget class="QLineEdit" name="wavRanges">
+                   <property name="toolTip">
+                    <string>Comma separated list of wavelength ranges. One reduction
+will always be done between the first and last ranges the
+intermediate ranges are there for comparison</string>
+                   </property>
+                  </widget>
+                 </item>
+                 <item>
+                  <widget class="QLabel" name="wavRanVal_lb">
+                   <property name="text">
+                    <string>*</string>
+                   </property>
+                   <property name="textFormat">
+                    <enum>Qt::AutoText</enum>
+                   </property>
+                  </widget>
+                 </item>
+                </layout>
+               </widget>
+              </widget>
+             </item>
+             <item row="3" column="3">
+              <widget class="QLabel" name="wav_step_lbl">
+               <property name="text">
+                <string>step</string>
+               </property>
+              </widget>
+             </item>
+             <item row="3" column="4">
+              <widget class="QLineEdit" name="wav_dw">
+               <property name="sizePolicy">
+                <sizepolicy hsizetype="Maximum" vsizetype="Maximum">
+                 <horstretch>0</horstretch>
+                 <verstretch>0</verstretch>
+                </sizepolicy>
+               </property>
+               <property name="maximumSize">
+                <size>
+                 <width>70</width>
+                 <height>16777215</height>
+                </size>
+               </property>
+               <property name="toolTip">
+                <string>The bin width of the output from convert to wavelength</string>
+               </property>
+              </widget>
+             </item>
+             <item row="3" column="5">
+              <widget class="QComboBox" name="wav_dw_opt">
+               <property name="sizePolicy">
+                <sizepolicy hsizetype="Maximum" vsizetype="Maximum">
+                 <horstretch>0</horstretch>
+                 <verstretch>0</verstretch>
+                </sizepolicy>
+               </property>
+               <property name="minimumSize">
+                <size>
+                 <width>0</width>
+                 <height>0</height>
+                </size>
+               </property>
+               <property name="toolTip">
+                <string>Use Plot Result (in first tab) to check overlapping</string>
+               </property>
+               <item>
+                <property name="text">
+                 <string>Linear</string>
+                </property>
+               </item>
+               <item>
+                <property name="text">
+                 <string>Logarithmic</string>
+                </property>
+               </item>
+               <item>
+                <property name="text">
+                 <string>Ranges Lin</string>
+                </property>
+               </item>
+               <item>
+                <property name="text">
+                 <string>Ranges Log</string>
+                </property>
+               </item>
+              </widget>
+             </item>
+             <item row="4" column="0" colspan="5">
+              <widget class="QStackedWidget" name="q_stack">
+               <property name="autoFillBackground">
+                <bool>false</bool>
+               </property>
+               <property name="lineWidth">
+                <number>1</number>
+               </property>
+               <property name="currentIndex">
+                <number>0</number>
+               </property>
+               <widget class="QWidget" name="page_2">
+                <layout class="QGridLayout" name="gridLayout_16">
+                 <property name="leftMargin">
+                  <number>0</number>
+                 </property>
+                 <property name="topMargin">
+                  <number>0</number>
+                 </property>
+                 <property name="rightMargin">
+                  <number>0</number>
+                 </property>
+                 <property name="bottomMargin">
+                  <number>0</number>
+                 </property>
+                 <item row="0" column="2">
+                  <widget class="QLineEdit" name="q_min">
+                   <property name="sizePolicy">
+                    <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+                     <horstretch>0</horstretch>
+                     <verstretch>0</verstretch>
+                    </sizepolicy>
+                   </property>
+                   <property name="maximumSize">
+                    <size>
+                     <width>70</width>
+                     <height>16777215</height>
+                    </size>
+                   </property>
+                  </widget>
+                 </item>
+                 <item row="0" column="3">
+                  <widget class="QLineEdit" name="q_max">
+                   <property name="sizePolicy">
+                    <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+                     <horstretch>0</horstretch>
+                     <verstretch>0</verstretch>
+                    </sizepolicy>
+                   </property>
+                   <property name="maximumSize">
+                    <size>
+                     <width>70</width>
+                     <height>16777215</height>
+                    </size>
+                   </property>
+                  </widget>
+                 </item>
+                 <item row="0" column="4">
+                  <widget class="QLabel" name="q_step_lbl">
+                   <property name="text">
+                    <string>stepping</string>
+                   </property>
+                  </widget>
+                 </item>
+                 <item row="0" column="5">
+                  <widget class="QLineEdit" name="q_dq">
+                   <property name="sizePolicy">
+                    <sizepolicy hsizetype="Maximum" vsizetype="Maximum">
+                     <horstretch>0</horstretch>
+                     <verstretch>0</verstretch>
+                    </sizepolicy>
+                   </property>
+                   <property name="maximumSize">
+                    <size>
+                     <width>70</width>
+                     <height>16777215</height>
+                    </size>
+                   </property>
+                  </widget>
+                 </item>
+                 <item row="0" column="1">
+                  <widget class="QLabel" name="qx_lb">
+                   <property name="sizePolicy">
+                    <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+                     <horstretch>0</horstretch>
+                     <verstretch>0</verstretch>
+                    </sizepolicy>
+                   </property>
+                   <property name="minimumSize">
+                    <size>
+                     <width>120</width>
+                     <height>0</height>
+                    </size>
+                   </property>
+                   <property name="text">
+                    <string>Qx (A^-1)</string>
+                   </property>
+                  </widget>
+                 </item>
+                </layout>
+               </widget>
+               <widget class="QWidget" name="page_4">
+                <layout class="QHBoxLayout" name="horizontalLayout_17">
+                 <property name="leftMargin">
+                  <number>0</number>
+                 </property>
+                 <property name="topMargin">
+                  <number>0</number>
+                 </property>
+                 <property name="rightMargin">
+                  <number>0</number>
+                 </property>
+                 <property name="bottomMargin">
+                  <number>0</number>
+                 </property>
+                 <item>
+                  <widget class="QLabel" name="label_37">
+                   <property name="minimumSize">
+                    <size>
+                     <width>120</width>
+                     <height>0</height>
+                    </size>
+                   </property>
+                   <property name="text">
+                    <string>Qx (Ã…^-1)</string>
+                   </property>
+                  </widget>
+                 </item>
+                 <item>
+                  <widget class="QLineEdit" name="q_rebin"/>
+                 </item>
+                </layout>
+               </widget>
+              </widget>
+             </item>
+             <item row="4" column="5">
+              <widget class="QComboBox" name="q_dq_opt">
+               <property name="sizePolicy">
+                <sizepolicy hsizetype="Maximum" vsizetype="Maximum">
+                 <horstretch>0</horstretch>
+                 <verstretch>0</verstretch>
+                </sizepolicy>
+               </property>
+               <property name="minimumSize">
+                <size>
+                 <width>0</width>
+                 <height>0</height>
+                </size>
+               </property>
+               <property name="maximumSize">
+                <size>
+                 <width>95</width>
+                 <height>16777215</height>
+                </size>
+               </property>
+               <property name="currentIndex">
+                <number>0</number>
+               </property>
+               <item>
+                <property name="text">
+                 <string>Linear</string>
+                </property>
+               </item>
+               <item>
+                <property name="text">
+                 <string>Logarithmic</string>
+                </property>
+               </item>
+               <item>
+                <property name="text">
+                 <string>Variable</string>
+                </property>
+               </item>
+              </widget>
+             </item>
+             <item row="5" column="0">
+              <widget class="QLabel" name="qxy_lb">
+               <property name="text">
+                <string>Qxy (A^-1)</string>
+               </property>
+              </widget>
+             </item>
+             <item row="5" column="1">
+              <widget class="QLineEdit" name="qy_max">
+               <property name="sizePolicy">
+                <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+                 <horstretch>0</horstretch>
+                 <verstretch>0</verstretch>
+                </sizepolicy>
+               </property>
+               <property name="maximumSize">
+                <size>
+                 <width>70</width>
+                 <height>16777215</height>
+                </size>
+               </property>
+              </widget>
+             </item>
+             <item row="5" column="3">
+              <widget class="QLabel" name="qy_step_lbl">
+               <property name="text">
+                <string>step</string>
+               </property>
+              </widget>
+             </item>
+             <item row="5" column="4">
+              <widget class="QLineEdit" name="qy_dqy">
+               <property name="sizePolicy">
+                <sizepolicy hsizetype="Expanding" vsizetype="Maximum">
+                 <horstretch>0</horstretch>
+                 <verstretch>0</verstretch>
+                </sizepolicy>
+               </property>
+               <property name="maximumSize">
+                <size>
+                 <width>70</width>
+                 <height>16777215</height>
+                </size>
+               </property>
+              </widget>
+             </item>
+             <item row="5" column="5">
+              <widget class="QComboBox" name="qy_dqy_opt">
+               <property name="sizePolicy">
+                <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+                 <horstretch>0</horstretch>
+                 <verstretch>0</verstretch>
+                </sizepolicy>
+               </property>
+               <item>
+                <property name="text">
+                 <string>Linear</string>
+                </property>
+               </item>
+              </widget>
+             </item>
+             <item row="6" column="0">
+              <widget class="QComboBox" name="trans_selector_opt">
+               <item>
+                <property name="text">
+                 <string>Both</string>
+                </property>
+               </item>
+               <item>
+                <property name="text">
+                 <string>Separate</string>
+                </property>
+               </item>
+              </widget>
+             </item>
+             <item row="6" column="1">
+              <widget class="QCheckBox" name="transFitOnOff">
+               <property name="text">
+                <string>Trans Fit</string>
+               </property>
+              </widget>
+             </item>
+             <item row="6" column="2">
+              <widget class="QCheckBox" name="transFit_ck">
+               <property name="text">
+                <string>Use</string>
+               </property>
+              </widget>
+             </item>
+             <item row="6" column="3">
+              <widget class="QLineEdit" name="trans_min"/>
+             </item>
+             <item row="6" column="4">
+              <widget class="QLineEdit" name="trans_max"/>
+             </item>
+             <item row="6" column="5">
+              <widget class="QComboBox" name="trans_opt">
+               <item>
+                <property name="text">
+                 <string>Logarithmic</string>
+                </property>
+               </item>
+               <item>
+                <property name="text">
+                 <string>Linear</string>
+                </property>
+               </item>
+               <item>
+                <property name="text">
+                 <string>Polynomial2</string>
+                </property>
+               </item>
+               <item>
+                <property name="text">
+                 <string>Polynomial3</string>
+                </property>
+               </item>
+               <item>
+                <property name="text">
+                 <string>Polynomial4</string>
+                </property>
+               </item>
+               <item>
+                <property name="text">
+                 <string>Polynomial5</string>
+                </property>
+               </item>
+               <item>
+                <property name="text">
+                 <string>Polynomial6</string>
+                </property>
+               </item>
+              </widget>
+             </item>
+             <item row="7" column="5">
+              <widget class="QComboBox" name="trans_opt_can">
+               <item>
+                <property name="text">
+                 <string>Logarithmic</string>
+                </property>
+               </item>
+               <item>
+                <property name="text">
+                 <string>Linear</string>
+                </property>
+               </item>
+               <item>
+                <property name="text">
+                 <string>Polynomial2</string>
+                </property>
+               </item>
+               <item>
+                <property name="text">
+                 <string>Polynomial3</string>
+                </property>
+               </item>
+               <item>
+                <property name="text">
+                 <string>Polynomial4</string>
+                </property>
+               </item>
+               <item>
+                <property name="text">
+                 <string>Polynomial5</string>
+                </property>
+               </item>
+               <item>
+                <property name="text">
+                 <string>Polynomial6</string>
+                </property>
+               </item>
+              </widget>
+             </item>
+             <item row="7" column="4">
+              <widget class="QLineEdit" name="trans_max_can"/>
+             </item>
+             <item row="7" column="3">
+              <widget class="QLineEdit" name="trans_min_can"/>
+             </item>
+             <item row="7" column="2">
+              <widget class="QCheckBox" name="transFit_ck_can">
+               <property name="text">
+                <string>Use</string>
+               </property>
+               <property name="checked">
+                <bool>true</bool>
+               </property>
+              </widget>
+             </item>
+             <item row="7" column="1">
+              <widget class="QCheckBox" name="transFitOnOff_can">
+               <property name="text">
+                <string>Trans Fit</string>
+               </property>
+              </widget>
+             </item>
+             <item row="7" column="0">
+              <widget class="QLabel" name="trans_can_label">
+               <property name="text">
+                <string>Can</string>
+               </property>
+              </widget>
+             </item>
+             <item row="1" column="3">
+              <widget class="QLabel" name="l_events_label">
+               <property name="text">
+                <string>Events</string>
+               </property>
+              </widget>
+             </item>
+             <item row="1" column="4" colspan="2">
+              <widget class="QLineEdit" name="l_events_binning"/>
+             </item>
+            </layout>
+           </widget>
+          </item>
+         </layout>
+        </item>
+        <item row="1" column="1">
+         <layout class="QVBoxLayout" name="verticalLayout_8">
+          <item>
+           <widget class="QGroupBox" name="groupBox_14">
+            <property name="title">
+             <string>Incident Monitors</string>
+            </property>
+            <layout class="QGridLayout" name="gridLayout_9">
+             <item row="0" column="0">
+              <widget class="QLabel" name="label_41">
+               <property name="text">
+                <string>For scattering</string>
+               </property>
+              </widget>
+             </item>
+             <item row="0" column="1">
+              <widget class="QLineEdit" name="monitor_spec">
+               <property name="sizePolicy">
+                <sizepolicy hsizetype="Expanding" vsizetype="Maximum">
+                 <horstretch>0</horstretch>
+                 <verstretch>0</verstretch>
+                </sizepolicy>
+               </property>
+               <property name="maximumSize">
+                <size>
+                 <width>40</width>
+                 <height>16777215</height>
+                </size>
+               </property>
+              </widget>
+             </item>
+             <item row="0" column="3">
+              <spacer name="horizontalSpacer_6">
+               <property name="orientation">
+                <enum>Qt::Horizontal</enum>
+               </property>
+               <property name="sizeHint" stdset="0">
+                <size>
+                 <width>40</width>
+                 <height>20</height>
+                </size>
+               </property>
+              </spacer>
+             </item>
+             <item row="0" column="2">
+              <widget class="QCheckBox" name="monitor_interp">
+               <property name="text">
+                <string>Interpolate</string>
+               </property>
+              </widget>
+             </item>
+             <item row="1" column="0">
+              <widget class="QLabel" name="label_39">
+               <property name="text">
+                <string>For transmissions</string>
+               </property>
+              </widget>
+             </item>
+             <item row="1" column="1">
+              <widget class="QLineEdit" name="trans_monitor">
+               <property name="sizePolicy">
+                <sizepolicy hsizetype="Maximum" vsizetype="Fixed">
+                 <horstretch>0</horstretch>
+                 <verstretch>0</verstretch>
+                </sizepolicy>
+               </property>
+               <property name="maximumSize">
+                <size>
+                 <width>40</width>
+                 <height>16777215</height>
+                </size>
+               </property>
+              </widget>
+             </item>
+             <item row="1" column="2">
+              <widget class="QCheckBox" name="trans_interp">
+               <property name="text">
+                <string>Interpolate</string>
+               </property>
+              </widget>
+             </item>
+            </layout>
+           </widget>
+          </item>
+         </layout>
+        </item>
+        <item row="2" column="1" rowspan="3">
+         <layout class="QVBoxLayout" name="verticalLayout_11">
+          <item>
+           <widget class="QGroupBox" name="groupBox_15">
+            <property name="sizePolicy">
+             <sizepolicy hsizetype="Preferred" vsizetype="Expanding">
+              <horstretch>0</horstretch>
+              <verstretch>0</verstretch>
+             </sizepolicy>
+            </property>
+            <property name="title">
+             <string>Detector</string>
+            </property>
+            <layout class="QGridLayout" name="gridLayout_17">
+             <item row="4" column="1" colspan="2">
+              <widget class="QCheckBox" name="mirror_phi">
+               <property name="text">
+                <string>Use mirror sector</string>
+               </property>
+               <property name="checked">
+                <bool>true</bool>
+               </property>
+              </widget>
+             </item>
+             <item row="1" column="0" colspan="4">
+              <layout class="QHBoxLayout" name="horizontalLayout_10">
+               <item>
+                <widget class="QLabel" name="label_43">
+                 <property name="text">
+                  <string>Detector bank</string>
+                 </property>
+                </widget>
+               </item>
+               <item>
+                <widget class="QComboBox" name="detbank_sel">
+                 <property name="sizePolicy">
+                  <sizepolicy hsizetype="Preferred" vsizetype="Maximum">
+                   <horstretch>0</horstretch>
+                   <verstretch>0</verstretch>
+                  </sizepolicy>
+                 </property>
+                 <item>
+                  <property name="text">
+                   <string>main-detector-bank</string>
+                  </property>
+                 </item>
+                 <item>
+                  <property name="text">
+                   <string>HAB</string>
+                  </property>
+                 </item>
+                 <item>
+                  <property name="text">
+                   <string>both</string>
+                  </property>
+                 </item>
+                 <item>
+                  <property name="text">
+                   <string>merged</string>
+                  </property>
+                 </item>
+                </widget>
+               </item>
+              </layout>
+             </item>
+             <item row="3" column="0" colspan="4">
+              <layout class="QHBoxLayout" name="horizontalLayout_11">
+               <item>
+                <widget class="QLabel" name="label_45">
+                 <property name="text">
+                  <string>Limit Phi (degrees)</string>
+                 </property>
+                </widget>
+               </item>
+               <item>
+                <widget class="QLineEdit" name="phi_min">
+                 <property name="enabled">
+                  <bool>true</bool>
+                 </property>
+                 <property name="sizePolicy">
+                  <sizepolicy hsizetype="Expanding" vsizetype="Maximum">
+                   <horstretch>0</horstretch>
+                   <verstretch>0</verstretch>
+                  </sizepolicy>
+                 </property>
+                 <property name="maximumSize">
+                  <size>
+                   <width>50</width>
+                   <height>16777215</height>
+                  </size>
+                 </property>
+                </widget>
+               </item>
+               <item>
+                <widget class="QLabel" name="label_33">
+                 <property name="text">
+                  <string>to</string>
+                 </property>
+                </widget>
+               </item>
+               <item>
+                <widget class="QLineEdit" name="phi_max">
+                 <property name="enabled">
+                  <bool>true</bool>
+                 </property>
+                 <property name="sizePolicy">
+                  <sizepolicy hsizetype="Expanding" vsizetype="Maximum">
+                   <horstretch>0</horstretch>
+                   <verstretch>0</verstretch>
+                  </sizepolicy>
+                 </property>
+                 <property name="maximumSize">
+                  <size>
+                   <width>50</width>
+                   <height>16777215</height>
+                  </size>
+                 </property>
+                </widget>
+               </item>
+              </layout>
+             </item>
+             <item row="6" column="0">
+              <layout class="QHBoxLayout" name="horizontalLayout_12">
+               <item>
+                <layout class="QGridLayout" name="gridLayout_29">
+                 <item row="0" column="0">
+                  <widget class="QLabel" name="label_2">
+                   <property name="text">
+                    <string>Rescale</string>
+                   </property>
+                  </widget>
+                 </item>
+                 <item row="0" column="1">
+                  <widget class="QLineEdit" name="frontDetRescale"/>
+                 </item>
+                 <item row="0" column="2">
+                  <widget class="QCheckBox" name="frontDetRescaleCB">
+                   <property name="enabled">
+                    <bool>true</bool>
+                   </property>
+                   <property name="text">
+                    <string/>
+                   </property>
+                  </widget>
+                 </item>
+                 <item row="1" column="0">
+                  <widget class="QLabel" name="label_4">
+                   <property name="text">
+                    <string>Shift</string>
+                   </property>
+                  </widget>
+                 </item>
+                 <item row="1" column="1">
+                  <widget class="QLineEdit" name="frontDetShift"/>
+                 </item>
+                 <item row="1" column="2">
+                  <widget class="QCheckBox" name="frontDetShiftCB">
+                   <property name="enabled">
+                    <bool>true</bool>
+                   </property>
+                   <property name="text">
+                    <string/>
+                   </property>
+                  </widget>
+                 </item>
+                </layout>
+               </item>
+              </layout>
+             </item>
+             <item row="5" column="0">
+              <layout class="QHBoxLayout" name="horizontalLayout_15">
+               <item>
+                <widget class="QLabel" name="label_6">
+                 <property name="text">
+                  <string>Front detector</string>
+                 </property>
+                </widget>
+               </item>
+               <item>
+                <widget class="QLabel" name="label_10">
+                 <property name="text">
+                  <string>Fit</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+                 </property>
+                </widget>
+               </item>
+              </layout>
+             </item>
+             <item row="6" column="1" colspan="3">
+              <layout class="QGridLayout" name="gridLayout_30">
+               <item row="0" column="2">
+                <widget class="QLineEdit" name="frontDetQmax"/>
+               </item>
+               <item row="1" column="0">
+                <spacer name="horizontalSpacer_8">
+                 <property name="orientation">
+                  <enum>Qt::Horizontal</enum>
+                 </property>
+                 <property name="sizeHint" stdset="0">
+                  <size>
+                   <width>40</width>
+                   <height>20</height>
+                  </size>
+                 </property>
+                </spacer>
+               </item>
+               <item row="0" column="0">
+                <widget class="QLineEdit" name="frontDetQmin"/>
+               </item>
+               <item row="0" column="1">
+                <widget class="QLabel" name="label_8">
+                 <property name="text">
+                  <string>to</string>
+                 </property>
+                </widget>
+               </item>
+               <item row="0" column="3">
+                <widget class="QCheckBox" name="frontDetQrangeOnOff">
+                 <property name="enabled">
+                  <bool>true</bool>
+                 </property>
+                 <property name="text">
+                  <string/>
+                 </property>
+                </widget>
+               </item>
+              </layout>
+             </item>
+             <item row="5" column="1" colspan="2">
+              <widget class="QLabel" name="label_12">
+               <property name="text">
+                <string>Q range</string>
+               </property>
+               <property name="alignment">
+                <set>Qt::AlignCenter</set>
+               </property>
+              </widget>
+             </item>
+            </layout>
+           </widget>
+          </item>
          </layout>
-        </widget>
-       </item>
-       <item row="4" column="0" rowspan="2">
-        <widget class="QGroupBox" name="groupBox_17">
-         <property name="title">
-          <string>Apply flood correction file</string>
-         </property>
-         <layout class="QVBoxLayout" name="verticalLayout_13">
+        </item>
+        <item row="3" column="0">
+         <widget class="QGroupBox" name="groupBox_6">
+          <property name="title">
+           <string>Efficiency correction</string>
+          </property>
+          <layout class="QGridLayout" name="gridLayout_2">
+           <item row="0" column="1">
+            <widget class="QLabel" name="label_27">
+             <property name="text">
+              <string>Rear</string>
+             </property>
+            </widget>
+           </item>
+           <item row="0" column="2">
+            <widget class="QLineEdit" name="direct_file">
+             <property name="enabled">
+              <bool>false</bool>
+             </property>
+             <property name="sizePolicy">
+              <sizepolicy hsizetype="Preferred" vsizetype="Maximum">
+               <horstretch>0</horstretch>
+               <verstretch>0</verstretch>
+              </sizepolicy>
+             </property>
+             <property name="minimumSize">
+              <size>
+               <width>275</width>
+               <height>0</height>
+              </size>
+             </property>
+             <property name="alignment">
+              <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+             </property>
+            </widget>
+           </item>
+           <item row="1" column="1">
+            <widget class="QLabel" name="label_28">
+             <property name="text">
+              <string>Front</string>
+             </property>
+            </widget>
+           </item>
+           <item row="1" column="2">
+            <widget class="QLineEdit" name="front_direct_file">
+             <property name="enabled">
+              <bool>false</bool>
+             </property>
+             <property name="sizePolicy">
+              <sizepolicy hsizetype="Preferred" vsizetype="Maximum">
+               <horstretch>0</horstretch>
+               <verstretch>0</verstretch>
+              </sizepolicy>
+             </property>
+             <property name="alignment">
+              <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+             </property>
+            </widget>
+           </item>
+          </layout>
+         </widget>
+        </item>
+        <item row="4" column="0" rowspan="2">
+         <widget class="QGroupBox" name="groupBox_17">
+          <property name="title">
+           <string>Apply flood correction file</string>
+          </property>
+          <layout class="QVBoxLayout" name="verticalLayout_13">
+           <item>
+            <layout class="QHBoxLayout" name="horizontalLayout_21">
+             <item>
+              <widget class="QCheckBox" name="enableRearFlood_ck">
+               <property name="text">
+                <string/>
+               </property>
+              </widget>
+             </item>
+             <item>
+              <widget class="MantidQt::MantidWidgets::MWRunFiles" name="floodRearFile" native="true">
+               <property name="findRunFiles" stdset="0">
+                <bool>false</bool>
+               </property>
+               <property name="label" stdset="0">
+                <string>Rear Flood File</string>
+               </property>
+               <property name="multipleFiles" stdset="0">
+                <bool>false</bool>
+               </property>
+               <property name="optional" stdset="0">
+                <bool>false</bool>
+               </property>
+               <property name="multiEntry" stdset="0">
+                <bool>false</bool>
+               </property>
+              </widget>
+             </item>
+            </layout>
+           </item>
+           <item>
+            <layout class="QHBoxLayout" name="horizontalLayout_22">
+             <item>
+              <widget class="QCheckBox" name="enableFrontFlood_ck">
+               <property name="text">
+                <string/>
+               </property>
+              </widget>
+             </item>
+             <item>
+              <widget class="MantidQt::MantidWidgets::MWRunFiles" name="floodFrontFile" native="true">
+               <property name="findRunFiles" stdset="0">
+                <bool>false</bool>
+               </property>
+               <property name="label" stdset="0">
+                <string>Front Flood File</string>
+               </property>
+               <property name="multipleFiles" stdset="0">
+                <bool>false</bool>
+               </property>
+               <property name="optional" stdset="0">
+                <bool>false</bool>
+               </property>
+               <property name="multiEntry" stdset="0">
+                <bool>false</bool>
+               </property>
+              </widget>
+             </item>
+            </layout>
+           </item>
+          </layout>
+         </widget>
+        </item>
+        <item row="5" column="1">
+         <layout class="QHBoxLayout" name="horizontalLayout_6">
           <item>
-           <layout class="QHBoxLayout" name="horizontalLayout_21">
-            <item>
-             <widget class="QCheckBox" name="enableRearFlood_ck">
-              <property name="text">
-               <string/>
-              </property>
-             </widget>
-            </item>
-            <item>
-             <widget class="MantidQt::MantidWidgets::MWRunFiles" name="floodRearFile" native="true">
-              <property name="findRunFiles" stdset="0">
-               <bool>false</bool>
-              </property>
-              <property name="label" stdset="0">
-               <string>Rear Flood File</string>
-              </property>
-              <property name="multipleFiles" stdset="0">
-               <bool>false</bool>
-              </property>
-              <property name="optional" stdset="0">
-               <bool>false</bool>
-              </property>
-              <property name="multiEntry" stdset="0">
-               <bool>false</bool>
-              </property>
-             </widget>
-            </item>
-           </layout>
+           <widget class="QGroupBox" name="groupBox_3">
+            <property name="title">
+             <string>Data range</string>
+            </property>
+            <layout class="QGridLayout" name="gridLayout_3">
+             <property name="topMargin">
+              <number>0</number>
+             </property>
+             <property name="bottomMargin">
+              <number>9</number>
+             </property>
+             <property name="horizontalSpacing">
+              <number>8</number>
+             </property>
+             <property name="verticalSpacing">
+              <number>6</number>
+             </property>
+             <item row="1" column="0">
+              <widget class="QLabel" name="label_5">
+               <property name="text">
+                <string>Time of flight</string>
+               </property>
+              </widget>
+             </item>
+             <item row="1" column="1">
+              <widget class="QLineEdit" name="tof_min">
+               <property name="enabled">
+                <bool>false</bool>
+               </property>
+               <property name="sizePolicy">
+                <sizepolicy hsizetype="Expanding" vsizetype="Maximum">
+                 <horstretch>0</horstretch>
+                 <verstretch>0</verstretch>
+                </sizepolicy>
+               </property>
+               <property name="maximumSize">
+                <size>
+                 <width>60</width>
+                 <height>16777215</height>
+                </size>
+               </property>
+               <property name="text">
+                <string/>
+               </property>
+              </widget>
+             </item>
+             <item row="1" column="2">
+              <widget class="QLineEdit" name="tof_max">
+               <property name="enabled">
+                <bool>false</bool>
+               </property>
+               <property name="sizePolicy">
+                <sizepolicy hsizetype="Expanding" vsizetype="Maximum">
+                 <horstretch>0</horstretch>
+                 <verstretch>0</verstretch>
+                </sizepolicy>
+               </property>
+               <property name="maximumSize">
+                <size>
+                 <width>60</width>
+                 <height>16777215</height>
+                </size>
+               </property>
+              </widget>
+             </item>
+             <item row="0" column="1">
+              <widget class="QLabel" name="label_22">
+               <property name="text">
+                <string>Min</string>
+               </property>
+               <property name="alignment">
+                <set>Qt::AlignCenter</set>
+               </property>
+              </widget>
+             </item>
+             <item row="0" column="2">
+              <widget class="QLabel" name="label_24">
+               <property name="text">
+                <string>Max</string>
+               </property>
+               <property name="alignment">
+                <set>Qt::AlignCenter</set>
+               </property>
+              </widget>
+             </item>
+            </layout>
+           </widget>
           </item>
           <item>
-           <layout class="QHBoxLayout" name="horizontalLayout_22">
-            <item>
-             <widget class="QCheckBox" name="enableFrontFlood_ck">
-              <property name="text">
-               <string/>
-              </property>
-             </widget>
-            </item>
-            <item>
-             <widget class="MantidQt::MantidWidgets::MWRunFiles" name="floodFrontFile" native="true">
-              <property name="findRunFiles" stdset="0">
-               <bool>false</bool>
-              </property>
-              <property name="label" stdset="0">
-               <string>Front Flood File</string>
-              </property>
-              <property name="multipleFiles" stdset="0">
-               <bool>false</bool>
-              </property>
-              <property name="optional" stdset="0">
-               <bool>false</bool>
-              </property>
-              <property name="multiEntry" stdset="0">
-               <bool>false</bool>
-              </property>
-             </widget>
-            </item>
-           </layout>
+           <widget class="QGroupBox" name="groupBox_9">
+            <property name="title">
+             <string>Scale Factor</string>
+            </property>
+            <layout class="QHBoxLayout" name="horizontalLayout_13">
+             <item>
+              <widget class="QLineEdit" name="scale_factor">
+               <property name="enabled">
+                <bool>false</bool>
+               </property>
+               <property name="sizePolicy">
+                <sizepolicy hsizetype="Maximum" vsizetype="Maximum">
+                 <horstretch>0</horstretch>
+                 <verstretch>0</verstretch>
+                </sizepolicy>
+               </property>
+               <property name="maximumSize">
+                <size>
+                 <width>70</width>
+                 <height>16777215</height>
+                </size>
+               </property>
+              </widget>
+             </item>
+            </layout>
+           </widget>
           </item>
          </layout>
-        </widget>
-       </item>
-       <item row="5" column="1">
-        <layout class="QHBoxLayout" name="horizontalLayout_6">
-         <item>
-          <widget class="QGroupBox" name="groupBox_3">
-           <property name="title">
-            <string>Data range</string>
+        </item>
+       </layout>
+      </widget>
+      <widget class="QWidget" name="tab_4">
+       <attribute name="title">
+        <string>Geometry</string>
+       </attribute>
+       <layout class="QGridLayout" name="gridLayout_14">
+        <item row="0" column="0">
+         <widget class="QGroupBox" name="sampDetails_gb">
+          <property name="title">
+           <string>Sample Details</string>
+          </property>
+          <layout class="QGridLayout" name="gridLayout_5">
+           <property name="verticalSpacing">
+            <number>1</number>
            </property>
-           <layout class="QGridLayout" name="gridLayout_3">
-            <property name="topMargin">
-             <number>0</number>
-            </property>
-            <property name="bottomMargin">
-             <number>9</number>
-            </property>
-            <property name="horizontalSpacing">
-             <number>8</number>
-            </property>
-            <property name="verticalSpacing">
-             <number>6</number>
-            </property>
-            <item row="1" column="0">
-             <widget class="QLabel" name="label_5">
+           <item row="0" column="0">
+            <widget class="QLabel" name="label_47">
+             <property name="text">
+              <string>Geometry:</string>
+             </property>
+            </widget>
+           </item>
+           <item row="0" column="1" colspan="2">
+            <widget class="QComboBox" name="sample_geomid">
+             <property name="sizePolicy">
+              <sizepolicy hsizetype="Maximum" vsizetype="Preferred">
+               <horstretch>0</horstretch>
+               <verstretch>0</verstretch>
+              </sizepolicy>
+             </property>
+             <property name="maximumSize">
+              <size>
+               <width>16777215</width>
+               <height>16777215</height>
+              </size>
+             </property>
+             <property name="currentIndex">
+              <number>2</number>
+             </property>
+             <item>
               <property name="text">
-               <string>Time of flight</string>
+               <string>1: Cylinder</string>
               </property>
-             </widget>
-            </item>
-            <item row="1" column="1">
-             <widget class="QLineEdit" name="tof_min">
-              <property name="enabled">
-               <bool>false</bool>
+             </item>
+             <item>
+              <property name="text">
+               <string>2: Flat plate</string>
               </property>
-              <property name="sizePolicy">
-               <sizepolicy hsizetype="Expanding" vsizetype="Maximum">
-                <horstretch>0</horstretch>
-                <verstretch>0</verstretch>
-               </sizepolicy>
+             </item>
+             <item>
+              <property name="text">
+               <string>3: Disc</string>
               </property>
-              <property name="maximumSize">
-               <size>
-                <width>60</width>
-                <height>16777215</height>
-               </size>
+             </item>
+            </widget>
+           </item>
+           <item row="3" column="0">
+            <widget class="QLabel" name="label_50">
+             <property name="text">
+              <string>Width(mm):</string>
+             </property>
+             <property name="alignment">
+              <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+             </property>
+            </widget>
+           </item>
+           <item row="1" column="1">
+            <widget class="QLineEdit" name="sample_thick">
+             <property name="sizePolicy">
+              <sizepolicy hsizetype="Expanding" vsizetype="Preferred">
+               <horstretch>0</horstretch>
+               <verstretch>0</verstretch>
+              </sizepolicy>
+             </property>
+             <property name="maximumSize">
+              <size>
+               <width>45</width>
+               <height>16777215</height>
+              </size>
+             </property>
+             <property name="text">
+              <string>1.0</string>
+             </property>
+            </widget>
+           </item>
+           <item row="3" column="1">
+            <widget class="QLineEdit" name="sample_width">
+             <property name="sizePolicy">
+              <sizepolicy hsizetype="Expanding" vsizetype="Preferred">
+               <horstretch>0</horstretch>
+               <verstretch>0</verstretch>
+              </sizepolicy>
+             </property>
+             <property name="maximumSize">
+              <size>
+               <width>45</width>
+               <height>16777215</height>
+              </size>
+             </property>
+             <property name="text">
+              <string>1.0</string>
+             </property>
+            </widget>
+           </item>
+           <item row="1" column="0">
+            <widget class="QLabel" name="label_48">
+             <property name="text">
+              <string>Thickness (mm):</string>
+             </property>
+             <property name="alignment">
+              <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+             </property>
+            </widget>
+           </item>
+           <item row="1" column="2">
+            <widget class="QLabel" name="label_49">
+             <property name="text">
+              <string>Height(mm):</string>
+             </property>
+             <property name="alignment">
+              <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+             </property>
+            </widget>
+           </item>
+           <item row="1" column="3">
+            <widget class="QLineEdit" name="sample_height">
+             <property name="sizePolicy">
+              <sizepolicy hsizetype="Expanding" vsizetype="Preferred">
+               <horstretch>0</horstretch>
+               <verstretch>0</verstretch>
+              </sizepolicy>
+             </property>
+             <property name="maximumSize">
+              <size>
+               <width>45</width>
+               <height>16777215</height>
+              </size>
+             </property>
+             <property name="text">
+              <string>1.0</string>
+             </property>
+            </widget>
+           </item>
+           <item row="3" column="2">
+            <widget class="QLabel" name="label_31">
+             <property name="text">
+              <string>Z-offset (mm)</string>
+             </property>
+            </widget>
+           </item>
+           <item row="3" column="3">
+            <widget class="QLineEdit" name="smpl_offset">
+             <property name="sizePolicy">
+              <sizepolicy hsizetype="Expanding" vsizetype="Preferred">
+               <horstretch>0</horstretch>
+               <verstretch>0</verstretch>
+              </sizepolicy>
+             </property>
+             <property name="maximumSize">
+              <size>
+               <width>45</width>
+               <height>16777215</height>
+              </size>
+             </property>
+            </widget>
+           </item>
+          </layout>
+         </widget>
+        </item>
+        <item row="1" column="0">
+         <widget class="QStackedWidget" name="geom_stack">
+          <property name="sizePolicy">
+           <sizepolicy hsizetype="Minimum" vsizetype="Minimum">
+            <horstretch>0</horstretch>
+            <verstretch>0</verstretch>
+           </sizepolicy>
+          </property>
+          <property name="currentIndex">
+           <number>1</number>
+          </property>
+          <widget class="QWidget" name="page_3">
+           <layout class="QGridLayout" name="gridLayout_6">
+            <item row="0" column="0">
+             <widget class="QGroupBox" name="loq_geometry">
+              <property name="title">
+               <string>LOQ Geometry (mm)</string>
               </property>
-              <property name="text">
-               <string/>
+              <property name="checkable">
+               <bool>false</bool>
               </property>
+              <layout class="QGridLayout" name="gridLayout_7">
+               <item row="1" column="0">
+                <spacer name="horizontalSpacer_22">
+                 <property name="orientation">
+                  <enum>Qt::Horizontal</enum>
+                 </property>
+                 <property name="sizeType">
+                  <enum>QSizePolicy::Fixed</enum>
+                 </property>
+                 <property name="sizeHint" stdset="0">
+                  <size>
+                   <width>140</width>
+                   <height>20</height>
+                  </size>
+                 </property>
+                </spacer>
+               </item>
+               <item row="1" column="1">
+                <widget class="QLabel" name="label_52">
+                 <property name="text">
+                  <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
+&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
+p, li { white-space: pre-wrap; }
+&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;
+&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:8pt; font-weight:600;&quot;&gt;Sample&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+                 </property>
+                </widget>
+               </item>
+               <item row="1" column="2">
+                <widget class="QLabel" name="label_53">
+                 <property name="text">
+                  <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
+&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
+p, li { white-space: pre-wrap; }
+&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;
+&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:8pt; font-weight:600;&quot;&gt;Can&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignCenter</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="2" column="0">
+                <widget class="QLabel" name="label_54">
+                 <property name="sizePolicy">
+                  <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+                   <horstretch>0</horstretch>
+                   <verstretch>0</verstretch>
+                  </sizepolicy>
+                 </property>
+                 <property name="text">
+                  <string>moderator - sample</string>
+                 </property>
+                </widget>
+               </item>
+               <item row="2" column="1">
+                <widget class="QLabel" name="dist_sample_ms">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 </property>
+                 <property name="textInteractionFlags">
+                  <set>Qt::LinksAccessibleByMouse</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="2" column="2">
+                <widget class="QLabel" name="dist_can_ms">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 </property>
+                 <property name="textInteractionFlags">
+                  <set>Qt::LinksAccessibleByMouse</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="3" column="2">
+                <widget class="QLabel" name="dist_can_mdb">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="3" column="1">
+                <widget class="QLabel" name="dist_smp_mdb">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="4" column="0">
+                <widget class="QLabel" name="label_61">
+                 <property name="sizePolicy">
+                  <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+                   <horstretch>0</horstretch>
+                   <verstretch>0</verstretch>
+                  </sizepolicy>
+                 </property>
+                 <property name="text">
+                  <string>sample - HAB</string>
+                 </property>
+                </widget>
+               </item>
+               <item row="4" column="1">
+                <widget class="QLabel" name="dist_smp_hab">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="4" column="2">
+                <widget class="QLabel" name="dist_can_hab">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="1" column="3">
+                <widget class="QLabel" name="label_62">
+                 <property name="text">
+                  <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
+&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
+p, li { white-space: pre-wrap; }
+&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;
+&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:8pt; font-weight:600;&quot;&gt;Bkgrd&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignCenter</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="2" column="3">
+                <widget class="QLabel" name="dist_bkgd_ms">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 </property>
+                 <property name="textInteractionFlags">
+                  <set>Qt::LinksAccessibleByMouse</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="3" column="3">
+                <widget class="QLabel" name="dist_bkgd_mdb">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="4" column="3">
+                <widget class="QLabel" name="dist_bkgd_hab">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="0" column="0">
+                <widget class="QLabel" name="label_63">
+                 <property name="text">
+                  <string>moderator - monitor </string>
+                 </property>
+                </widget>
+               </item>
+               <item row="0" column="2">
+                <widget class="QLabel" name="dist_mod_mon">
+                 <property name="font">
+                  <font>
+                   <pointsize>8</pointsize>
+                   <weight>50</weight>
+                   <bold>false</bold>
+                  </font>
+                 </property>
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignCenter</set>
+                 </property>
+                 <property name="textInteractionFlags">
+                  <set>Qt::LinksAccessibleByMouse</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="3" column="0">
+                <widget class="QLabel" name="label_55">
+                 <property name="sizePolicy">
+                  <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+                   <horstretch>0</horstretch>
+                   <verstretch>0</verstretch>
+                  </sizepolicy>
+                 </property>
+                 <property name="text">
+                  <string>sample - main-detector bank</string>
+                 </property>
+                </widget>
+               </item>
+              </layout>
              </widget>
             </item>
-            <item row="1" column="2">
-             <widget class="QLineEdit" name="tof_max">
-              <property name="enabled">
-               <bool>false</bool>
-              </property>
-              <property name="sizePolicy">
-               <sizepolicy hsizetype="Expanding" vsizetype="Maximum">
-                <horstretch>0</horstretch>
-                <verstretch>0</verstretch>
-               </sizepolicy>
+            <item row="1" column="0">
+             <spacer name="verticalSpacer">
+              <property name="orientation">
+               <enum>Qt::Vertical</enum>
               </property>
-              <property name="maximumSize">
+              <property name="sizeHint" stdset="0">
                <size>
-                <width>60</width>
-                <height>16777215</height>
+                <width>20</width>
+                <height>40</height>
                </size>
               </property>
-             </widget>
-            </item>
-            <item row="0" column="1">
-             <widget class="QLabel" name="label_22">
-              <property name="text">
-               <string>Min</string>
-              </property>
-              <property name="alignment">
-               <set>Qt::AlignCenter</set>
-              </property>
-             </widget>
-            </item>
-            <item row="0" column="2">
-             <widget class="QLabel" name="label_24">
-              <property name="text">
-               <string>Max</string>
-              </property>
-              <property name="alignment">
-               <set>Qt::AlignCenter</set>
-              </property>
-             </widget>
+             </spacer>
             </item>
            </layout>
           </widget>
-         </item>
-         <item>
-          <widget class="QGroupBox" name="groupBox_9">
-           <property name="title">
-            <string>Scale Factor</string>
-           </property>
-           <layout class="QHBoxLayout" name="horizontalLayout_13">
+          <widget class="QWidget" name="page">
+           <layout class="QHBoxLayout" name="horizontalLayout_41">
             <item>
-             <widget class="QLineEdit" name="scale_factor">
-              <property name="enabled">
-               <bool>false</bool>
-              </property>
+             <widget class="QGroupBox" name="groupBox_43">
               <property name="sizePolicy">
-               <sizepolicy hsizetype="Maximum" vsizetype="Maximum">
+               <sizepolicy hsizetype="Minimum" vsizetype="Preferred">
                 <horstretch>0</horstretch>
                 <verstretch>0</verstretch>
                </sizepolicy>
-              </property>
-              <property name="maximumSize">
-               <size>
-                <width>70</width>
-                <height>16777215</height>
-               </size>
-              </property>
-             </widget>
-            </item>
-           </layout>
-          </widget>
-         </item>
-        </layout>
-       </item>
-      </layout>
-     </widget>
-     <widget class="QWidget" name="tab_4">
-      <attribute name="title">
-       <string>Geometry</string>
-      </attribute>
-      <layout class="QGridLayout" name="gridLayout_14">
-       <item row="0" column="0">
-        <widget class="QGroupBox" name="sampDetails_gb">
-         <property name="title">
-          <string>Sample Details</string>
-         </property>
-         <layout class="QGridLayout" name="gridLayout_5">
-          <property name="verticalSpacing">
-           <number>1</number>
-          </property>
-          <item row="0" column="0">
-           <widget class="QLabel" name="label_47">
-            <property name="text">
-             <string>Geometry:</string>
-            </property>
-           </widget>
-          </item>
-          <item row="0" column="1" colspan="2">
-           <widget class="QComboBox" name="sample_geomid">
-            <property name="sizePolicy">
-             <sizepolicy hsizetype="Maximum" vsizetype="Preferred">
-              <horstretch>0</horstretch>
-              <verstretch>0</verstretch>
-             </sizepolicy>
-            </property>
-            <property name="maximumSize">
-             <size>
-              <width>16777215</width>
-              <height>16777215</height>
-             </size>
-            </property>
-            <property name="currentIndex">
-             <number>2</number>
-            </property>
-            <item>
-             <property name="text">
-              <string>1: Cylinder</string>
-             </property>
-            </item>
-            <item>
-             <property name="text">
-              <string>2: Flat plate</string>
-             </property>
-            </item>
-            <item>
-             <property name="text">
-              <string>3: Disc</string>
-             </property>
-            </item>
-           </widget>
-          </item>
-          <item row="3" column="0">
-           <widget class="QLabel" name="label_50">
-            <property name="text">
-             <string>Width(mm):</string>
-            </property>
-            <property name="alignment">
-             <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-            </property>
-           </widget>
-          </item>
-          <item row="1" column="1">
-           <widget class="QLineEdit" name="sample_thick">
-            <property name="sizePolicy">
-             <sizepolicy hsizetype="Expanding" vsizetype="Preferred">
-              <horstretch>0</horstretch>
-              <verstretch>0</verstretch>
-             </sizepolicy>
-            </property>
-            <property name="maximumSize">
-             <size>
-              <width>45</width>
-              <height>16777215</height>
-             </size>
-            </property>
-            <property name="text">
-             <string>1.0</string>
-            </property>
-           </widget>
-          </item>
-          <item row="3" column="1">
-           <widget class="QLineEdit" name="sample_width">
-            <property name="sizePolicy">
-             <sizepolicy hsizetype="Expanding" vsizetype="Preferred">
-              <horstretch>0</horstretch>
-              <verstretch>0</verstretch>
-             </sizepolicy>
-            </property>
-            <property name="maximumSize">
-             <size>
-              <width>45</width>
-              <height>16777215</height>
-             </size>
-            </property>
-            <property name="text">
-             <string>1.0</string>
-            </property>
-           </widget>
-          </item>
-          <item row="1" column="0">
-           <widget class="QLabel" name="label_48">
-            <property name="text">
-             <string>Thickness (mm):</string>
-            </property>
-            <property name="alignment">
-             <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-            </property>
-           </widget>
-          </item>
-          <item row="1" column="2">
-           <widget class="QLabel" name="label_49">
-            <property name="text">
-             <string>Height(mm):</string>
-            </property>
-            <property name="alignment">
-             <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-            </property>
-           </widget>
-          </item>
-          <item row="1" column="3">
-           <widget class="QLineEdit" name="sample_height">
-            <property name="sizePolicy">
-             <sizepolicy hsizetype="Expanding" vsizetype="Preferred">
-              <horstretch>0</horstretch>
-              <verstretch>0</verstretch>
-             </sizepolicy>
-            </property>
-            <property name="maximumSize">
-             <size>
-              <width>45</width>
-              <height>16777215</height>
-             </size>
-            </property>
-            <property name="text">
-             <string>1.0</string>
-            </property>
-           </widget>
-          </item>
-          <item row="3" column="2">
-           <widget class="QLabel" name="label_31">
-            <property name="text">
-             <string>Z-offset (mm)</string>
-            </property>
-           </widget>
-          </item>
-          <item row="3" column="3">
-           <widget class="QLineEdit" name="smpl_offset">
-            <property name="sizePolicy">
-             <sizepolicy hsizetype="Expanding" vsizetype="Preferred">
-              <horstretch>0</horstretch>
-              <verstretch>0</verstretch>
-             </sizepolicy>
-            </property>
-            <property name="maximumSize">
-             <size>
-              <width>45</width>
-              <height>16777215</height>
-             </size>
-            </property>
-           </widget>
-          </item>
-         </layout>
-        </widget>
-       </item>
-       <item row="1" column="0">
-        <widget class="QStackedWidget" name="geom_stack">
-         <property name="sizePolicy">
-          <sizepolicy hsizetype="Minimum" vsizetype="Minimum">
-           <horstretch>0</horstretch>
-           <verstretch>0</verstretch>
-          </sizepolicy>
-         </property>
-         <property name="currentIndex">
-          <number>1</number>
-         </property>
-         <widget class="QWidget" name="page_3">
-          <layout class="QGridLayout" name="gridLayout_6">
-           <item row="0" column="0">
-            <widget class="QGroupBox" name="loq_geometry">
-             <property name="title">
-              <string>LOQ Geometry (mm)</string>
-             </property>
-             <property name="checkable">
-              <bool>false</bool>
-             </property>
-             <layout class="QGridLayout" name="gridLayout_7">
-              <item row="1" column="0">
-               <spacer name="horizontalSpacer_22">
-                <property name="orientation">
-                 <enum>Qt::Horizontal</enum>
-                </property>
-                <property name="sizeType">
-                 <enum>QSizePolicy::Fixed</enum>
-                </property>
-                <property name="sizeHint" stdset="0">
-                 <size>
-                  <width>140</width>
-                  <height>20</height>
-                 </size>
-                </property>
-               </spacer>
-              </item>
-              <item row="1" column="1">
-               <widget class="QLabel" name="label_52">
-                <property name="text">
-                 <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
-&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
-p, li { white-space: pre-wrap; }
-&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;
-&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:8pt; font-weight:600;&quot;&gt;Sample&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
-                </property>
-               </widget>
-              </item>
-              <item row="1" column="2">
-               <widget class="QLabel" name="label_53">
-                <property name="text">
-                 <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
-&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
-p, li { white-space: pre-wrap; }
-&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;
-&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:8pt; font-weight:600;&quot;&gt;Can&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignCenter</set>
-                </property>
-               </widget>
-              </item>
-              <item row="2" column="0">
-               <widget class="QLabel" name="label_54">
-                <property name="sizePolicy">
-                 <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
-                  <horstretch>0</horstretch>
-                  <verstretch>0</verstretch>
-                 </sizepolicy>
-                </property>
-                <property name="text">
-                 <string>moderator - sample</string>
-                </property>
-               </widget>
-              </item>
-              <item row="2" column="1">
-               <widget class="QLabel" name="dist_sample_ms">
-                <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-                </property>
-                <property name="textInteractionFlags">
-                 <set>Qt::LinksAccessibleByMouse</set>
-                </property>
-               </widget>
-              </item>
-              <item row="2" column="2">
-               <widget class="QLabel" name="dist_can_ms">
-                <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-                </property>
-                <property name="textInteractionFlags">
-                 <set>Qt::LinksAccessibleByMouse</set>
-                </property>
-               </widget>
-              </item>
-              <item row="3" column="2">
-               <widget class="QLabel" name="dist_can_mdb">
-                <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-                </property>
-               </widget>
-              </item>
-              <item row="3" column="1">
-               <widget class="QLabel" name="dist_smp_mdb">
-                <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-                </property>
-               </widget>
-              </item>
-              <item row="4" column="0">
-               <widget class="QLabel" name="label_61">
-                <property name="sizePolicy">
-                 <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
-                  <horstretch>0</horstretch>
-                  <verstretch>0</verstretch>
-                 </sizepolicy>
-                </property>
-                <property name="text">
-                 <string>sample - HAB</string>
-                </property>
-               </widget>
-              </item>
-              <item row="4" column="1">
-               <widget class="QLabel" name="dist_smp_hab">
-                <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-                </property>
-               </widget>
-              </item>
-              <item row="4" column="2">
-               <widget class="QLabel" name="dist_can_hab">
-                <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-                </property>
-               </widget>
-              </item>
-              <item row="1" column="3">
-               <widget class="QLabel" name="label_62">
-                <property name="text">
-                 <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
+              </property>
+              <property name="minimumSize">
+               <size>
+                <width>275</width>
+                <height>0</height>
+               </size>
+              </property>
+              <property name="title">
+               <string>SANS2D Geometry (mm)</string>
+              </property>
+              <property name="checkable">
+               <bool>false</bool>
+              </property>
+              <layout class="QGridLayout" name="gridLayout_26">
+               <property name="horizontalSpacing">
+                <number>6</number>
+               </property>
+               <property name="verticalSpacing">
+                <number>0</number>
+               </property>
+               <item row="1" column="1">
+                <widget class="QLabel" name="label_181">
+                 <property name="text">
+                  <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
+&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
+p, li { white-space: pre-wrap; }
+&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;
+&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:8pt; font-weight:600;&quot;&gt;Sample&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+                 </property>
+                </widget>
+               </item>
+               <item row="1" column="2">
+                <widget class="QLabel" name="label_182">
+                 <property name="text">
+                  <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
+&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
+p, li { white-space: pre-wrap; }
+&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;
+&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:8pt; font-weight:600;&quot;&gt;Can&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignCenter</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="2" column="0">
+                <widget class="QLabel" name="label_183">
+                 <property name="sizePolicy">
+                  <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+                   <horstretch>0</horstretch>
+                   <verstretch>0</verstretch>
+                  </sizepolicy>
+                 </property>
+                 <property name="text">
+                  <string>moderator - sample</string>
+                 </property>
+                </widget>
+               </item>
+               <item row="3" column="0">
+                <widget class="QLabel" name="label_184">
+                 <property name="sizePolicy">
+                  <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+                   <horstretch>0</horstretch>
+                   <verstretch>0</verstretch>
+                  </sizepolicy>
+                 </property>
+                 <property name="text">
+                  <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
+&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
+p, li { white-space: pre-wrap; }
+&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal;&quot;&gt;
+&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;rear-detector:&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+                 </property>
+                </widget>
+               </item>
+               <item row="2" column="1">
+                <widget class="QLabel" name="dist_sample_ms_s2d">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 </property>
+                 <property name="textInteractionFlags">
+                  <set>Qt::LinksAccessibleByMouse</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="2" column="2">
+                <widget class="QLabel" name="dist_can_ms_s2d">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 </property>
+                 <property name="textInteractionFlags">
+                  <set>Qt::LinksAccessibleByMouse</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="1" column="3">
+                <widget class="QLabel" name="label_185">
+                 <property name="text">
+                  <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
 &lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
 p, li { white-space: pre-wrap; }
 &lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;
 &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:8pt; font-weight:600;&quot;&gt;Bkgrd&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignCenter</set>
-                </property>
-               </widget>
-              </item>
-              <item row="2" column="3">
-               <widget class="QLabel" name="dist_bkgd_ms">
-                <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-                </property>
-                <property name="textInteractionFlags">
-                 <set>Qt::LinksAccessibleByMouse</set>
-                </property>
-               </widget>
-              </item>
-              <item row="3" column="3">
-               <widget class="QLabel" name="dist_bkgd_mdb">
-                <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-                </property>
-               </widget>
-              </item>
-              <item row="4" column="3">
-               <widget class="QLabel" name="dist_bkgd_hab">
-                <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-                </property>
-               </widget>
-              </item>
-              <item row="0" column="0">
-               <widget class="QLabel" name="label_63">
-                <property name="text">
-                 <string>moderator - monitor </string>
-                </property>
-               </widget>
-              </item>
-              <item row="0" column="2">
-               <widget class="QLabel" name="dist_mod_mon">
-                <property name="font">
-                 <font>
-                  <pointsize>8</pointsize>
-                  <weight>50</weight>
-                  <bold>false</bold>
-                 </font>
-                </property>
-                <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignCenter</set>
-                </property>
-                <property name="textInteractionFlags">
-                 <set>Qt::LinksAccessibleByMouse</set>
-                </property>
-               </widget>
-              </item>
-              <item row="3" column="0">
-               <widget class="QLabel" name="label_55">
-                <property name="sizePolicy">
-                 <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
-                  <horstretch>0</horstretch>
-                  <verstretch>0</verstretch>
-                 </sizepolicy>
-                </property>
-                <property name="text">
-                 <string>sample - main-detector bank</string>
-                </property>
-               </widget>
-              </item>
-             </layout>
-            </widget>
-           </item>
-           <item row="1" column="0">
-            <spacer name="verticalSpacer">
-             <property name="orientation">
-              <enum>Qt::Vertical</enum>
-             </property>
-             <property name="sizeHint" stdset="0">
-              <size>
-               <width>20</width>
-               <height>40</height>
-              </size>
-             </property>
-            </spacer>
-           </item>
-          </layout>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignCenter</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="2" column="3">
+                <widget class="QLabel" name="dist_bkgd_ms_s2d">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 </property>
+                 <property name="textInteractionFlags">
+                  <set>Qt::LinksAccessibleByMouse</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="0" column="2">
+                <widget class="QLabel" name="dist_mon_s2d">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignCenter</set>
+                 </property>
+                 <property name="textInteractionFlags">
+                  <set>Qt::LinksAccessibleByMouse</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="0" column="0" colspan="2">
+                <widget class="QLabel" name="label_186">
+                 <property name="text">
+                  <string>moderator - monitor </string>
+                 </property>
+                </widget>
+               </item>
+               <item row="4" column="0">
+                <widget class="QLabel" name="label_187">
+                 <property name="text">
+                  <string>X</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignCenter</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="4" column="1">
+                <widget class="QLabel" name="dist_smp_rearX">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 </property>
+                 <property name="textInteractionFlags">
+                  <set>Qt::LinksAccessibleByMouse</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="4" column="2">
+                <widget class="QLabel" name="dist_can_rearX">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 </property>
+                 <property name="textInteractionFlags">
+                  <set>Qt::LinksAccessibleByMouse</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="4" column="3">
+                <widget class="QLabel" name="dist_bkgd_rearX">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 </property>
+                 <property name="textInteractionFlags">
+                  <set>Qt::LinksAccessibleByMouse</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="5" column="0">
+                <widget class="QLabel" name="label_188">
+                 <property name="text">
+                  <string>Z</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignCenter</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="6" column="0">
+                <widget class="QLabel" name="label_189">
+                 <property name="sizePolicy">
+                  <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+                   <horstretch>0</horstretch>
+                   <verstretch>0</verstretch>
+                  </sizepolicy>
+                 </property>
+                 <property name="text">
+                  <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
+&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
+p, li { white-space: pre-wrap; }
+&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal;&quot;&gt;
+&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;front-detector:&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+                 </property>
+                </widget>
+               </item>
+               <item row="7" column="0">
+                <widget class="QLabel" name="label_190">
+                 <property name="text">
+                  <string>X</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignCenter</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="8" column="0">
+                <widget class="QLabel" name="label_191">
+                 <property name="text">
+                  <string>Z</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignCenter</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="9" column="0">
+                <widget class="QLabel" name="label_192">
+                 <property name="text">
+                  <string>Rot</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignCenter</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="5" column="1">
+                <widget class="QLabel" name="dist_smp_rearZ">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 </property>
+                 <property name="textInteractionFlags">
+                  <set>Qt::LinksAccessibleByMouse</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="5" column="2">
+                <widget class="QLabel" name="dist_can_rearZ">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 </property>
+                 <property name="textInteractionFlags">
+                  <set>Qt::LinksAccessibleByMouse</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="5" column="3">
+                <widget class="QLabel" name="dist_bkgd_rearZ">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 </property>
+                 <property name="textInteractionFlags">
+                  <set>Qt::LinksAccessibleByMouse</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="7" column="1">
+                <widget class="QLabel" name="dist_smp_frontX">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 </property>
+                 <property name="textInteractionFlags">
+                  <set>Qt::LinksAccessibleByMouse</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="7" column="2">
+                <widget class="QLabel" name="dist_can_frontX">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 </property>
+                 <property name="textInteractionFlags">
+                  <set>Qt::LinksAccessibleByMouse</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="7" column="3">
+                <widget class="QLabel" name="dist_bkgd_frontX">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 </property>
+                 <property name="textInteractionFlags">
+                  <set>Qt::LinksAccessibleByMouse</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="8" column="1">
+                <widget class="QLabel" name="dist_smp_frontZ">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 </property>
+                 <property name="textInteractionFlags">
+                  <set>Qt::LinksAccessibleByMouse</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="8" column="2">
+                <widget class="QLabel" name="dist_can_frontZ">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 </property>
+                 <property name="textInteractionFlags">
+                  <set>Qt::LinksAccessibleByMouse</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="8" column="3">
+                <widget class="QLabel" name="dist_bkgd_frontZ">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 </property>
+                 <property name="textInteractionFlags">
+                  <set>Qt::LinksAccessibleByMouse</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="9" column="1">
+                <widget class="QLabel" name="smp_rot">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 </property>
+                 <property name="textInteractionFlags">
+                  <set>Qt::LinksAccessibleByMouse</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="9" column="2">
+                <widget class="QLabel" name="can_rot">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 </property>
+                 <property name="textInteractionFlags">
+                  <set>Qt::LinksAccessibleByMouse</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="9" column="3">
+                <widget class="QLabel" name="bkgd_rot">
+                 <property name="text">
+                  <string>-</string>
+                 </property>
+                 <property name="alignment">
+                  <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 </property>
+                 <property name="textInteractionFlags">
+                  <set>Qt::LinksAccessibleByMouse</set>
+                 </property>
+                </widget>
+               </item>
+               <item row="1" column="0">
+                <spacer name="horizontalSpacer_21">
+                 <property name="orientation">
+                  <enum>Qt::Horizontal</enum>
+                 </property>
+                 <property name="sizeType">
+                  <enum>QSizePolicy::Fixed</enum>
+                 </property>
+                 <property name="sizeHint" stdset="0">
+                  <size>
+                   <width>110</width>
+                   <height>20</height>
+                  </size>
+                 </property>
+                </spacer>
+               </item>
+              </layout>
+             </widget>
+            </item>
+           </layout>
+          </widget>
          </widget>
-         <widget class="QWidget" name="page">
-          <layout class="QHBoxLayout" name="horizontalLayout_41">
+        </item>
+        <item row="0" column="1" rowspan="2">
+         <widget class="QGroupBox" name="groupBox_13">
+          <property name="title">
+           <string>Beam Centre</string>
+          </property>
+          <property name="flat">
+           <bool>false</bool>
+          </property>
+          <property name="checkable">
+           <bool>false</bool>
+          </property>
+          <layout class="QVBoxLayout" name="verticalLayout_12" stretch="1,1,2">
            <item>
-            <widget class="QGroupBox" name="groupBox_43">
-             <property name="sizePolicy">
-              <sizepolicy hsizetype="Minimum" vsizetype="Preferred">
-               <horstretch>0</horstretch>
-               <verstretch>0</verstretch>
-              </sizepolicy>
-             </property>
-             <property name="minimumSize">
-              <size>
-               <width>275</width>
-               <height>0</height>
-              </size>
-             </property>
+            <widget class="QGroupBox" name="groupBox_12">
              <property name="title">
-              <string>SANS2D Geometry (mm)</string>
-             </property>
-             <property name="checkable">
-              <bool>false</bool>
+              <string>Current ( x , y ) [mm]</string>
              </property>
-             <layout class="QGridLayout" name="gridLayout_26">
-              <property name="horizontalSpacing">
-               <number>6</number>
-              </property>
-              <property name="verticalSpacing">
-               <number>0</number>
-              </property>
-              <item row="1" column="1">
-               <widget class="QLabel" name="label_181">
-                <property name="text">
-                 <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
-&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
-p, li { white-space: pre-wrap; }
-&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;
-&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:8pt; font-weight:600;&quot;&gt;Sample&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
-                </property>
-               </widget>
-              </item>
-              <item row="1" column="2">
-               <widget class="QLabel" name="label_182">
-                <property name="text">
-                 <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
-&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
-p, li { white-space: pre-wrap; }
-&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;
-&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:8pt; font-weight:600;&quot;&gt;Can&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignCenter</set>
-                </property>
-               </widget>
-              </item>
-              <item row="2" column="0">
-               <widget class="QLabel" name="label_183">
-                <property name="sizePolicy">
-                 <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
-                  <horstretch>0</horstretch>
-                  <verstretch>0</verstretch>
-                 </sizepolicy>
-                </property>
-                <property name="text">
-                 <string>moderator - sample</string>
-                </property>
-               </widget>
-              </item>
-              <item row="3" column="0">
-               <widget class="QLabel" name="label_184">
-                <property name="sizePolicy">
-                 <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
-                  <horstretch>0</horstretch>
-                  <verstretch>0</verstretch>
-                 </sizepolicy>
-                </property>
-                <property name="text">
-                 <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
-&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
-p, li { white-space: pre-wrap; }
-&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal;&quot;&gt;
-&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;rear-detector:&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
-                </property>
-               </widget>
-              </item>
-              <item row="2" column="1">
-               <widget class="QLabel" name="dist_sample_ms_s2d">
-                <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-                </property>
-                <property name="textInteractionFlags">
-                 <set>Qt::LinksAccessibleByMouse</set>
-                </property>
-               </widget>
-              </item>
-              <item row="2" column="2">
-               <widget class="QLabel" name="dist_can_ms_s2d">
-                <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-                </property>
-                <property name="textInteractionFlags">
-                 <set>Qt::LinksAccessibleByMouse</set>
+             <layout class="QGridLayout" name="gridLayout_31">
+              <item row="0" column="0">
+               <widget class="QLineEdit" name="rear_beam_x">
+                <property name="maximumSize">
+                 <size>
+                  <width>70</width>
+                  <height>16777215</height>
+                 </size>
                 </property>
-               </widget>
-              </item>
-              <item row="1" column="3">
-               <widget class="QLabel" name="label_185">
                 <property name="text">
-                 <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
-&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
-p, li { white-space: pre-wrap; }
-&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;
-&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:8pt; font-weight:600;&quot;&gt;Bkgrd&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignCenter</set>
+                 <string/>
                 </property>
                </widget>
               </item>
-              <item row="2" column="3">
-               <widget class="QLabel" name="dist_bkgd_ms_s2d">
-                <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-                </property>
-                <property name="textInteractionFlags">
-                 <set>Qt::LinksAccessibleByMouse</set>
+              <item row="0" column="1">
+               <widget class="QLineEdit" name="rear_beam_y">
+                <property name="maximumSize">
+                 <size>
+                  <width>70</width>
+                  <height>16777215</height>
+                 </size>
                 </property>
                </widget>
               </item>
               <item row="0" column="2">
-               <widget class="QLabel" name="dist_mon_s2d">
-                <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignCenter</set>
-                </property>
-                <property name="textInteractionFlags">
-                 <set>Qt::LinksAccessibleByMouse</set>
-                </property>
-               </widget>
-              </item>
-              <item row="0" column="0" colspan="2">
-               <widget class="QLabel" name="label_186">
-                <property name="text">
-                 <string>moderator - monitor </string>
-                </property>
-               </widget>
-              </item>
-              <item row="4" column="0">
-               <widget class="QLabel" name="label_187">
-                <property name="text">
-                 <string>X</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignCenter</set>
-                </property>
-               </widget>
-              </item>
-              <item row="4" column="1">
-               <widget class="QLabel" name="dist_smp_rearX">
-                <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-                </property>
-                <property name="textInteractionFlags">
-                 <set>Qt::LinksAccessibleByMouse</set>
-                </property>
-               </widget>
-              </item>
-              <item row="4" column="2">
-               <widget class="QLabel" name="dist_can_rearX">
-                <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-                </property>
-                <property name="textInteractionFlags">
-                 <set>Qt::LinksAccessibleByMouse</set>
-                </property>
-               </widget>
-              </item>
-              <item row="4" column="3">
-               <widget class="QLabel" name="dist_bkgd_rearX">
-                <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-                </property>
-                <property name="textInteractionFlags">
-                 <set>Qt::LinksAccessibleByMouse</set>
-                </property>
-               </widget>
-              </item>
-              <item row="5" column="0">
-               <widget class="QLabel" name="label_188">
-                <property name="text">
-                 <string>Z</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignCenter</set>
-                </property>
-               </widget>
-              </item>
-              <item row="6" column="0">
-               <widget class="QLabel" name="label_189">
-                <property name="sizePolicy">
-                 <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
-                  <horstretch>0</horstretch>
-                  <verstretch>0</verstretch>
-                 </sizepolicy>
-                </property>
-                <property name="text">
-                 <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
-&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
-p, li { white-space: pre-wrap; }
-&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal;&quot;&gt;
-&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;front-detector:&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
-                </property>
-               </widget>
-              </item>
-              <item row="7" column="0">
-               <widget class="QLabel" name="label_190">
-                <property name="text">
-                 <string>X</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignCenter</set>
-                </property>
-               </widget>
-              </item>
-              <item row="8" column="0">
-               <widget class="QLabel" name="label_191">
-                <property name="text">
-                 <string>Z</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignCenter</set>
-                </property>
-               </widget>
-              </item>
-              <item row="9" column="0">
-               <widget class="QLabel" name="label_192">
-                <property name="text">
-                 <string>Rot</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignCenter</set>
-                </property>
-               </widget>
-              </item>
-              <item row="5" column="1">
-               <widget class="QLabel" name="dist_smp_rearZ">
-                <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-                </property>
-                <property name="textInteractionFlags">
-                 <set>Qt::LinksAccessibleByMouse</set>
-                </property>
-               </widget>
-              </item>
-              <item row="5" column="2">
-               <widget class="QLabel" name="dist_can_rearZ">
-                <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-                </property>
-                <property name="textInteractionFlags">
-                 <set>Qt::LinksAccessibleByMouse</set>
-                </property>
-               </widget>
-              </item>
-              <item row="5" column="3">
-               <widget class="QLabel" name="dist_bkgd_rearZ">
-                <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-                </property>
-                <property name="textInteractionFlags">
-                 <set>Qt::LinksAccessibleByMouse</set>
-                </property>
-               </widget>
-              </item>
-              <item row="7" column="1">
-               <widget class="QLabel" name="dist_smp_frontX">
-                <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-                </property>
-                <property name="textInteractionFlags">
-                 <set>Qt::LinksAccessibleByMouse</set>
-                </property>
-               </widget>
-              </item>
-              <item row="7" column="2">
-               <widget class="QLabel" name="dist_can_frontX">
+               <widget class="QRadioButton" name="rear_radio">
                 <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+                 <string>Rear</string>
                 </property>
-                <property name="textInteractionFlags">
-                 <set>Qt::LinksAccessibleByMouse</set>
+                <property name="checked">
+                 <bool>true</bool>
                 </property>
                </widget>
               </item>
-              <item row="7" column="3">
-               <widget class="QLabel" name="dist_bkgd_frontX">
-                <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-                </property>
-                <property name="textInteractionFlags">
-                 <set>Qt::LinksAccessibleByMouse</set>
+              <item row="1" column="0">
+               <widget class="QLineEdit" name="front_beam_x">
+                <property name="maximumSize">
+                 <size>
+                  <width>70</width>
+                  <height>16777215</height>
+                 </size>
                 </property>
-               </widget>
-              </item>
-              <item row="8" column="1">
-               <widget class="QLabel" name="dist_smp_frontZ">
                 <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-                </property>
-                <property name="textInteractionFlags">
-                 <set>Qt::LinksAccessibleByMouse</set>
+                 <string/>
                 </property>
                </widget>
               </item>
-              <item row="8" column="2">
-               <widget class="QLabel" name="dist_can_frontZ">
-                <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-                </property>
-                <property name="textInteractionFlags">
-                 <set>Qt::LinksAccessibleByMouse</set>
+              <item row="1" column="1">
+               <widget class="QLineEdit" name="front_beam_y">
+                <property name="maximumSize">
+                 <size>
+                  <width>70</width>
+                  <height>16777215</height>
+                 </size>
                 </property>
                </widget>
               </item>
-              <item row="8" column="3">
-               <widget class="QLabel" name="dist_bkgd_frontZ">
+              <item row="1" column="2">
+               <widget class="QRadioButton" name="front_radio">
                 <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-                </property>
-                <property name="textInteractionFlags">
-                 <set>Qt::LinksAccessibleByMouse</set>
+                 <string>Front</string>
                 </property>
                </widget>
               </item>
-              <item row="9" column="1">
-               <widget class="QLabel" name="smp_rot">
+             </layout>
+             <zorder>rear_beam_y</zorder>
+             <zorder>rear_radio</zorder>
+             <zorder>front_beam_y</zorder>
+             <zorder>front_beam_x</zorder>
+             <zorder>front_radio</zorder>
+             <zorder>rear_beam_x</zorder>
+            </widget>
+           </item>
+           <item>
+            <widget class="Line" name="line_3">
+             <property name="orientation">
+              <enum>Qt::Horizontal</enum>
+             </property>
+            </widget>
+           </item>
+           <item>
+            <widget class="QGroupBox" name="groupBox_8">
+             <property name="title">
+              <string>Automatic Search:</string>
+             </property>
+             <layout class="QVBoxLayout" name="verticalLayout_3">
+              <item>
+               <widget class="QLabel" name="label_59">
                 <property name="text">
-                 <string>-</string>
+                 <string>This will overwrite the coordinates above</string>
                 </property>
-                <property name="alignment">
-                 <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-                </property>
-                <property name="textInteractionFlags">
-                 <set>Qt::LinksAccessibleByMouse</set>
+                <property name="wordWrap">
+                 <bool>true</bool>
                 </property>
                </widget>
               </item>
-              <item row="9" column="2">
-               <widget class="QLabel" name="can_rot">
-                <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-                </property>
-                <property name="textInteractionFlags">
-                 <set>Qt::LinksAccessibleByMouse</set>
-                </property>
-               </widget>
+              <item>
+               <layout class="QHBoxLayout" name="horizontalLayout_19">
+                <item>
+                 <layout class="QGridLayout" name="gridLayout_8">
+                  <item row="0" column="0">
+                   <widget class="QLabel" name="label_56">
+                    <property name="text">
+                     <string>Starting position:</string>
+                    </property>
+                    <property name="alignment">
+                     <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+                    </property>
+                   </widget>
+                  </item>
+                  <item row="0" column="1" colspan="2">
+                   <widget class="QComboBox" name="beamstart_box">
+                    <property name="currentIndex">
+                     <number>1</number>
+                    </property>
+                    <item>
+                     <property name="text">
+                      <string>Auto Find</string>
+                     </property>
+                    </item>
+                    <item>
+                     <property name="text">
+                      <string>Current</string>
+                     </property>
+                    </item>
+                   </widget>
+                  </item>
+                  <item row="1" column="0">
+                   <widget class="QLabel" name="label_57">
+                    <property name="text">
+                     <string>Radius limits(mm):</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item row="1" column="1">
+                   <widget class="QLineEdit" name="beam_rmin">
+                    <property name="maximumSize">
+                     <size>
+                      <width>60</width>
+                      <height>16777215</height>
+                     </size>
+                    </property>
+                    <property name="text">
+                     <string>60</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item row="1" column="2">
+                   <widget class="QLineEdit" name="beam_rmax">
+                    <property name="maximumSize">
+                     <size>
+                      <width>60</width>
+                      <height>16777215</height>
+                     </size>
+                    </property>
+                    <property name="text">
+                     <string>200</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item row="2" column="0">
+                   <widget class="QLabel" name="label_60">
+                    <property name="text">
+                     <string>Max. iterations</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item row="2" column="1">
+                   <widget class="QLineEdit" name="beam_iter">
+                    <property name="maximumSize">
+                     <size>
+                      <width>40</width>
+                      <height>16777215</height>
+                     </size>
+                    </property>
+                    <property name="text">
+                     <string>10</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item row="3" column="0">
+                   <widget class="QLabel" name="label_35">
+                    <property name="text">
+                     <string>Status: </string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item row="3" column="1">
+                   <widget class="QLabel" name="centre_stat">
+                    <property name="frameShape">
+                     <enum>QFrame::Box</enum>
+                    </property>
+                    <property name="frameShadow">
+                     <enum>QFrame::Raised</enum>
+                    </property>
+                    <property name="text">
+                     <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
+&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
+p, li { white-space: pre-wrap; }
+&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal;&quot;&gt;
+&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;Stopped&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+                    </property>
+                    <property name="textFormat">
+                     <enum>Qt::RichText</enum>
+                    </property>
+                   </widget>
+                  </item>
+                 </layout>
+                </item>
+                <item>
+                 <spacer name="horizontalSpacer_7">
+                  <property name="orientation">
+                   <enum>Qt::Horizontal</enum>
+                  </property>
+                  <property name="sizeHint" stdset="0">
+                   <size>
+                    <width>10</width>
+                    <height>20</height>
+                   </size>
+                  </property>
+                 </spacer>
+                </item>
+                <item>
+                 <layout class="QVBoxLayout" name="verticalLayout_4">
+                  <item>
+                   <spacer name="verticalSpacer_2">
+                    <property name="orientation">
+                     <enum>Qt::Vertical</enum>
+                    </property>
+                    <property name="sizeType">
+                     <enum>QSizePolicy::Preferred</enum>
+                    </property>
+                    <property name="sizeHint" stdset="0">
+                     <size>
+                      <width>20</width>
+                      <height>40</height>
+                     </size>
+                    </property>
+                   </spacer>
+                  </item>
+                  <item>
+                   <layout class="QHBoxLayout" name="horizontalLayout_8">
+                    <item>
+                     <widget class="QLabel" name="label_14">
+                      <property name="text">
+                       <string>Tolerance 
+[um]</string>
+                      </property>
+                      <property name="alignment">
+                       <set>Qt::AlignCenter</set>
+                      </property>
+                     </widget>
+                    </item>
+                    <item>
+                     <widget class="QLineEdit" name="toleranceLineEdit">
+                      <property name="maximumSize">
+                       <size>
+                        <width>60</width>
+                        <height>16777215</height>
+                       </size>
+                      </property>
+                      <property name="text">
+                       <string>1.251</string>
+                      </property>
+                     </widget>
+                    </item>
+                   </layout>
+                  </item>
+                 </layout>
+                </item>
+               </layout>
               </item>
-              <item row="9" column="3">
-               <widget class="QLabel" name="bkgd_rot">
-                <property name="text">
-                 <string>-</string>
-                </property>
-                <property name="alignment">
-                 <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
-                </property>
-                <property name="textInteractionFlags">
-                 <set>Qt::LinksAccessibleByMouse</set>
+              <item>
+               <widget class="MantidQt::MantidWidgets::MessageDisplay" name="centre_logging" native="true">
+                <property name="source" stdset="0">
+                 <string>CentreFinder</string>
                 </property>
                </widget>
               </item>
-              <item row="1" column="0">
-               <spacer name="horizontalSpacer_21">
-                <property name="orientation">
-                 <enum>Qt::Horizontal</enum>
-                </property>
-                <property name="sizeType">
-                 <enum>QSizePolicy::Fixed</enum>
-                </property>
-                <property name="sizeHint" stdset="0">
-                 <size>
-                  <width>110</width>
-                  <height>20</height>
-                 </size>
-                </property>
-               </spacer>
+              <item>
+               <layout class="QHBoxLayout" name="horizontalLayout_23">
+                <item>
+                 <spacer name="horizontalSpacer_24">
+                  <property name="orientation">
+                   <enum>Qt::Horizontal</enum>
+                  </property>
+                  <property name="sizeHint" stdset="0">
+                   <size>
+                    <width>40</width>
+                    <height>20</height>
+                   </size>
+                  </property>
+                 </spacer>
+                </item>
+                <item>
+                 <widget class="QPushButton" name="runcentreBtn">
+                  <property name="text">
+                   <string>Run</string>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QPushButton" name="clear_centre_log">
+                  <property name="text">
+                   <string>Clear log</string>
+                  </property>
+                 </widget>
+                </item>
+               </layout>
               </item>
              </layout>
             </widget>
            </item>
           </layout>
          </widget>
-        </widget>
-       </item>
-       <item row="0" column="1" rowspan="2">
-        <widget class="QGroupBox" name="groupBox_13">
-         <property name="title">
-          <string>Beam Centre</string>
-         </property>
-         <property name="flat">
-          <bool>false</bool>
-         </property>
-         <property name="checkable">
-          <bool>false</bool>
-         </property>
-         <layout class="QVBoxLayout" name="verticalLayout_12" stretch="1,1,2">
+        </item>
+       </layout>
+      </widget>
+      <widget class="QWidget" name="tab_3">
+       <attribute name="title">
+        <string>Masking</string>
+       </attribute>
+       <layout class="QHBoxLayout" name="horizontalLayout_3">
+        <item>
+         <spacer name="horizontalSpacer_15">
+          <property name="orientation">
+           <enum>Qt::Horizontal</enum>
+          </property>
+          <property name="sizeType">
+           <enum>QSizePolicy::Preferred</enum>
+          </property>
+          <property name="sizeHint" stdset="0">
+           <size>
+            <width>20</width>
+            <height>20</height>
+           </size>
+          </property>
+         </spacer>
+        </item>
+        <item>
+         <layout class="QVBoxLayout" name="verticalLayout_6">
           <item>
-           <widget class="QGroupBox" name="groupBox_12">
+           <widget class="QGroupBox" name="groupBox_10">
+            <property name="sizePolicy">
+             <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+              <horstretch>0</horstretch>
+              <verstretch>1</verstretch>
+             </sizepolicy>
+            </property>
+            <property name="minimumSize">
+             <size>
+              <width>0</width>
+              <height>0</height>
+             </size>
+            </property>
             <property name="title">
-             <string>Current ( x , y ) [mm]</string>
+             <string>Default Mask</string>
             </property>
-            <layout class="QGridLayout" name="gridLayout_31">
-             <item row="0" column="0">
-              <widget class="QLineEdit" name="rear_beam_x">
-               <property name="maximumSize">
-                <size>
-                 <width>70</width>
-                 <height>16777215</height>
-                </size>
-               </property>
-               <property name="text">
-                <string/>
-               </property>
-              </widget>
-             </item>
-             <item row="0" column="1">
-              <widget class="QLineEdit" name="rear_beam_y">
-               <property name="maximumSize">
-                <size>
-                 <width>70</width>
-                 <height>16777215</height>
-                </size>
-               </property>
-              </widget>
-             </item>
-             <item row="0" column="2">
-              <widget class="QRadioButton" name="rear_radio">
-               <property name="text">
-                <string>Rear</string>
-               </property>
-               <property name="checked">
-                <bool>true</bool>
-               </property>
-              </widget>
-             </item>
-             <item row="1" column="0">
-              <widget class="QLineEdit" name="front_beam_x">
-               <property name="maximumSize">
-                <size>
-                 <width>70</width>
-                 <height>16777215</height>
-                </size>
-               </property>
-               <property name="text">
-                <string/>
+            <layout class="QVBoxLayout" name="verticalLayout">
+             <item>
+              <widget class="QTableWidget" name="mask_table">
+               <property name="sizePolicy">
+                <sizepolicy hsizetype="Expanding" vsizetype="Preferred">
+                 <horstretch>1</horstretch>
+                 <verstretch>1</verstretch>
+                </sizepolicy>
                </property>
-              </widget>
-             </item>
-             <item row="1" column="1">
-              <widget class="QLineEdit" name="front_beam_y">
-               <property name="maximumSize">
+               <property name="minimumSize">
                 <size>
-                 <width>70</width>
-                 <height>16777215</height>
+                 <width>315</width>
+                 <height>0</height>
                 </size>
                </property>
-              </widget>
-             </item>
-             <item row="1" column="2">
-              <widget class="QRadioButton" name="front_radio">
-               <property name="text">
-                <string>Front</string>
+               <property name="horizontalScrollBarPolicy">
+                <enum>Qt::ScrollBarAsNeeded</enum>
                </property>
-              </widget>
-             </item>
-            </layout>
-            <zorder>rear_beam_y</zorder>
-            <zorder>rear_radio</zorder>
-            <zorder>front_beam_y</zorder>
-            <zorder>front_beam_x</zorder>
-            <zorder>front_radio</zorder>
-            <zorder>rear_beam_x</zorder>
-           </widget>
-          </item>
-          <item>
-           <widget class="Line" name="line_3">
-            <property name="orientation">
-             <enum>Qt::Horizontal</enum>
-            </property>
-           </widget>
-          </item>
-          <item>
-           <widget class="QGroupBox" name="groupBox_8">
-            <property name="title">
-             <string>Automatic Search:</string>
-            </property>
-            <layout class="QVBoxLayout" name="verticalLayout_3">
-             <item>
-              <widget class="QLabel" name="label_59">
-               <property name="text">
-                <string>This will overwrite the coordinates above</string>
+               <property name="editTriggers">
+                <set>QAbstractItemView::NoEditTriggers</set>
                </property>
-               <property name="wordWrap">
-                <bool>true</bool>
+               <property name="textElideMode">
+                <enum>Qt::ElideNone</enum>
                </property>
-              </widget>
-             </item>
-             <item>
-              <layout class="QHBoxLayout" name="horizontalLayout_19">
-               <item>
-                <layout class="QGridLayout" name="gridLayout_8">
-                 <item row="0" column="0">
-                  <widget class="QLabel" name="label_56">
-                   <property name="text">
-                    <string>Starting position:</string>
-                   </property>
-                   <property name="alignment">
-                    <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
-                   </property>
-                  </widget>
-                 </item>
-                 <item row="0" column="1" colspan="2">
-                  <widget class="QComboBox" name="beamstart_box">
-                   <property name="currentIndex">
-                    <number>1</number>
-                   </property>
-                   <item>
-                    <property name="text">
-                     <string>Auto Find</string>
-                    </property>
-                   </item>
-                   <item>
-                    <property name="text">
-                     <string>Current</string>
-                    </property>
-                   </item>
-                  </widget>
-                 </item>
-                 <item row="1" column="0">
-                  <widget class="QLabel" name="label_57">
-                   <property name="text">
-                    <string>Radius limits(mm):</string>
-                   </property>
-                  </widget>
-                 </item>
-                 <item row="1" column="1">
-                  <widget class="QLineEdit" name="beam_rmin">
-                   <property name="maximumSize">
-                    <size>
-                     <width>60</width>
-                     <height>16777215</height>
-                    </size>
-                   </property>
-                   <property name="text">
-                    <string>60</string>
-                   </property>
-                  </widget>
-                 </item>
-                 <item row="1" column="2">
-                  <widget class="QLineEdit" name="beam_rmax">
-                   <property name="maximumSize">
-                    <size>
-                     <width>60</width>
-                     <height>16777215</height>
-                    </size>
-                   </property>
-                   <property name="text">
-                    <string>200</string>
-                   </property>
-                  </widget>
-                 </item>
-                 <item row="2" column="0">
-                  <widget class="QLabel" name="label_60">
-                   <property name="text">
-                    <string>Max. iterations</string>
-                   </property>
-                  </widget>
-                 </item>
-                 <item row="2" column="1">
-                  <widget class="QLineEdit" name="beam_iter">
-                   <property name="maximumSize">
-                    <size>
-                     <width>40</width>
-                     <height>16777215</height>
-                    </size>
-                   </property>
-                   <property name="text">
-                    <string>10</string>
-                   </property>
-                  </widget>
-                 </item>
-                 <item row="3" column="0">
-                  <widget class="QLabel" name="label_35">
-                   <property name="text">
-                    <string>Status: </string>
-                   </property>
-                  </widget>
-                 </item>
-                 <item row="3" column="1">
-                  <widget class="QLabel" name="centre_stat">
-                   <property name="frameShape">
-                    <enum>QFrame::Box</enum>
-                   </property>
-                   <property name="frameShadow">
-                    <enum>QFrame::Raised</enum>
-                   </property>
-                   <property name="text">
-                    <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
-&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
-p, li { white-space: pre-wrap; }
-&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal;&quot;&gt;
-&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;Stopped&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
-                   </property>
-                   <property name="textFormat">
-                    <enum>Qt::RichText</enum>
-                   </property>
-                  </widget>
-                 </item>
-                </layout>
-               </item>
-               <item>
-                <spacer name="horizontalSpacer_7">
-                 <property name="orientation">
-                  <enum>Qt::Horizontal</enum>
-                 </property>
-                 <property name="sizeHint" stdset="0">
-                  <size>
-                   <width>10</width>
-                   <height>20</height>
-                  </size>
-                 </property>
-                </spacer>
-               </item>
-               <item>
-                <layout class="QVBoxLayout" name="verticalLayout_4">
-                 <item>
-                  <spacer name="verticalSpacer_2">
-                   <property name="orientation">
-                    <enum>Qt::Vertical</enum>
-                   </property>
-                   <property name="sizeType">
-                    <enum>QSizePolicy::Preferred</enum>
-                   </property>
-                   <property name="sizeHint" stdset="0">
-                    <size>
-                     <width>20</width>
-                     <height>40</height>
-                    </size>
-                   </property>
-                  </spacer>
-                 </item>
-                 <item>
-                  <layout class="QHBoxLayout" name="horizontalLayout_8">
-                   <item>
-                    <widget class="QLabel" name="label_14">
-                     <property name="text">
-                      <string>Tolerance 
-[um]</string>
-                     </property>
-                     <property name="alignment">
-                      <set>Qt::AlignCenter</set>
-                     </property>
-                    </widget>
-                   </item>
-                   <item>
-                    <widget class="QLineEdit" name="toleranceLineEdit">
-                     <property name="maximumSize">
-                      <size>
-                       <width>60</width>
-                       <height>16777215</height>
-                      </size>
-                     </property>
-                     <property name="text">
-                      <string>1.251</string>
-                     </property>
-                    </widget>
-                   </item>
-                  </layout>
-                 </item>
-                </layout>
-               </item>
-              </layout>
-             </item>
-             <item>
-              <widget class="MantidQt::MantidWidgets::MessageDisplay" name="centre_logging" native="true">
-               <property name="source" stdset="0">
-                <string>CentreFinder</string>
+               <property name="wordWrap">
+                <bool>true</bool>
                </property>
+               <column>
+                <property name="text">
+                 <string>Type</string>
+                </property>
+               </column>
+               <column>
+                <property name="text">
+                 <string>Detector</string>
+                </property>
+               </column>
+               <column>
+                <property name="text">
+                 <string>Details</string>
+                </property>
+               </column>
               </widget>
              </item>
-             <item>
-              <layout class="QHBoxLayout" name="horizontalLayout_23">
-               <item>
-                <spacer name="horizontalSpacer_24">
-                 <property name="orientation">
-                  <enum>Qt::Horizontal</enum>
-                 </property>
-                 <property name="sizeHint" stdset="0">
-                  <size>
-                   <width>40</width>
-                   <height>20</height>
-                  </size>
-                 </property>
-                </spacer>
-               </item>
-               <item>
-                <widget class="QPushButton" name="runcentreBtn">
-                 <property name="text">
-                  <string>Run</string>
-                 </property>
-                </widget>
-               </item>
-               <item>
-                <widget class="QPushButton" name="clear_centre_log">
-                 <property name="text">
-                  <string>Clear log</string>
-                 </property>
-                </widget>
-               </item>
-              </layout>
-             </item>
             </layout>
            </widget>
           </item>
-         </layout>
-        </widget>
-       </item>
-      </layout>
-     </widget>
-     <widget class="QWidget" name="tab_3">
-      <attribute name="title">
-       <string>Masking</string>
-      </attribute>
-      <layout class="QHBoxLayout" name="horizontalLayout_3">
-       <item>
-        <spacer name="horizontalSpacer_15">
-         <property name="orientation">
-          <enum>Qt::Horizontal</enum>
-         </property>
-         <property name="sizeType">
-          <enum>QSizePolicy::Preferred</enum>
-         </property>
-         <property name="sizeHint" stdset="0">
-          <size>
-           <width>20</width>
-           <height>20</height>
-          </size>
-         </property>
-        </spacer>
-       </item>
-       <item>
-        <layout class="QVBoxLayout" name="verticalLayout_6">
-         <item>
-          <widget class="QGroupBox" name="groupBox_10">
-           <property name="sizePolicy">
-            <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
-             <horstretch>0</horstretch>
-             <verstretch>1</verstretch>
-            </sizepolicy>
-           </property>
-           <property name="minimumSize">
-            <size>
-             <width>0</width>
-             <height>0</height>
-            </size>
-           </property>
-           <property name="title">
-            <string>Default Mask</string>
-           </property>
-           <layout class="QVBoxLayout" name="verticalLayout">
+          <item>
+           <layout class="QHBoxLayout" name="horizontalLayout_7">
             <item>
-             <widget class="QTableWidget" name="mask_table">
-              <property name="sizePolicy">
-               <sizepolicy hsizetype="Expanding" vsizetype="Preferred">
-                <horstretch>1</horstretch>
-                <verstretch>1</verstretch>
-               </sizepolicy>
+             <spacer name="horizontalSpacer_12">
+              <property name="orientation">
+               <enum>Qt::Horizontal</enum>
               </property>
-              <property name="minimumSize">
+              <property name="sizeHint" stdset="0">
                <size>
-                <width>315</width>
-                <height>0</height>
+                <width>40</width>
+                <height>20</height>
                </size>
               </property>
-              <property name="horizontalScrollBarPolicy">
-               <enum>Qt::ScrollBarAsNeeded</enum>
-              </property>
-              <property name="editTriggers">
-               <set>QAbstractItemView::NoEditTriggers</set>
-              </property>
-              <property name="textElideMode">
-               <enum>Qt::ElideNone</enum>
-              </property>
-              <property name="wordWrap">
-               <bool>true</bool>
-              </property>
-              <column>
-               <property name="text">
-                <string>Type</string>
-               </property>
-              </column>
-              <column>
-               <property name="text">
-                <string>Detector</string>
-               </property>
-              </column>
-              <column>
-               <property name="text">
-                <string>Details</string>
-               </property>
-              </column>
-             </widget>
+             </spacer>
             </item>
-           </layout>
-          </widget>
-         </item>
-         <item>
-          <layout class="QHBoxLayout" name="horizontalLayout_7">
-           <item>
-            <spacer name="horizontalSpacer_12">
-             <property name="orientation">
-              <enum>Qt::Horizontal</enum>
-             </property>
-             <property name="sizeHint" stdset="0">
-              <size>
-               <width>40</width>
-               <height>20</height>
-              </size>
-             </property>
-            </spacer>
-           </item>
-           <item>
-            <widget class="QPushButton" name="showMaskBtn">
-             <property name="sizePolicy">
-              <sizepolicy hsizetype="Minimum" vsizetype="Maximum">
-               <horstretch>0</horstretch>
-               <verstretch>0</verstretch>
-              </sizepolicy>
-             </property>
-             <property name="text">
-              <string>Display mask</string>
-             </property>
-            </widget>
-           </item>
-           <item>
-            <spacer name="horizontalSpacer_13">
-             <property name="orientation">
-              <enum>Qt::Horizontal</enum>
-             </property>
-             <property name="sizeHint" stdset="0">
-              <size>
-               <width>40</width>
-               <height>20</height>
-              </size>
-             </property>
-            </spacer>
-           </item>
-          </layout>
-         </item>
-        </layout>
-       </item>
-       <item>
-        <spacer name="horizontalSpacer_14">
-         <property name="orientation">
-          <enum>Qt::Horizontal</enum>
-         </property>
-         <property name="sizeType">
-          <enum>QSizePolicy::Preferred</enum>
-         </property>
-         <property name="sizeHint" stdset="0">
-          <size>
-           <width>30</width>
-           <height>20</height>
-          </size>
-         </property>
-        </spacer>
-       </item>
-       <item>
-        <layout class="QVBoxLayout" name="verticalLayout_7">
-         <item>
-          <widget class="QGroupBox" name="groupBox_11">
-           <property name="sizePolicy">
-            <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
-             <horstretch>0</horstretch>
-             <verstretch>0</verstretch>
-            </sizepolicy>
-           </property>
-           <property name="title">
-            <string>User Mask</string>
-           </property>
-           <layout class="QVBoxLayout" name="verticalLayout_2">
             <item>
-             <widget class="QLabel" name="label_25">
+             <widget class="QPushButton" name="showMaskBtn">
               <property name="sizePolicy">
-               <sizepolicy hsizetype="Preferred" vsizetype="Maximum">
+               <sizepolicy hsizetype="Minimum" vsizetype="Maximum">
                 <horstretch>0</horstretch>
                 <verstretch>0</verstretch>
                </sizepolicy>
               </property>
               <property name="text">
-               <string>Enter additional spectra masks (separated by a comma) e.g. S8000,H190&gt;H191,H0&gt;H5+V0&gt;V5</string>
-              </property>
-              <property name="wordWrap">
-               <bool>true</bool>
-              </property>
-             </widget>
-            </item>
-            <item>
-             <widget class="QLineEdit" name="user_spec_mask">
-              <property name="minimumSize">
-               <size>
-                <width>300</width>
-                <height>0</height>
-               </size>
-              </property>
-              <property name="text">
-               <string/>
+               <string>Display mask</string>
               </property>
              </widget>
             </item>
             <item>
-             <widget class="QLabel" name="label_9">
-              <property name="sizePolicy">
-               <sizepolicy hsizetype="Preferred" vsizetype="Maximum">
-                <horstretch>0</horstretch>
-                <verstretch>0</verstretch>
-               </sizepolicy>
+             <spacer name="horizontalSpacer_13">
+              <property name="orientation">
+               <enum>Qt::Horizontal</enum>
               </property>
-              <property name="maximumSize">
+              <property name="sizeHint" stdset="0">
                <size>
-                <width>16777215</width>
-                <height>16777215</height>
+                <width>40</width>
+                <height>20</height>
                </size>
               </property>
-              <property name="text">
-               <string>Enter additional time range masks (separated by a comma e.g. 10000. 11000.,12000. 13000.)</string>
-              </property>
-              <property name="wordWrap">
-               <bool>true</bool>
-              </property>
-             </widget>
-            </item>
-            <item>
-             <widget class="QLineEdit" name="user_time_mask"/>
+             </spacer>
             </item>
            </layout>
-          </widget>
-         </item>
-         <item>
-          <spacer name="verticalSpacer_4">
-           <property name="orientation">
-            <enum>Qt::Vertical</enum>
-           </property>
-           <property name="sizeHint" stdset="0">
-            <size>
-             <width>20</width>
-             <height>40</height>
-            </size>
-           </property>
-          </spacer>
-         </item>
-        </layout>
-       </item>
-       <item>
-        <spacer name="horizontalSpacer_3">
-         <property name="orientation">
-          <enum>Qt::Horizontal</enum>
-         </property>
-         <property name="sizeType">
-          <enum>QSizePolicy::Preferred</enum>
-         </property>
-         <property name="sizeHint" stdset="0">
-          <size>
-           <width>20</width>
-           <height>20</height>
-          </size>
-         </property>
-        </spacer>
-       </item>
-      </layout>
-     </widget>
-     <widget class="QWidget" name="tab_5">
-      <attribute name="title">
-       <string>Logging</string>
-      </attribute>
-      <layout class="QGridLayout" name="gridLayout_15">
-       <item row="1" column="2">
-        <layout class="QVBoxLayout" name="verticalLayout_10">
-         <item>
-          <spacer name="verticalSpacer_3">
-           <property name="orientation">
-            <enum>Qt::Vertical</enum>
-           </property>
-           <property name="sizeHint" stdset="0">
-            <size>
-             <width>20</width>
-             <height>40</height>
-            </size>
-           </property>
-          </spacer>
-         </item>
-        </layout>
-       </item>
-       <item row="2" column="1">
-        <layout class="QHBoxLayout" name="horizontalLayout_5">
-         <item>
-          <spacer name="horizontalSpacer_20">
-           <property name="orientation">
-            <enum>Qt::Horizontal</enum>
-           </property>
-           <property name="sizeHint" stdset="0">
-            <size>
-             <width>40</width>
-             <height>20</height>
-            </size>
-           </property>
-          </spacer>
-         </item>
-         <item>
-          <widget class="QPushButton" name="logger_clear">
-           <property name="text">
-            <string>Clear</string>
-           </property>
-          </widget>
-         </item>
-         <item>
-          <spacer name="horizontalSpacer_5">
-           <property name="orientation">
-            <enum>Qt::Horizontal</enum>
-           </property>
-           <property name="sizeHint" stdset="0">
-            <size>
-             <width>40</width>
-             <height>20</height>
-            </size>
-           </property>
-          </spacer>
-         </item>
-        </layout>
-       </item>
-       <item row="0" column="1">
-        <widget class="QLabel" name="label_29">
-         <property name="text">
-          <string>Log messages:</string>
-         </property>
-        </widget>
-       </item>
-       <item row="1" column="1">
-        <widget class="MantidQt::MantidWidgets::MessageDisplay" name="logging_field" native="true">
-         <property name="source" stdset="0">
-          <string>SANS</string>
-         </property>
-        </widget>
-       </item>
-       <item row="1" column="0">
-        <layout class="QVBoxLayout" name="verticalLayout_14">
-         <item>
-          <spacer name="verticalSpacer_5">
-           <property name="orientation">
-            <enum>Qt::Vertical</enum>
-           </property>
-           <property name="sizeHint" stdset="0">
-            <size>
-             <width>20</width>
-             <height>40</height>
-            </size>
-           </property>
-          </spacer>
-         </item>
-        </layout>
-       </item>
-      </layout>
-     </widget>
-     <widget class="QWidget" name="AddRuns">
-      <attribute name="title">
-       <string>Add Runs</string>
-      </attribute>
-      <layout class="QGridLayout" name="gridLayout_18">
-       <item row="0" column="2">
-        <spacer name="verticalSpacer_9">
-         <property name="orientation">
-          <enum>Qt::Vertical</enum>
-         </property>
-         <property name="sizeHint" stdset="0">
-          <size>
-           <width>20</width>
-           <height>40</height>
-          </size>
-         </property>
-        </spacer>
-       </item>
-       <item row="1" column="0">
-        <spacer name="horizontalSpacer_11">
-         <property name="orientation">
-          <enum>Qt::Horizontal</enum>
-         </property>
-         <property name="sizeType">
-          <enum>QSizePolicy::Maximum</enum>
-         </property>
-         <property name="sizeHint" stdset="0">
-          <size>
-           <width>40</width>
-           <height>20</height>
-          </size>
-         </property>
-        </spacer>
-       </item>
-       <item row="1" column="2">
-        <widget class="QLabel" name="summedPath_lb">
-         <property name="text">
-          <string/>
-         </property>
-        </widget>
-       </item>
-       <item row="3" column="2">
-        <spacer name="verticalSpacer_10">
-         <property name="orientation">
-          <enum>Qt::Vertical</enum>
-         </property>
-         <property name="sizeHint" stdset="0">
-          <size>
-           <width>20</width>
-           <height>40</height>
-          </size>
-         </property>
-        </spacer>
-       </item>
-       <item row="4" column="0" colspan="2">
-        <widget class="QLabel" name="label_42">
-         <property name="sizePolicy">
-          <sizepolicy hsizetype="Fixed" vsizetype="Preferred">
-           <horstretch>0</horstretch>
-           <verstretch>0</verstretch>
-          </sizepolicy>
-         </property>
-         <property name="maximumSize">
-          <size>
-           <width>100</width>
-           <height>16777215</height>
-          </size>
-         </property>
-         <property name="toolTip">
-          <string>Type , separated lists of run numbers or ranges of numbers with a : </string>
-         </property>
-         <property name="text">
-          <string/>
-         </property>
-        </widget>
-       </item>
-       <item row="4" column="2">
-        <widget class="QLineEdit" name="new2Add_edit">
-         <property name="toolTip">
-          <string>Type , separated lists of run numbers or ranges of numbers with a : </string>
-         </property>
-        </widget>
-       </item>
-       <item row="4" column="3">
-        <widget class="QPushButton" name="add_Btn">
-         <property name="toolTip">
-          <string>Adds entries to the big table, use before clicking &quot;Sum&quot;.</string>
-         </property>
-         <property name="text">
-          <string>Add</string>
-         </property>
-        </widget>
-       </item>
-       <item row="4" column="4">
-        <widget class="QPushButton" name="browse_to_add_Btn">
-         <property name="toolTip">
-          <string>Find a file on your system</string>
-         </property>
-         <property name="text">
-          <string>Browse</string>
-         </property>
-        </widget>
-       </item>
-       <item row="4" column="5">
-        <spacer name="horizontalSpacer_18">
-         <property name="orientation">
-          <enum>Qt::Horizontal</enum>
-         </property>
-         <property name="sizeType">
-          <enum>QSizePolicy::Maximum</enum>
-         </property>
-         <property name="sizeHint" stdset="0">
-          <size>
-           <width>40</width>
-           <height>20</height>
-          </size>
-         </property>
-        </spacer>
-       </item>
-       <item row="5" column="0">
-        <widget class="QLabel" name="label_46">
-         <property name="toolTip">
-          <string>Files to be summed, click at the top of this box or use the &quot;Add&quot; button</string>
-         </property>
-         <property name="text">
-          <string>Run files to sum</string>
-         </property>
-        </widget>
-       </item>
-       <item row="5" column="1" rowspan="3" colspan="2">
-        <widget class="QListWidget" name="toAdd_List">
-         <property name="toolTip">
-          <string>Files to be summed, click at the top of this box or use the &quot;Add&quot; button</string>
-         </property>
-         <property name="editTriggers">
-          <set>QAbstractItemView::AnyKeyPressed|QAbstractItemView::DoubleClicked|QAbstractItemView::EditKeyPressed|QAbstractItemView::SelectedClicked</set>
-         </property>
-         <property name="selectionMode">
-          <enum>QAbstractItemView::ExtendedSelection</enum>
-         </property>
-         <property name="selectionBehavior">
-          <enum>QAbstractItemView::SelectRows</enum>
-         </property>
-         <property name="resizeMode">
-          <enum>QListView::Fixed</enum>
-         </property>
-         <property name="currentRow">
-          <number>-1</number>
-         </property>
-        </widget>
-       </item>
-       <item row="5" column="3">
-        <widget class="QPushButton" name="clear_Btn">
-         <property name="toolTip">
-          <string>Clear the table</string>
-         </property>
-         <property name="text">
-          <string>Remove all</string>
-         </property>
-        </widget>
-       </item>
-       <item row="6" column="3">
-        <widget class="QPushButton" name="remove_Btn">
-         <property name="toolTip">
-          <string>Select rows by clicking on the table and remove then with this button</string>
-         </property>
-         <property name="text">
-          <string>Remove</string>
-         </property>
-        </widget>
-       </item>
-       <item row="7" column="3">
-        <spacer name="verticalSpacer_7">
-         <property name="orientation">
-          <enum>Qt::Vertical</enum>
-         </property>
-         <property name="sizeHint" stdset="0">
-          <size>
-           <width>20</width>
-           <height>40</height>
-          </size>
-         </property>
-        </spacer>
-       </item>
-       <item row="1" column="4">
-        <widget class="QPushButton" name="summedPath_Btn">
-         <property name="toolTip">
-          <string>The directory to created the summed run file in</string>
-         </property>
-         <property name="text">
-          <string>Manage Directories</string>
-         </property>
-        </widget>
-       </item>
-       <item row="2" column="2">
-        <widget class="QCheckBox" name="loadSeparateEntries">
-         <property name="text">
-          <string>Minimise memory usage</string>
-         </property>
-        </widget>
-       </item>
-       <item row="11" column="2">
-        <widget class="QLineEdit" name="eventToHistBinning">
-         <property name="text">
-          <string>5.5,45.5,50.0, 50.0,1000.0, 500.0,1500.0, 750.0,99750.0, 255.0,100005.0</string>
-         </property>
-        </widget>
-       </item>
-       <item row="9" column="2">
-        <widget class="QLabel" name="label">
-         <property name="text">
-          <string>Histogram binning (when adding event data):</string>
-         </property>
-        </widget>
-       </item>
-       <item row="8" column="3">
-        <widget class="QPushButton" name="sum_Btn">
-         <property name="toolTip">
-          <string>Load the files in the table above and save them to one file</string>
-         </property>
-         <property name="text">
-          <string>Sum</string>
-         </property>
-        </widget>
-       </item>
-       <item row="12" column="2">
-        <widget class="QCheckBox" name="takeBinningFromMonitors">
-         <property name="text">
-          <string>Use binning from monitors</string>
-         </property>
-         <property name="checked">
-          <bool>true</bool>
-         </property>
-        </widget>
-       </item>
-      </layout>
-     </widget>
-     <widget class="QWidget" name="widget">
-      <attribute name="title">
-       <string>Diagnostics</string>
-      </attribute>
-      <layout class="QGridLayout" name="gridLayout_25">
-       <item row="0" column="0">
-        <layout class="QGridLayout" name="gridLayout_23">
-         <property name="sizeConstraint">
-          <enum>QLayout::SetDefaultConstraint</enum>
-         </property>
-         <property name="verticalSpacing">
-          <number>6</number>
-         </property>
-         <item row="0" column="0">
-          <widget class="MantidQt::MantidWidgets::MWRunFiles" name="file_run_edit" native="true">
-           <property name="sizePolicy">
-            <sizepolicy hsizetype="MinimumExpanding" vsizetype="Minimum">
-             <horstretch>0</horstretch>
-             <verstretch>0</verstretch>
-            </sizepolicy>
-           </property>
-           <property name="maximumSize">
-            <size>
-             <width>16777215</width>
-             <height>16777215</height>
-            </size>
-           </property>
-           <property name="label" stdset="0">
-            <string>File/Run:</string>
-           </property>
-           <property name="multipleFiles" stdset="0">
-            <bool>false</bool>
-           </property>
-          </widget>
-         </item>
-         <item row="0" column="1">
-          <widget class="QLabel" name="label_period">
-           <property name="text">
-            <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
-&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
-p, li { white-space: pre-wrap; }
-&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;
-&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:8pt;&quot;&gt;Period :&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
-           </property>
-          </widget>
-         </item>
-         <item row="0" column="2">
-          <widget class="QLineEdit" name="period_edit">
-           <property name="minimumSize">
-            <size>
-             <width>25</width>
-             <height>0</height>
-            </size>
-           </property>
-           <property name="maximumSize">
-            <size>
-             <width>25</width>
-             <height>20</height>
-            </size>
-           </property>
-          </widget>
-         </item>
-         <item row="0" column="3">
-          <widget class="QLabel" name="total_perioids">
-           <property name="text">
-            <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
-&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
-p, li { white-space: pre-wrap; }
-&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;
-&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:12pt;&quot;&gt;/n&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
-           </property>
-          </widget>
-         </item>
-        </layout>
-       </item>
-       <item row="1" column="0">
-        <widget class="QLabel" name="label_7">
-         <property name="text">
-          <string>The format of Range string for example is 60-65 or 60-66:2 or 60:66 or 60:66:2 or 60+61 or 60-65,66,67,68:72:2,73+74</string>
-         </property>
-        </widget>
-       </item>
-       <item row="2" column="0">
-        <widget class="QGroupBox" name="groupBox_Detector1">
-         <property name="title">
-          <string> Detector1</string>
-         </property>
-         <layout class="QGridLayout" name="gridLayout_22">
-          <item row="0" column="0">
-           <widget class="QPushButton" name="hi_Btn1">
-            <property name="text">
-             <string>Horizontal Integral</string>
-            </property>
-           </widget>
           </item>
-          <item row="0" column="1">
-           <widget class="QLabel" name="hrange_det1">
-            <property name="text">
-             <string>Range:</string>
+         </layout>
+        </item>
+        <item>
+         <spacer name="horizontalSpacer_14">
+          <property name="orientation">
+           <enum>Qt::Horizontal</enum>
+          </property>
+          <property name="sizeType">
+           <enum>QSizePolicy::Preferred</enum>
+          </property>
+          <property name="sizeHint" stdset="0">
+           <size>
+            <width>30</width>
+            <height>20</height>
+           </size>
+          </property>
+         </spacer>
+        </item>
+        <item>
+         <layout class="QVBoxLayout" name="verticalLayout_7">
+          <item>
+           <widget class="QGroupBox" name="groupBox_11">
+            <property name="sizePolicy">
+             <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+              <horstretch>0</horstretch>
+              <verstretch>0</verstretch>
+             </sizepolicy>
+            </property>
+            <property name="title">
+             <string>User Mask</string>
             </property>
+            <layout class="QVBoxLayout" name="verticalLayout_2">
+             <item>
+              <widget class="QLabel" name="label_25">
+               <property name="sizePolicy">
+                <sizepolicy hsizetype="Preferred" vsizetype="Maximum">
+                 <horstretch>0</horstretch>
+                 <verstretch>0</verstretch>
+                </sizepolicy>
+               </property>
+               <property name="text">
+                <string>Enter additional spectra masks (separated by a comma) e.g. S8000,H190&gt;H191,H0&gt;H5+V0&gt;V5</string>
+               </property>
+               <property name="wordWrap">
+                <bool>true</bool>
+               </property>
+              </widget>
+             </item>
+             <item>
+              <widget class="QLineEdit" name="user_spec_mask">
+               <property name="minimumSize">
+                <size>
+                 <width>300</width>
+                 <height>0</height>
+                </size>
+               </property>
+               <property name="text">
+                <string/>
+               </property>
+              </widget>
+             </item>
+             <item>
+              <widget class="QLabel" name="label_9">
+               <property name="sizePolicy">
+                <sizepolicy hsizetype="Preferred" vsizetype="Maximum">
+                 <horstretch>0</horstretch>
+                 <verstretch>0</verstretch>
+                </sizepolicy>
+               </property>
+               <property name="maximumSize">
+                <size>
+                 <width>16777215</width>
+                 <height>16777215</height>
+                </size>
+               </property>
+               <property name="text">
+                <string>Enter additional time range masks (separated by a comma e.g. 10000. 11000.,12000. 13000.)</string>
+               </property>
+               <property name="wordWrap">
+                <bool>true</bool>
+               </property>
+              </widget>
+             </item>
+             <item>
+              <widget class="QLineEdit" name="user_time_mask"/>
+             </item>
+            </layout>
            </widget>
           </item>
-          <item row="0" column="2">
-           <widget class="QLineEdit" name="hirange_edit1"/>
+          <item>
+           <spacer name="verticalSpacer_4">
+            <property name="orientation">
+             <enum>Qt::Vertical</enum>
+            </property>
+            <property name="sizeHint" stdset="0">
+             <size>
+              <width>20</width>
+              <height>40</height>
+             </size>
+            </property>
+           </spacer>
           </item>
-          <item row="0" column="3">
-           <widget class="QCheckBox" name="tcmask1">
-            <property name="text">
-             <string>Apply Time Channel Mask</string>
+         </layout>
+        </item>
+        <item>
+         <spacer name="horizontalSpacer_3">
+          <property name="orientation">
+           <enum>Qt::Horizontal</enum>
+          </property>
+          <property name="sizeType">
+           <enum>QSizePolicy::Preferred</enum>
+          </property>
+          <property name="sizeHint" stdset="0">
+           <size>
+            <width>20</width>
+            <height>20</height>
+           </size>
+          </property>
+         </spacer>
+        </item>
+       </layout>
+      </widget>
+      <widget class="QWidget" name="tab_5">
+       <attribute name="title">
+        <string>Logging</string>
+       </attribute>
+       <layout class="QGridLayout" name="gridLayout_15">
+        <item row="1" column="2">
+         <layout class="QVBoxLayout" name="verticalLayout_10">
+          <item>
+           <spacer name="verticalSpacer_3">
+            <property name="orientation">
+             <enum>Qt::Vertical</enum>
             </property>
-           </widget>
+            <property name="sizeHint" stdset="0">
+             <size>
+              <width>20</width>
+              <height>40</height>
+             </size>
+            </property>
+           </spacer>
           </item>
-          <item row="1" column="0">
-           <widget class="QPushButton" name="vi_Btn1">
-            <property name="text">
-             <string>Vertical Integral</string>
+         </layout>
+        </item>
+        <item row="2" column="1">
+         <layout class="QHBoxLayout" name="horizontalLayout_5">
+          <item>
+           <spacer name="horizontalSpacer_20">
+            <property name="orientation">
+             <enum>Qt::Horizontal</enum>
             </property>
-           </widget>
-          </item>
-          <item row="1" column="1">
-           <widget class="QLabel" name="vrange_det1">
-            <property name="text">
-             <string>Range:</string>
+            <property name="sizeHint" stdset="0">
+             <size>
+              <width>40</width>
+              <height>20</height>
+             </size>
             </property>
-           </widget>
-          </item>
-          <item row="1" column="2">
-           <widget class="QLineEdit" name="virange_edit1"/>
+           </spacer>
           </item>
-          <item row="1" column="3">
-           <widget class="QCheckBox" name="tcmask2">
+          <item>
+           <widget class="QPushButton" name="logger_clear">
             <property name="text">
-             <string>Apply Time Channel Mask</string>
+             <string>Clear</string>
             </property>
            </widget>
           </item>
-          <item row="2" column="0">
-           <widget class="QPushButton" name="ti_Btn1">
-            <property name="text">
-             <string>Time Integral</string>
+          <item>
+           <spacer name="horizontalSpacer_5">
+            <property name="orientation">
+             <enum>Qt::Horizontal</enum>
             </property>
-           </widget>
-          </item>
-          <item row="2" column="1">
-           <widget class="QLabel" name="region_det1">
-            <property name="text">
-             <string>Region:</string>
+            <property name="sizeHint" stdset="0">
+             <size>
+              <width>40</width>
+              <height>20</height>
+             </size>
             </property>
-           </widget>
-          </item>
-          <item row="2" column="2">
-           <widget class="QLineEdit" name="tirange_edit1"/>
+           </spacer>
           </item>
-          <item row="2" column="3">
-           <widget class="QCheckBox" name="pmask1">
-            <property name="text">
-             <string>Apply Pixel Mask</string>
+         </layout>
+        </item>
+        <item row="0" column="1">
+         <widget class="QLabel" name="label_29">
+          <property name="text">
+           <string>Log messages:</string>
+          </property>
+         </widget>
+        </item>
+        <item row="1" column="1">
+         <widget class="MantidQt::MantidWidgets::MessageDisplay" name="logging_field" native="true">
+          <property name="source" stdset="0">
+           <string>SANS</string>
+          </property>
+         </widget>
+        </item>
+        <item row="1" column="0">
+         <layout class="QVBoxLayout" name="verticalLayout_14">
+          <item>
+           <spacer name="verticalSpacer_5">
+            <property name="orientation">
+             <enum>Qt::Vertical</enum>
             </property>
-           </widget>
+            <property name="sizeHint" stdset="0">
+             <size>
+              <width>20</width>
+              <height>40</height>
+             </size>
+            </property>
+           </spacer>
           </item>
          </layout>
-        </widget>
-       </item>
-       <item row="3" column="0">
-        <widget class="QGroupBox" name="groupBox_Detector2">
-         <property name="title">
-          <string>Detector2</string>
-         </property>
-         <layout class="QGridLayout" name="gridLayout_24">
-          <item row="0" column="0">
-           <widget class="QPushButton" name="hi_Btn2">
-            <property name="text">
-             <string>Horizontal Integral</string>
-            </property>
-           </widget>
+        </item>
+       </layout>
+      </widget>
+      <widget class="QWidget" name="AddRuns">
+       <attribute name="title">
+        <string>Add Runs</string>
+       </attribute>
+       <layout class="QGridLayout" name="gridLayout_18">
+        <item row="0" column="2">
+         <spacer name="verticalSpacer_9">
+          <property name="orientation">
+           <enum>Qt::Vertical</enum>
+          </property>
+          <property name="sizeHint" stdset="0">
+           <size>
+            <width>20</width>
+            <height>40</height>
+           </size>
+          </property>
+         </spacer>
+        </item>
+        <item row="1" column="0">
+         <spacer name="horizontalSpacer_11">
+          <property name="orientation">
+           <enum>Qt::Horizontal</enum>
+          </property>
+          <property name="sizeType">
+           <enum>QSizePolicy::Maximum</enum>
+          </property>
+          <property name="sizeHint" stdset="0">
+           <size>
+            <width>40</width>
+            <height>20</height>
+           </size>
+          </property>
+         </spacer>
+        </item>
+        <item row="1" column="2">
+         <widget class="QLabel" name="summedPath_lb">
+          <property name="text">
+           <string/>
+          </property>
+         </widget>
+        </item>
+        <item row="3" column="2">
+         <spacer name="verticalSpacer_10">
+          <property name="orientation">
+           <enum>Qt::Vertical</enum>
+          </property>
+          <property name="sizeHint" stdset="0">
+           <size>
+            <width>20</width>
+            <height>40</height>
+           </size>
+          </property>
+         </spacer>
+        </item>
+        <item row="4" column="0" colspan="2">
+         <widget class="QLabel" name="label_42">
+          <property name="sizePolicy">
+           <sizepolicy hsizetype="Fixed" vsizetype="Preferred">
+            <horstretch>0</horstretch>
+            <verstretch>0</verstretch>
+           </sizepolicy>
+          </property>
+          <property name="maximumSize">
+           <size>
+            <width>100</width>
+            <height>16777215</height>
+           </size>
+          </property>
+          <property name="toolTip">
+           <string>Type , separated lists of run numbers or ranges of numbers with a : </string>
+          </property>
+          <property name="text">
+           <string/>
+          </property>
+         </widget>
+        </item>
+        <item row="4" column="2">
+         <widget class="QLineEdit" name="new2Add_edit">
+          <property name="toolTip">
+           <string>Type , separated lists of run numbers or ranges of numbers with a : </string>
+          </property>
+         </widget>
+        </item>
+        <item row="4" column="3">
+         <widget class="QPushButton" name="add_Btn">
+          <property name="toolTip">
+           <string>Adds entries to the big table, use before clicking &quot;Sum&quot;.</string>
+          </property>
+          <property name="text">
+           <string>Add</string>
+          </property>
+         </widget>
+        </item>
+        <item row="4" column="4">
+         <widget class="QPushButton" name="browse_to_add_Btn">
+          <property name="toolTip">
+           <string>Find a file on your system</string>
+          </property>
+          <property name="text">
+           <string>Browse</string>
+          </property>
+         </widget>
+        </item>
+        <item row="4" column="5">
+         <spacer name="horizontalSpacer_18">
+          <property name="orientation">
+           <enum>Qt::Horizontal</enum>
+          </property>
+          <property name="sizeType">
+           <enum>QSizePolicy::Maximum</enum>
+          </property>
+          <property name="sizeHint" stdset="0">
+           <size>
+            <width>40</width>
+            <height>20</height>
+           </size>
+          </property>
+         </spacer>
+        </item>
+        <item row="5" column="0">
+         <widget class="QLabel" name="label_46">
+          <property name="toolTip">
+           <string>Files to be summed, click at the top of this box or use the &quot;Add&quot; button</string>
+          </property>
+          <property name="text">
+           <string>Run files to sum</string>
+          </property>
+         </widget>
+        </item>
+        <item row="5" column="1" rowspan="3" colspan="2">
+         <widget class="QListWidget" name="toAdd_List">
+          <property name="toolTip">
+           <string>Files to be summed, click at the top of this box or use the &quot;Add&quot; button</string>
+          </property>
+          <property name="editTriggers">
+           <set>QAbstractItemView::AnyKeyPressed|QAbstractItemView::DoubleClicked|QAbstractItemView::EditKeyPressed|QAbstractItemView::SelectedClicked</set>
+          </property>
+          <property name="selectionMode">
+           <enum>QAbstractItemView::ExtendedSelection</enum>
+          </property>
+          <property name="selectionBehavior">
+           <enum>QAbstractItemView::SelectRows</enum>
+          </property>
+          <property name="resizeMode">
+           <enum>QListView::Fixed</enum>
+          </property>
+          <property name="currentRow">
+           <number>-1</number>
+          </property>
+         </widget>
+        </item>
+        <item row="5" column="3">
+         <widget class="QPushButton" name="clear_Btn">
+          <property name="toolTip">
+           <string>Clear the table</string>
+          </property>
+          <property name="text">
+           <string>Remove all</string>
+          </property>
+         </widget>
+        </item>
+        <item row="6" column="3">
+         <widget class="QPushButton" name="remove_Btn">
+          <property name="toolTip">
+           <string>Select rows by clicking on the table and remove then with this button</string>
+          </property>
+          <property name="text">
+           <string>Remove</string>
+          </property>
+         </widget>
+        </item>
+        <item row="7" column="3">
+         <spacer name="verticalSpacer_7">
+          <property name="orientation">
+           <enum>Qt::Vertical</enum>
+          </property>
+          <property name="sizeHint" stdset="0">
+           <size>
+            <width>20</width>
+            <height>40</height>
+           </size>
+          </property>
+         </spacer>
+        </item>
+        <item row="1" column="4">
+         <widget class="QPushButton" name="summedPath_Btn">
+          <property name="toolTip">
+           <string>The directory to created the summed run file in</string>
+          </property>
+          <property name="text">
+           <string>Manage Directories</string>
+          </property>
+         </widget>
+        </item>
+        <item row="2" column="2">
+         <widget class="QCheckBox" name="loadSeparateEntries">
+          <property name="text">
+           <string>Minimise memory usage</string>
+          </property>
+         </widget>
+        </item>
+        <item row="9" column="2">
+         <widget class="QLabel" name="label">
+          <property name="text">
+           <string>Histogram binning (when adding event data):</string>
+          </property>
+         </widget>
+        </item>
+        <item row="8" column="3">
+         <widget class="QPushButton" name="sum_Btn">
+          <property name="toolTip">
+           <string>Load the files in the table above and save them to one file</string>
+          </property>
+          <property name="text">
+           <string>Sum</string>
+          </property>
+         </widget>
+        </item>
+        <item row="12" column="2">
+         <widget class="QLineEdit" name="eventToHistBinning">
+          <property name="text">
+           <string>5.5,45.5,50.0, 50.0,1000.0, 500.0,1500.0, 750.0,99750.0, 255.0,100005.0</string>
+          </property>
+         </widget>
+        </item>
+        <item row="10" column="2">
+         <widget class="QComboBox" name="comboBox_histogram_choice">
+          <item>
+           <property name="text">
+            <string>Use custom binning</string>
+           </property>
           </item>
-          <item row="0" column="1">
-           <widget class="QLabel" name="hrange_det2">
-            <property name="text">
-             <string>Range:</string>
-            </property>
-           </widget>
+          <item>
+           <property name="text">
+            <string>Use binning from monitors</string>
+           </property>
           </item>
-          <item row="0" column="2">
-           <widget class="QLineEdit" name="hirange_edit2"/>
+          <item>
+           <property name="text">
+            <string>Save as event data</string>
+           </property>
           </item>
-          <item row="0" column="3">
-           <widget class="QCheckBox" name="tcmask3">
-            <property name="text">
-             <string>Apply Time Channel Mask</string>
+         </widget>
+        </item>
+       </layout>
+      </widget>
+      <widget class="QWidget" name="widget">
+       <attribute name="title">
+        <string>Diagnostics</string>
+       </attribute>
+       <layout class="QGridLayout" name="gridLayout_25">
+        <item row="0" column="0">
+         <layout class="QGridLayout" name="gridLayout_23">
+          <property name="sizeConstraint">
+           <enum>QLayout::SetDefaultConstraint</enum>
+          </property>
+          <property name="verticalSpacing">
+           <number>6</number>
+          </property>
+          <item row="0" column="0">
+           <widget class="MantidQt::MantidWidgets::MWRunFiles" name="file_run_edit" native="true">
+            <property name="sizePolicy">
+             <sizepolicy hsizetype="MinimumExpanding" vsizetype="Minimum">
+              <horstretch>0</horstretch>
+              <verstretch>0</verstretch>
+             </sizepolicy>
             </property>
-           </widget>
-          </item>
-          <item row="1" column="0">
-           <widget class="QPushButton" name="vi_Btn2">
-            <property name="text">
-             <string>Vertical Integral</string>
+            <property name="maximumSize">
+             <size>
+              <width>16777215</width>
+              <height>16777215</height>
+             </size>
             </property>
-           </widget>
-          </item>
-          <item row="1" column="1">
-           <widget class="QLabel" name="vrange_det2">
-            <property name="text">
-             <string>Range:</string>
+            <property name="label" stdset="0">
+             <string>File/Run:</string>
             </property>
-           </widget>
-          </item>
-          <item row="1" column="2">
-           <widget class="QLineEdit" name="virange_edit2"/>
-          </item>
-          <item row="1" column="3">
-           <widget class="QCheckBox" name="tcmask4">
-            <property name="text">
-             <string>Apply Time Channel Mask</string>
+            <property name="multipleFiles" stdset="0">
+             <bool>false</bool>
             </property>
            </widget>
           </item>
-          <item row="2" column="0">
-           <widget class="QPushButton" name="ti_Btn2">
+          <item row="0" column="1">
+           <widget class="QLabel" name="label_period">
             <property name="text">
-             <string>Time Integral</string>
+             <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
+&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
+p, li { white-space: pre-wrap; }
+&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;
+&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:8pt;&quot;&gt;Period :&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
             </property>
            </widget>
           </item>
-          <item row="2" column="1">
-           <widget class="QLabel" name="region_det2">
-            <property name="text">
-             <string>Region:</string>
+          <item row="0" column="2">
+           <widget class="QLineEdit" name="period_edit">
+            <property name="minimumSize">
+             <size>
+              <width>25</width>
+              <height>0</height>
+             </size>
+            </property>
+            <property name="maximumSize">
+             <size>
+              <width>25</width>
+              <height>20</height>
+             </size>
             </property>
            </widget>
           </item>
-          <item row="2" column="2">
-           <widget class="QLineEdit" name="tirange_edit2"/>
-          </item>
-          <item row="2" column="3">
-           <widget class="QCheckBox" name="pmask2">
+          <item row="0" column="3">
+           <widget class="QLabel" name="total_perioids">
             <property name="text">
-             <string>Apply Pixel Mask</string>
+             <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
+&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
+p, li { white-space: pre-wrap; }
+&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;
+&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:12pt;&quot;&gt;/n&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
             </property>
            </widget>
           </item>
          </layout>
-        </widget>
-       </item>
-       <item row="4" column="0">
-        <spacer name="verticalSpacer_11">
-         <property name="orientation">
-          <enum>Qt::Vertical</enum>
-         </property>
-         <property name="sizeHint" stdset="0">
-          <size>
-           <width>20</width>
-           <height>40</height>
-          </size>
-         </property>
-        </spacer>
-       </item>
-      </layout>
-     </widget>
-     <widget class="QWidget" name="tab1DAnalysis">
-      <attribute name="title">
-       <string>1D Analysis</string>
-      </attribute>
-      <layout class="QVBoxLayout" name="displayLayout"/>
+        </item>
+        <item row="1" column="0">
+         <widget class="QLabel" name="label_7">
+          <property name="text">
+           <string>The format of Range string for example is 60-65 or 60-66:2 or 60:66 or 60:66:2 or 60+61 or 60-65,66,67,68:72:2,73+74</string>
+          </property>
+         </widget>
+        </item>
+        <item row="2" column="0">
+         <widget class="QGroupBox" name="groupBox_Detector1">
+          <property name="title">
+           <string> Detector1</string>
+          </property>
+          <layout class="QGridLayout" name="gridLayout_22">
+           <item row="0" column="0">
+            <widget class="QPushButton" name="hi_Btn1">
+             <property name="text">
+              <string>Horizontal Integral</string>
+             </property>
+            </widget>
+           </item>
+           <item row="0" column="1">
+            <widget class="QLabel" name="hrange_det1">
+             <property name="text">
+              <string>Range:</string>
+             </property>
+            </widget>
+           </item>
+           <item row="0" column="2">
+            <widget class="QLineEdit" name="hirange_edit1"/>
+           </item>
+           <item row="0" column="3">
+            <widget class="QCheckBox" name="tcmask1">
+             <property name="text">
+              <string>Apply Time Channel Mask</string>
+             </property>
+            </widget>
+           </item>
+           <item row="1" column="0">
+            <widget class="QPushButton" name="vi_Btn1">
+             <property name="text">
+              <string>Vertical Integral</string>
+             </property>
+            </widget>
+           </item>
+           <item row="1" column="1">
+            <widget class="QLabel" name="vrange_det1">
+             <property name="text">
+              <string>Range:</string>
+             </property>
+            </widget>
+           </item>
+           <item row="1" column="2">
+            <widget class="QLineEdit" name="virange_edit1"/>
+           </item>
+           <item row="1" column="3">
+            <widget class="QCheckBox" name="tcmask2">
+             <property name="text">
+              <string>Apply Time Channel Mask</string>
+             </property>
+            </widget>
+           </item>
+           <item row="2" column="0">
+            <widget class="QPushButton" name="ti_Btn1">
+             <property name="text">
+              <string>Time Integral</string>
+             </property>
+            </widget>
+           </item>
+           <item row="2" column="1">
+            <widget class="QLabel" name="region_det1">
+             <property name="text">
+              <string>Region:</string>
+             </property>
+            </widget>
+           </item>
+           <item row="2" column="2">
+            <widget class="QLineEdit" name="tirange_edit1"/>
+           </item>
+           <item row="2" column="3">
+            <widget class="QCheckBox" name="pmask1">
+             <property name="text">
+              <string>Apply Pixel Mask</string>
+             </property>
+            </widget>
+           </item>
+          </layout>
+         </widget>
+        </item>
+        <item row="3" column="0">
+         <widget class="QGroupBox" name="groupBox_Detector2">
+          <property name="title">
+           <string>Detector2</string>
+          </property>
+          <layout class="QGridLayout" name="gridLayout_24">
+           <item row="0" column="0">
+            <widget class="QPushButton" name="hi_Btn2">
+             <property name="text">
+              <string>Horizontal Integral</string>
+             </property>
+            </widget>
+           </item>
+           <item row="0" column="1">
+            <widget class="QLabel" name="hrange_det2">
+             <property name="text">
+              <string>Range:</string>
+             </property>
+            </widget>
+           </item>
+           <item row="0" column="2">
+            <widget class="QLineEdit" name="hirange_edit2"/>
+           </item>
+           <item row="0" column="3">
+            <widget class="QCheckBox" name="tcmask3">
+             <property name="text">
+              <string>Apply Time Channel Mask</string>
+             </property>
+            </widget>
+           </item>
+           <item row="1" column="0">
+            <widget class="QPushButton" name="vi_Btn2">
+             <property name="text">
+              <string>Vertical Integral</string>
+             </property>
+            </widget>
+           </item>
+           <item row="1" column="1">
+            <widget class="QLabel" name="vrange_det2">
+             <property name="text">
+              <string>Range:</string>
+             </property>
+            </widget>
+           </item>
+           <item row="1" column="2">
+            <widget class="QLineEdit" name="virange_edit2"/>
+           </item>
+           <item row="1" column="3">
+            <widget class="QCheckBox" name="tcmask4">
+             <property name="text">
+              <string>Apply Time Channel Mask</string>
+             </property>
+            </widget>
+           </item>
+           <item row="2" column="0">
+            <widget class="QPushButton" name="ti_Btn2">
+             <property name="text">
+              <string>Time Integral</string>
+             </property>
+            </widget>
+           </item>
+           <item row="2" column="1">
+            <widget class="QLabel" name="region_det2">
+             <property name="text">
+              <string>Region:</string>
+             </property>
+            </widget>
+           </item>
+           <item row="2" column="2">
+            <widget class="QLineEdit" name="tirange_edit2"/>
+           </item>
+           <item row="2" column="3">
+            <widget class="QCheckBox" name="pmask2">
+             <property name="text">
+              <string>Apply Pixel Mask</string>
+             </property>
+            </widget>
+           </item>
+          </layout>
+         </widget>
+        </item>
+        <item row="4" column="0">
+         <spacer name="verticalSpacer_11">
+          <property name="orientation">
+           <enum>Qt::Vertical</enum>
+          </property>
+          <property name="sizeHint" stdset="0">
+           <size>
+            <width>20</width>
+            <height>40</height>
+           </size>
+          </property>
+         </spacer>
+        </item>
+       </layout>
+      </widget>
+      <widget class="QWidget" name="tab1DAnalysis">
+       <attribute name="title">
+        <string>1D Analysis</string>
+       </attribute>
+       <layout class="QVBoxLayout" name="displayLayout"/>
+      </widget>
      </widget>
-    </widget>
-   </item>
-  </layout>
+    </item>
+   </layout>
   </widget>
  </widget>
  <customwidgets>
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/TomoReconstruction/TomoReconstruction.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/TomoReconstruction/TomoReconstruction.h
new file mode 100644
index 0000000000000000000000000000000000000000..07870e7915f5adce0fbf17680be7910b4a73a618
--- /dev/null
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/TomoReconstruction/TomoReconstruction.h
@@ -0,0 +1,292 @@
+#ifndef MANTIDQTCUSTOMINTERFACES_TOMORECONSTRUCTION_H_
+#define MANTIDQTCUSTOMINTERFACES_TOMORECONSTRUCTION_H_
+
+#include "MantidAPI/IRemoteJobManager.h"
+#include "MantidAPI/MatrixWorkspace.h"
+#include "MantidAPI/TableRow.h"
+#include "MantidAPI/WorkspaceGroup.h"
+#include "MantidQtAPI/UserSubWindow.h"
+#include "MantidQtCustomInterfaces/TomoReconstruction/TomoToolConfigDialog.h"
+
+#include <json/json.h>
+#include <QMutex>
+
+// Qt classes forward declarations
+class QLineEdit;
+class QThread;
+class QTimer;
+class QTreeWidgetItem;
+
+namespace MantidQt {
+namespace CustomInterfaces {
+/**
+Tomographic reconstruction GUI. Interface for editing parameters,
+running and monitoring reconstruction jobs, quick image inspection,
+launching visualization windows, etc.
+
+Copyright &copy; 2014,205 ISIS Rutherford Appleton Laboratory, NScD
+Oak Ridge National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid 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 General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport TomoReconstruction : public MantidQt::API::UserSubWindow {
+  Q_OBJECT
+
+public: // public constructor, destructor and functions
+  /// Default Constructor
+  TomoReconstruction(QWidget *parent = 0);
+  /// Destructor
+  virtual ~TomoReconstruction();
+  /// Interface name
+  static std::string name() { return "Tomographic Reconstruction"; }
+  /// This interface's categories.
+  static QString categoryInfo() { return "Diffraction"; }
+  /// Setup tab UI
+  virtual void initLayout();
+
+public slots:
+  void periodicStatusUpdateRequested();
+
+  /// for buttons, run tab, and similar
+  void reconstructClicked();
+  void toolSetupClicked();
+  void runVisualizeClicked();
+  void jobCancelClicked();
+  void jobTableRefreshClicked();
+  void getJobStatusInfo();
+
+protected:
+  bool doPing();
+  void doLogin(const std::string &pw);
+  void doLogout();
+  void doQueryJobStatus(std::vector<std::string> &ids,
+                        std::vector<std::string> &names,
+                        std::vector<std::string> &status,
+                        std::vector<std::string> &cmds);
+  void doSubmitReconstructionJob();
+  void doCancelJob(const std::string &id);
+
+  void updateJobsTable();
+
+  void cleanup();
+
+  void makeRunnableWithOptions(std::string &run, std::string &opt);
+  std::string getComputeResource();
+  std::string getUsername();
+  std::string getPassword();
+
+  // current paths set by the user
+  std::string currentPathSCARF();
+  std::string currentPathFITS();
+  std::string currentPathFlat();
+  std::string currentPathDark();
+  std::string currentPathSavuConfig();
+
+private slots:
+  void compResourceIndexChanged(int);
+  void runToolIndexChanged(int);
+  void SCARFLoginClicked();
+  void SCARFLogoutClicked();
+
+  void browseImageClicked();
+
+  void fitsPathBrowseClicked();
+  void flatPathBrowseClicked();
+  void darkPathBrowseClicked();
+
+  /// open the MantidQT help window for this interface
+  void openHelpWin();
+
+  void menuSaveClicked();
+  void menuSaveAsClicked();
+  void availablePluginSelected();
+  void currentPluginSelected();
+  void transferClicked();
+  void moveUpClicked();
+  void moveDownClicked();
+  void removeClicked();
+  void menuOpenClicked();
+  void paramValModified(QTreeWidgetItem *, int);
+  void expandedItem(QTreeWidgetItem *);
+
+private:
+  void doSetupSectionSetup();
+  void doSetupSectionParameters();
+  void doSetupSectionRun();
+  void doSetupGeneralWidgets();
+
+  void setupComputeResource();
+  void setupRunTool();
+
+  void enableLoggedActions(bool enable);
+  void updateCompResourceStatus(bool online);
+
+  void processPathBrowseClick(QLineEdit *le, std::string &data);
+
+  /// Show a tool specific configuration dialog
+  void showToolConfig(const std::string &name);
+
+  std::string validateCompResource(const std::string &res);
+
+  Mantid::API::WorkspaceGroup_sptr loadFITSImage(const std::string &path);
+
+  void drawImage(const Mantid::API::MatrixWorkspace_sptr &ws);
+
+  void splitCmdLine(const std::string &cmd, std::string &run,
+                    std::string &opts);
+
+  void checkDataPathsSet();
+
+  void checkWarningToolNotSetup(const std::string &tool,
+                                const std::string &settings);
+
+  void userWarning(const std::string &err, const std::string &description);
+
+  void userError(const std::string &err, const std::string &description);
+
+  /// Load default interface settings for each tab, normally on startup
+  void readSettings();
+  /// save settings (before closing)
+  void saveSettings();
+
+  /// Starts a periodic query just to keep sessions alive when logged in
+  void startKeepAliveMechanism(int period);
+  /// Stops/kills the periodic query (for example if the user logs out)
+  void killKeepAliveMechanism();
+
+  virtual void closeEvent(QCloseEvent *ev);
+
+  std::string paramValStringFromArray(const Json::Value &jsonVal,
+                                      const std::string &name);
+  std::string pluginParamValString(const Json::Value &jsonVal,
+                                   const std::string &name);
+
+  /// to load plugins (savu classification / API)
+  void loadAvailablePlugins();
+
+  /// refresh the list/tree of savu plugins
+  void refreshAvailablePluginListUI();
+
+  void refreshCurrentPluginListUI();
+
+  /// make a tree entry from a row of a table of savu plugins
+  void createPluginTreeEntry(Mantid::API::TableRow &row);
+  void createPluginTreeEntries(Mantid::API::ITableWorkspace_sptr table);
+
+  std::string createUniqueNameHidden();
+
+  QString tableWSRowToString(Mantid::API::ITableWorkspace_sptr table, size_t i);
+
+  void loadSavuTomoConfig(std::string &filePath,
+                          Mantid::API::ITableWorkspace_sptr &currentPlugins);
+
+  /// Main interface window
+  Ui::TomoReconstruction m_ui;
+
+  /// Tool specific setup dialogs
+  Ui::TomoToolConfigAstra m_uiAstra;
+  Ui::TomoToolConfigCustom m_uiCustom;
+  Ui::TomoToolConfigSavu m_uiSavu;
+  Ui::TomoToolConfigTomoPy m_uiTomoPy;
+
+  /// login status (from local perspective)
+  bool m_loggedIn;
+
+  /// facility for the remote compute resource
+  const std::string m_facility;
+  /// compute resources suppoted by this GUI (remote ones, clusters, etc.)
+  std::vector<std::string> m_computeRes;
+  /// display name of the "local" compute resource
+  const std::string m_localCompName;
+
+  /// reduction tools
+  std::vector<std::string> m_SCARFtools;
+
+  /// file paths, base dir on scarf
+  std::string m_pathSCARFbase;
+  /// path to fits file (sample data)
+  std::string m_pathFITS;
+  /// path to flat/open beam/bright image
+  std::string m_pathFlat;
+  /// path to dark image
+  std::string m_pathDark;
+
+  static const std::string g_SCARFName;
+
+  // Names of image reconstruction tools
+  static const std::string g_TomoPyTool;
+  static const std::string g_AstraTool;
+  static const std::string g_CCPiTool;
+  static const std::string g_SavuTool;
+  static const std::string g_CustomCmdTool;
+
+  // plugins for savu config files
+  // std::vector<Mantid::API::ITableWorkspace_sptr> m_availPlugins;
+  Mantid::API::ITableWorkspace_sptr m_availPlugins;
+  // std::vector<Mantid::API::ITableWorkspace_sptr> m_currPlugins;
+  Mantid::API::ITableWorkspace_sptr m_currPlugins;
+  std::string m_currentParamPath;
+  static size_t g_nameSeqNo;
+
+  // status of remote jobs
+  std::vector<Mantid::API::IRemoteJobManager::RemoteJobInfo> m_jobsStatus;
+  std::vector<std::string> m_jobsStatusCmds;
+
+  static const std::string g_defOutPath;
+  // path name for persistent settings
+  std::string m_settingsGroup;
+
+  // for periodic update of the job status table/tree
+  QTimer *m_keepAliveTimer;
+  QThread *m_keepAliveThread;
+  // mutex for the "job status info -> job status table " operations
+  QMutex m_statusMutex;
+
+  // Basic representation of user settings, read/written on startup/close.
+  // TODO: this could be done more sophisticated, with a class using
+  // QDataStream and in/out stream operators for example. Keeping
+  // it simple for now
+  struct UserSettings {
+    std::string SCARFBasePath;
+    int useKeepAlive; // use if >0, number of seconds for a periodic query
+    bool onCloseAskForConfirmation;
+
+    UserSettings()
+        : SCARFBasePath("/work/imat/runs/test/"), useKeepAlive(60),
+          onCloseAskForConfirmation(false) {}
+  };
+  UserSettings m_settings;
+
+  /// Settings for the third party (tomographic reconstruction) tools
+  struct UserToolsSettings {
+    // This is just too basic at the moment. We probably want to store
+    // here the real settings objects, and rather than this horror have a
+    // dictionary of tools-settings
+    std::string tomoPy;
+    std::string astra;
+    std::string CCPi;
+    std::string savu;
+    std::string custom;
+  };
+  UserToolsSettings m_toolsSettings;
+};
+}
+}
+
+#endif // MANTIDQTCUSTOMINTERFACES_TOMORECONSTRUCTION_H_
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/TomoReconstruction/TomoReconstruction.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/TomoReconstruction/TomoReconstruction.ui
new file mode 100644
index 0000000000000000000000000000000000000000..36c09ab446ee5c1cd056829c04004045090db97e
--- /dev/null
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/TomoReconstruction/TomoReconstruction.ui
@@ -0,0 +1,1293 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>TomoReconstruction</class>
+ <widget class="QMainWindow" name="TomoReconstruction">
+  <property name="geometry">
+   <rect>
+    <x>0</x>
+    <y>0</y>
+    <width>1059</width>
+    <height>705</height>
+   </rect>
+  </property>
+  <property name="windowTitle">
+   <string>IMAT Tomographic Reconstruction</string>
+  </property>
+  <widget class="QWidget" name="mainWidget">
+   <layout class="QGridLayout" name="gridLayout_4">
+    <property name="margin">
+     <number>3</number>
+    </property>
+    <property name="spacing">
+     <number>1</number>
+    </property>
+    <item row="0" column="0">
+     <widget class="QTabWidget" name="tabMain">
+      <property name="toolTip">
+       <string/>
+      </property>
+      <property name="currentIndex">
+       <number>0</number>
+      </property>
+      <widget class="QWidget" name="runTab">
+       <property name="enabled">
+        <bool>true</bool>
+       </property>
+       <attribute name="title">
+        <string>Run</string>
+       </attribute>
+       <layout class="QGridLayout" name="gridLayout_17">
+        <item row="0" column="0">
+         <widget class="QSplitter" name="splitter_run_main_vertical">
+          <property name="orientation">
+           <enum>Qt::Vertical</enum>
+          </property>
+          <widget class="QSplitter" name="splitter_image_resource">
+           <property name="sizePolicy">
+            <sizepolicy hsizetype="Expanding" vsizetype="Expanding">
+             <horstretch>0</horstretch>
+             <verstretch>0</verstretch>
+            </sizepolicy>
+           </property>
+           <property name="orientation">
+            <enum>Qt::Horizontal</enum>
+           </property>
+           <property name="opaqueResize">
+            <bool>true</bool>
+           </property>
+           <widget class="QWidget" name="layoutWidget_5">
+            <layout class="QGridLayout" name="gridLayout_11">
+             <item row="0" column="0">
+              <layout class="QGridLayout" name="gridLayout_12">
+               <item row="0" column="0">
+                <widget class="QLabel" name="label_image_title">
+                 <property name="sizePolicy">
+                  <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+                   <horstretch>0</horstretch>
+                   <verstretch>0</verstretch>
+                  </sizepolicy>
+                 </property>
+                 <property name="text">
+                  <string>Image:</string>
+                 </property>
+                </widget>
+               </item>
+               <item row="0" column="2">
+                <widget class="QPushButton" name="pushButton_browse_image">
+                 <property name="text">
+                  <string>Browse</string>
+                 </property>
+                </widget>
+               </item>
+               <item row="0" column="1">
+                <widget class="QLabel" name="label_image_name">
+                 <property name="sizePolicy">
+                  <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+                   <horstretch>1</horstretch>
+                   <verstretch>0</verstretch>
+                  </sizepolicy>
+                 </property>
+                 <property name="text">
+                  <string>none</string>
+                 </property>
+                </widget>
+               </item>
+              </layout>
+             </item>
+             <item row="1" column="0">
+              <widget class="QFrame" name="frame_image">
+               <property name="sizePolicy">
+                <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+                 <horstretch>2</horstretch>
+                 <verstretch>2</verstretch>
+                </sizepolicy>
+               </property>
+               <property name="frameShape">
+                <enum>QFrame::StyledPanel</enum>
+               </property>
+               <property name="frameShadow">
+                <enum>QFrame::Raised</enum>
+               </property>
+               <layout class="QGridLayout" name="gridLayout_13">
+                <property name="margin">
+                 <number>3</number>
+                </property>
+                <property name="spacing">
+                 <number>2</number>
+                </property>
+                <item row="0" column="0">
+                 <widget class="QScrollArea" name="scrollArea_image">
+                  <property name="widgetResizable">
+                   <bool>true</bool>
+                  </property>
+                  <property name="alignment">
+                   <set>Qt::AlignCenter</set>
+                  </property>
+                  <widget class="QWidget" name="scrollAreaWidgetContents">
+                   <property name="geometry">
+                    <rect>
+                     <x>0</x>
+                     <y>0</y>
+                     <width>374</width>
+                     <height>278</height>
+                    </rect>
+                   </property>
+                   <layout class="QGridLayout" name="gridLayout_5">
+                    <property name="margin">
+                     <number>0</number>
+                    </property>
+                    <property name="spacing">
+                     <number>0</number>
+                    </property>
+                    <item row="0" column="0">
+                     <widget class="QLabel" name="label_image">
+                      <property name="text">
+                       <string/>
+                      </property>
+                     </widget>
+                    </item>
+                   </layout>
+                  </widget>
+                 </widget>
+                </item>
+               </layout>
+              </widget>
+             </item>
+            </layout>
+           </widget>
+           <widget class="QWidget" name="layoutWidget_6">
+            <layout class="QGridLayout" name="gridLayout_14">
+             <item row="1" column="1">
+              <widget class="QPushButton" name="pushButton_reconstruct">
+               <property name="minimumSize">
+                <size>
+                 <width>115</width>
+                 <height>0</height>
+                </size>
+               </property>
+               <property name="maximumSize">
+                <size>
+                 <width>115</width>
+                 <height>16777215</height>
+                </size>
+               </property>
+               <property name="toolTip">
+                <string/>
+               </property>
+               <property name="statusTip">
+                <string/>
+               </property>
+               <property name="text">
+                <string>Reconstruct</string>
+               </property>
+              </widget>
+             </item>
+             <item row="1" column="2">
+              <spacer name="horizontalSpacer_6">
+               <property name="orientation">
+                <enum>Qt::Horizontal</enum>
+               </property>
+               <property name="sizeHint" stdset="0">
+                <size>
+                 <width>13</width>
+                 <height>20</height>
+                </size>
+               </property>
+              </spacer>
+             </item>
+             <item row="2" column="1">
+              <spacer name="verticalSpacer_4">
+               <property name="orientation">
+                <enum>Qt::Vertical</enum>
+               </property>
+               <property name="sizeHint" stdset="0">
+                <size>
+                 <width>20</width>
+                 <height>40</height>
+                </size>
+               </property>
+              </spacer>
+             </item>
+             <item row="0" column="0" colspan="3">
+              <widget class="QGroupBox" name="groupBox_6">
+               <property name="sizePolicy">
+                <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+                 <horstretch>0</horstretch>
+                 <verstretch>0</verstretch>
+                </sizepolicy>
+               </property>
+               <property name="minimumSize">
+                <size>
+                 <width>0</width>
+                 <height>70</height>
+                </size>
+               </property>
+               <property name="title">
+                <string>Compute resource</string>
+               </property>
+               <layout class="QGridLayout" name="gridLayout_15">
+                <item row="1" column="0">
+                 <layout class="QHBoxLayout" name="horizontalLayout_4">
+                  <item>
+                   <spacer name="horizontalSpacer_8">
+                    <property name="orientation">
+                     <enum>Qt::Horizontal</enum>
+                    </property>
+                    <property name="sizeHint" stdset="0">
+                     <size>
+                      <width>40</width>
+                      <height>20</height>
+                     </size>
+                    </property>
+                   </spacer>
+                  </item>
+                  <item>
+                   <widget class="QLabel" name="label_12">
+                    <property name="text">
+                     <string>Status:</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <widget class="QPushButton" name="pushButton_remote_status">
+                    <property name="text">
+                     <string>Offline</string>
+                    </property>
+                    <property name="flat">
+                     <bool>true</bool>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <spacer name="horizontalSpacer_9">
+                    <property name="orientation">
+                     <enum>Qt::Horizontal</enum>
+                    </property>
+                    <property name="sizeHint" stdset="0">
+                     <size>
+                      <width>40</width>
+                      <height>20</height>
+                     </size>
+                    </property>
+                   </spacer>
+                  </item>
+                 </layout>
+                </item>
+                <item row="0" column="0">
+                 <widget class="QComboBox" name="comboBox_run_compute_resource">
+                  <item>
+                   <property name="text">
+                    <string>SCARF</string>
+                   </property>
+                  </item>
+                  <item>
+                   <property name="text">
+                    <string>Local</string>
+                   </property>
+                  </item>
+                 </widget>
+                </item>
+                <item row="2" column="0">
+                 <widget class="QGroupBox" name="groupBox_7">
+                  <property name="title">
+                   <string>Reconstruction tool</string>
+                  </property>
+                  <layout class="QGridLayout" name="gridLayout_18">
+                   <item row="0" column="0">
+                    <widget class="QComboBox" name="comboBox_run_tool">
+                     <item>
+                      <property name="text">
+                       <string>TomoPy</string>
+                      </property>
+                     </item>
+                     <item>
+                      <property name="text">
+                       <string>Astra</string>
+                      </property>
+                     </item>
+                     <item>
+                      <property name="text">
+                       <string>CCPi CGLS</string>
+                      </property>
+                     </item>
+                     <item>
+                      <property name="text">
+                       <string>Savu</string>
+                      </property>
+                     </item>
+                     <item>
+                      <property name="text">
+                       <string>Custom command</string>
+                      </property>
+                     </item>
+                    </widget>
+                   </item>
+                   <item row="0" column="1">
+                    <widget class="QPushButton" name="pushButton_run_tool_setup">
+                     <property name="toolTip">
+                      <string>Define specific settings for the tool selected</string>
+                     </property>
+                     <property name="statusTip">
+                      <string/>
+                     </property>
+                     <property name="text">
+                      <string>Setup</string>
+                     </property>
+                     <property name="autoRepeat">
+                      <bool>false</bool>
+                     </property>
+                     <property name="autoExclusive">
+                      <bool>false</bool>
+                     </property>
+                     <property name="flat">
+                      <bool>false</bool>
+                     </property>
+                    </widget>
+                   </item>
+                  </layout>
+                 </widget>
+                </item>
+               </layout>
+              </widget>
+             </item>
+             <item row="1" column="0">
+              <spacer name="horizontalSpacer_7">
+               <property name="orientation">
+                <enum>Qt::Horizontal</enum>
+               </property>
+               <property name="sizeHint" stdset="0">
+                <size>
+                 <width>17</width>
+                 <height>20</height>
+                </size>
+               </property>
+              </spacer>
+             </item>
+            </layout>
+           </widget>
+          </widget>
+          <widget class="QWidget" name="layoutWidget_7">
+           <layout class="QVBoxLayout" name="verticalLayout_7">
+            <item>
+             <widget class="QLabel" name="label_11">
+              <property name="sizePolicy">
+               <sizepolicy hsizetype="Preferred" vsizetype="Fixed">
+                <horstretch>0</horstretch>
+                <verstretch>0</verstretch>
+               </sizepolicy>
+              </property>
+              <property name="text">
+               <string>Reconstruction jobs:</string>
+              </property>
+             </widget>
+            </item>
+            <item>
+             <widget class="QSplitter" name="splitter_run_jobs">
+              <property name="orientation">
+               <enum>Qt::Horizontal</enum>
+              </property>
+              <widget class="QTableWidget" name="tableWidget_run_jobs">
+               <property name="sizePolicy">
+                <sizepolicy hsizetype="Expanding" vsizetype="Expanding">
+                 <horstretch>1</horstretch>
+                 <verstretch>1</verstretch>
+                </sizepolicy>
+               </property>
+               <property name="selectionBehavior">
+                <enum>QAbstractItemView::SelectRows</enum>
+               </property>
+               <attribute name="horizontalHeaderStretchLastSection">
+                <bool>true</bool>
+               </attribute>
+               <column>
+                <property name="text">
+                 <string>Running on</string>
+                </property>
+               </column>
+               <column>
+                <property name="text">
+                 <string>Name</string>
+                </property>
+               </column>
+               <column>
+                <property name="text">
+                 <string>ID</string>
+                </property>
+               </column>
+               <column>
+                <property name="text">
+                 <string>Status</string>
+                </property>
+               </column>
+               <column>
+                <property name="text">
+                 <string>Command line</string>
+                </property>
+               </column>
+              </widget>
+              <widget class="QWidget" name="layoutWidget_8">
+               <layout class="QGridLayout" name="gridLayout_16">
+                <item row="2" column="0">
+                 <widget class="QPushButton" name="pushButton_run_job_visualize">
+                  <property name="text">
+                   <string>Visualize</string>
+                  </property>
+                 </widget>
+                </item>
+                <item row="4" column="0">
+                 <widget class="QPushButton" name="pushButton_run_job_cancel">
+                  <property name="text">
+                   <string>Cancel</string>
+                  </property>
+                 </widget>
+                </item>
+                <item row="3" column="0">
+                 <spacer name="verticalSpacer_5">
+                  <property name="orientation">
+                   <enum>Qt::Vertical</enum>
+                  </property>
+                  <property name="sizeHint" stdset="0">
+                   <size>
+                    <width>20</width>
+                    <height>40</height>
+                   </size>
+                  </property>
+                 </spacer>
+                </item>
+                <item row="1" column="0">
+                 <widget class="QPushButton" name="pushButton_run_refresh">
+                  <property name="text">
+                   <string>Refresh</string>
+                  </property>
+                 </widget>
+                </item>
+               </layout>
+              </widget>
+             </widget>
+            </item>
+           </layout>
+          </widget>
+         </widget>
+        </item>
+       </layout>
+      </widget>
+      <widget class="QWidget" name="setupTab">
+       <property name="enabled">
+        <bool>true</bool>
+       </property>
+       <attribute name="title">
+        <string>Setup</string>
+       </attribute>
+       <layout class="QGridLayout" name="gridLayout_7">
+        <item row="0" column="0">
+         <widget class="QGroupBox" name="groupBox">
+          <property name="sizePolicy">
+           <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+            <horstretch>0</horstretch>
+            <verstretch>1</verstretch>
+           </sizepolicy>
+          </property>
+          <property name="minimumSize">
+           <size>
+            <width>0</width>
+            <height>0</height>
+           </size>
+          </property>
+          <property name="title">
+           <string>Compute resource</string>
+          </property>
+          <layout class="QGridLayout" name="gridLayout_25">
+           <property name="margin">
+            <number>3</number>
+           </property>
+           <property name="spacing">
+            <number>2</number>
+           </property>
+           <item row="0" column="0">
+            <widget class="QTabWidget" name="tabWidget_comp_resource">
+             <property name="sizePolicy">
+              <sizepolicy hsizetype="Expanding" vsizetype="Expanding">
+               <horstretch>0</horstretch>
+               <verstretch>1</verstretch>
+              </sizepolicy>
+             </property>
+             <property name="minimumSize">
+              <size>
+               <width>0</width>
+               <height>0</height>
+              </size>
+             </property>
+             <property name="currentIndex">
+              <number>0</number>
+             </property>
+             <widget class="QWidget" name="tab_SCARF">
+              <attribute name="title">
+               <string>SCARF</string>
+              </attribute>
+              <layout class="QGridLayout" name="gridLayout_6">
+               <item row="0" column="0">
+                <layout class="QHBoxLayout" name="horizontalLayout_7">
+                 <item>
+                  <widget class="QLabel" name="label_SCARF_username">
+                   <property name="text">
+                    <string>Username:</string>
+                   </property>
+                   <property name="minimumSize">
+                    <size>
+                     <width>90</width>
+                     <height>20</height>
+                    </size>
+                   </property>
+                  </widget>
+                 </item>
+                 <item>
+                  <widget class="QLineEdit" name="lineEdit_SCARF_username">
+                   <property name="sizePolicy">
+                    <sizepolicy hsizetype="Preferred" vsizetype="Fixed">
+                     <horstretch>0</horstretch>
+                     <verstretch>0</verstretch>
+                    </sizepolicy>
+                   </property>
+                   <property name="minimumSize">
+                    <size>
+                     <width>140</width>
+                     <height>20</height>
+                    </size>
+                   </property>
+                   <property name="toolTip">
+                    <string>Type your username on the remote compute resource</string>
+                   </property>
+                   <property name="text">
+                    <string/>
+                   </property>
+                  </widget>
+                 </item>
+                 <item>
+                  <spacer name="horizontalSpacer_15">
+                   <property name="orientation">
+                    <enum>Qt::Horizontal</enum>
+                   </property>
+                   <property name="sizeHint" stdset="0">
+                    <size>
+                     <width>738</width>
+                     <height>20</height>
+                    </size>
+                   </property>
+                  </spacer>
+                 </item>
+                </layout>
+               </item>
+               <item row="1" column="0">
+                <layout class="QHBoxLayout" name="horizontalLayout_5">
+                 <item>
+                  <widget class="QLabel" name="label_SCARF_password">
+                   <property name="text">
+                    <string>Password:</string>
+                   </property>
+                   <property name="minimumSize">
+                    <size>
+                     <width>90</width>
+                     <height>20</height>
+                    </size>
+                   </property>
+                  </widget>
+                 </item>
+                 <item>
+                  <widget class="QLineEdit" name="lineEdit_SCARF_password">
+                   <property name="sizePolicy">
+                    <sizepolicy hsizetype="Preferred" vsizetype="Fixed">
+                     <horstretch>0</horstretch>
+                     <verstretch>0</verstretch>
+                    </sizepolicy>
+                   </property>
+                   <property name="minimumSize">
+                    <size>
+                     <width>140</width>
+                     <height>20</height>
+                    </size>
+                   </property>
+                   <property name="toolTip">
+                    <string>Type your password. It will be used just for authentication. It won't be displayed or saved anywhere</string>
+                   </property>
+                   <property name="text">
+                    <string/>
+                   </property>
+                   <property name="echoMode">
+                    <enum>QLineEdit::Password</enum>
+                   </property>
+                   <property name="cursorPosition">
+                    <number>0</number>
+                   </property>
+                  </widget>
+                 </item>
+                 <item>
+                  <spacer name="horizontalSpacer_20">
+                   <property name="orientation">
+                    <enum>Qt::Horizontal</enum>
+                   </property>
+                   <property name="sizeHint" stdset="0">
+                    <size>
+                     <width>748</width>
+                     <height>20</height>
+                    </size>
+                   </property>
+                  </spacer>
+                 </item>
+                </layout>
+               </item>
+               <item row="2" column="0">
+                <layout class="QHBoxLayout" name="horizontalLayout_8">
+                 <item>
+                  <widget class="QPushButton" name="pushButton_SCARF_login">
+                   <property name="sizePolicy">
+                    <sizepolicy hsizetype="Minimum" vsizetype="Preferred">
+                     <horstretch>0</horstretch>
+                     <verstretch>0</verstretch>
+                    </sizepolicy>
+                   </property>
+                   <property name="minimumSize">
+                    <size>
+                     <width>0</width>
+                     <height>22</height>
+                    </size>
+                   </property>
+                   <property name="text">
+                    <string>Log in</string>
+                   </property>
+                  </widget>
+                 </item>
+                 <item>
+                  <widget class="QPushButton" name="pushButton_SCARF_logout">
+                   <property name="sizePolicy">
+                    <sizepolicy hsizetype="Minimum" vsizetype="Preferred">
+                     <horstretch>0</horstretch>
+                     <verstretch>0</verstretch>
+                    </sizepolicy>
+                   </property>
+                   <property name="minimumSize">
+                    <size>
+                     <width>0</width>
+                     <height>22</height>
+                    </size>
+                   </property>
+                   <property name="text">
+                    <string>Log out</string>
+                   </property>
+                  </widget>
+                 </item>
+                 <item>
+                  <spacer name="horizontalSpacer_12">
+                   <property name="orientation">
+                    <enum>Qt::Horizontal</enum>
+                   </property>
+                   <property name="sizeHint" stdset="0">
+                    <size>
+                     <width>198</width>
+                     <height>20</height>
+                    </size>
+                   </property>
+                  </spacer>
+                 </item>
+                </layout>
+               </item>
+               <item row="3" column="0">
+                <widget class="QGroupBox" name="groupBox_3">
+                 <property name="title">
+                  <string>Options:</string>
+                 </property>
+                 <layout class="QGridLayout" name="gridLayout_3">
+                  <item row="2" column="0">
+                   <layout class="QHBoxLayout" name="horizontalLayout_11">
+                    <item>
+                     <widget class="QLabel" name="label_23">
+                      <property name="text">
+                       <string>Number of nodes:</string>
+                      </property>
+                     </widget>
+                    </item>
+                    <item>
+                     <widget class="QSpinBox" name="spinBox_SCARFnumNodes">
+                      <property name="minimumSize">
+                       <size>
+                        <width>0</width>
+                        <height>20</height>
+                       </size>
+                      </property>
+                      <property name="minimum">
+                       <number>1</number>
+                      </property>
+                      <property name="maximum">
+                       <number>99</number>
+                      </property>
+                      <property name="value">
+                       <number>1</number>
+                      </property>
+                     </widget>
+                    </item>
+                    <item>
+                     <spacer name="horizontalSpacer_16">
+                      <property name="orientation">
+                       <enum>Qt::Horizontal</enum>
+                      </property>
+                      <property name="sizeHint" stdset="0">
+                       <size>
+                        <width>678</width>
+                        <height>20</height>
+                       </size>
+                      </property>
+                     </spacer>
+                    </item>
+                   </layout>
+                  </item>
+                  <item row="0" column="0">
+                   <layout class="QHBoxLayout" name="horizontalLayout_10">
+                    <item>
+                     <widget class="QLabel" name="label_22">
+                      <property name="text">
+                       <string>Main path on the SCARF file system:</string>
+                      </property>
+                     </widget>
+                    </item>
+                    <item>
+                     <widget class="QLineEdit" name="lineEdit_SCARF_path">
+                      <property name="minimumSize">
+                       <size>
+                        <width>0</width>
+                        <height>20</height>
+                       </size>
+                      </property>
+                      <property name="text">
+                       <string>/work/imat/runs/test</string>
+                      </property>
+                     </widget>
+                    </item>
+                    <item>
+                     <spacer name="horizontalSpacer_2">
+                      <property name="orientation">
+                       <enum>Qt::Horizontal</enum>
+                      </property>
+                      <property name="sizeHint" stdset="0">
+                       <size>
+                        <width>40</width>
+                        <height>20</height>
+                       </size>
+                      </property>
+                     </spacer>
+                    </item>
+                   </layout>
+                  </item>
+                  <item row="3" column="0">
+                   <layout class="QHBoxLayout" name="horizontalLayout_12">
+                    <item>
+                     <widget class="QLabel" name="label_24">
+                      <property name="text">
+                       <string>Number of cores:</string>
+                      </property>
+                     </widget>
+                    </item>
+                    <item>
+                     <widget class="QSpinBox" name="spinBox_SCARFnumCores">
+                      <property name="minimumSize">
+                       <size>
+                        <width>0</width>
+                        <height>20</height>
+                       </size>
+                      </property>
+                      <property name="minimum">
+                       <number>1</number>
+                      </property>
+                      <property name="maximum">
+                       <number>99</number>
+                      </property>
+                      <property name="value">
+                       <number>8</number>
+                      </property>
+                     </widget>
+                    </item>
+                    <item>
+                     <spacer name="horizontalSpacer_17">
+                      <property name="orientation">
+                       <enum>Qt::Horizontal</enum>
+                      </property>
+                      <property name="sizeHint" stdset="0">
+                       <size>
+                        <width>434</width>
+                        <height>20</height>
+                       </size>
+                      </property>
+                     </spacer>
+                    </item>
+                   </layout>
+                  </item>
+                  <item row="1" column="0">
+                   <layout class="QHBoxLayout" name="horizontalLayout_2">
+                    <item>
+                     <widget class="QLabel" name="label">
+                      <property name="text">
+                       <string>Base path for tools/scripts:</string>
+                      </property>
+                     </widget>
+                    </item>
+                    <item>
+                     <widget class="QLineEdit" name="lineEdit_scripts_base_dir">
+                      <property name="text">
+                       <string>/work/imat/runs-scripts</string>
+                      </property>
+                     </widget>
+                    </item>
+                    <item>
+                     <widget class="QPushButton" name="pushButton_reset_scripts_base_dir">
+                      <property name="text">
+                       <string>Reset</string>
+                      </property>
+                     </widget>
+                    </item>
+                   </layout>
+                  </item>
+                 </layout>
+                </widget>
+               </item>
+              </layout>
+             </widget>
+             <widget class="QWidget" name="tab_local">
+              <attribute name="title">
+               <string>Local</string>
+              </attribute>
+              <layout class="QGridLayout" name="gridLayout_28">
+               <item row="1" column="0">
+                <spacer name="verticalSpacer_9">
+                 <property name="orientation">
+                  <enum>Qt::Vertical</enum>
+                 </property>
+                 <property name="sizeHint" stdset="0">
+                  <size>
+                   <width>20</width>
+                   <height>82</height>
+                  </size>
+                 </property>
+                </spacer>
+               </item>
+               <item row="0" column="0">
+                <widget class="QGroupBox" name="groupBox_4">
+                 <property name="title">
+                  <string>Options:</string>
+                 </property>
+                 <layout class="QGridLayout" name="gridLayout_8">
+                  <item row="0" column="0">
+                   <layout class="QHBoxLayout" name="horizontalLayout_6">
+                    <item>
+                     <widget class="QLabel" name="label_25">
+                      <property name="text">
+                       <string>Number of cores:</string>
+                      </property>
+                     </widget>
+                    </item>
+                    <item>
+                     <widget class="QSpinBox" name="spinBox_localNumCores">
+                      <property name="minimumSize">
+                       <size>
+                        <width>0</width>
+                        <height>10</height>
+                       </size>
+                      </property>
+                      <property name="maximum">
+                       <number>99</number>
+                      </property>
+                      <property name="value">
+                       <number>8</number>
+                      </property>
+                     </widget>
+                    </item>
+                    <item>
+                     <spacer name="horizontalSpacer_18">
+                      <property name="orientation">
+                       <enum>Qt::Horizontal</enum>
+                      </property>
+                      <property name="sizeHint" stdset="0">
+                       <size>
+                        <width>40</width>
+                        <height>20</height>
+                       </size>
+                      </property>
+                     </spacer>
+                    </item>
+                   </layout>
+                  </item>
+                 </layout>
+                </widget>
+               </item>
+              </layout>
+             </widget>
+            </widget>
+           </item>
+          </layout>
+         </widget>
+        </item>
+        <item row="1" column="0">
+         <widget class="QGroupBox" name="groupBox_2">
+          <property name="sizePolicy">
+           <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+            <horstretch>0</horstretch>
+            <verstretch>1</verstretch>
+           </sizepolicy>
+          </property>
+          <property name="minimumSize">
+           <size>
+            <width>0</width>
+            <height>100</height>
+           </size>
+          </property>
+          <property name="title">
+           <string>Select base directories/folders for images:</string>
+          </property>
+          <layout class="QGridLayout" name="gridLayout">
+           <property name="margin">
+            <number>3</number>
+           </property>
+           <property name="spacing">
+            <number>2</number>
+           </property>
+           <item row="0" column="0">
+            <widget class="QLabel" name="label_5">
+             <property name="minimumSize">
+              <size>
+               <width>120</width>
+               <height>0</height>
+              </size>
+             </property>
+             <property name="maximumSize">
+              <size>
+               <width>101</width>
+               <height>16777215</height>
+              </size>
+             </property>
+             <property name="text">
+              <string>Samples directory:</string>
+             </property>
+            </widget>
+           </item>
+           <item row="0" column="1">
+            <widget class="QLineEdit" name="lineEdit_path_FITS">
+             <property name="text">
+              <string/>
+             </property>
+            </widget>
+           </item>
+           <item row="0" column="2">
+            <widget class="QPushButton" name="pushButton_fits_dir">
+             <property name="maximumSize">
+              <size>
+               <width>75</width>
+               <height>16777215</height>
+              </size>
+             </property>
+             <property name="text">
+              <string>Browse...</string>
+             </property>
+            </widget>
+           </item>
+           <item row="1" column="0">
+            <widget class="QLabel" name="label_6">
+             <property name="minimumSize">
+              <size>
+               <width>120</width>
+               <height>0</height>
+              </size>
+             </property>
+             <property name="maximumSize">
+              <size>
+               <width>101</width>
+               <height>16777215</height>
+              </size>
+             </property>
+             <property name="text">
+              <string>Open beam dir.:</string>
+             </property>
+            </widget>
+           </item>
+           <item row="1" column="1">
+            <widget class="QLineEdit" name="lineEdit_path_flat"/>
+           </item>
+           <item row="1" column="2">
+            <widget class="QPushButton" name="pushButton_flat_dir">
+             <property name="maximumSize">
+              <size>
+               <width>75</width>
+               <height>16777215</height>
+              </size>
+             </property>
+             <property name="text">
+              <string>Browse...</string>
+             </property>
+            </widget>
+           </item>
+           <item row="2" column="0">
+            <widget class="QLabel" name="label_7">
+             <property name="minimumSize">
+              <size>
+               <width>120</width>
+               <height>0</height>
+              </size>
+             </property>
+             <property name="maximumSize">
+              <size>
+               <width>101</width>
+               <height>16777215</height>
+              </size>
+             </property>
+             <property name="text">
+              <string>Dark field dir.:</string>
+             </property>
+            </widget>
+           </item>
+           <item row="2" column="1">
+            <widget class="QLineEdit" name="lineEdit_path_dark"/>
+           </item>
+           <item row="2" column="2">
+            <widget class="QPushButton" name="pushButton_dark_dir">
+             <property name="maximumSize">
+              <size>
+               <width>75</width>
+               <height>16777215</height>
+              </size>
+             </property>
+             <property name="text">
+              <string>Browse...</string>
+             </property>
+            </widget>
+           </item>
+          </layout>
+          <zorder>lineEdit_path_FITS</zorder>
+          <zorder>lineEdit_path_flat</zorder>
+          <zorder>lineEdit_path_dark</zorder>
+          <zorder>label_5</zorder>
+          <zorder>label_6</zorder>
+          <zorder>label_7</zorder>
+          <zorder>pushButton_fits_dir</zorder>
+          <zorder>pushButton_flat_dir</zorder>
+          <zorder>pushButton_dark_dir</zorder>
+         </widget>
+        </item>
+        <item row="2" column="0">
+         <widget class="QGroupBox" name="groupBox_run_config">
+          <property name="sizePolicy">
+           <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+            <horstretch>0</horstretch>
+            <verstretch>1</verstretch>
+           </sizepolicy>
+          </property>
+          <property name="minimumSize">
+           <size>
+            <width>0</width>
+            <height>100</height>
+           </size>
+          </property>
+          <property name="title">
+           <string>Run Configuration</string>
+          </property>
+          <layout class="QGridLayout" name="gridLayout_2">
+           <property name="margin">
+            <number>3</number>
+           </property>
+           <property name="spacing">
+            <number>2</number>
+           </property>
+           <item row="1" column="0">
+            <widget class="QFrame" name="frame">
+             <property name="enabled">
+              <bool>false</bool>
+             </property>
+             <property name="sizePolicy">
+              <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+               <horstretch>0</horstretch>
+               <verstretch>0</verstretch>
+              </sizepolicy>
+             </property>
+             <property name="maximumSize">
+              <size>
+               <width>16777215</width>
+               <height>60</height>
+              </size>
+             </property>
+             <property name="frameShape">
+              <enum>QFrame::StyledPanel</enum>
+             </property>
+             <property name="frameShadow">
+              <enum>QFrame::Raised</enum>
+             </property>
+             <layout class="QHBoxLayout" name="horizontalLayout">
+              <property name="leftMargin">
+               <number>8</number>
+              </property>
+              <property name="topMargin">
+               <number>0</number>
+              </property>
+              <property name="rightMargin">
+               <number>0</number>
+              </property>
+              <property name="bottomMargin">
+               <number>0</number>
+              </property>
+              <item>
+               <widget class="QCheckBox" name="checkBox">
+                <property name="text">
+                 <string>Automatically Reconstruct every </string>
+                </property>
+               </widget>
+              </item>
+              <item>
+               <widget class="QSpinBox" name="spinBox">
+                <property name="minimum">
+                 <number>1</number>
+                </property>
+                <property name="maximum">
+                 <number>5000</number>
+                </property>
+                <property name="value">
+                 <number>1</number>
+                </property>
+               </widget>
+              </item>
+              <item>
+               <widget class="QLabel" name="label_3">
+                <property name="text">
+                 <string>files.</string>
+                </property>
+               </widget>
+              </item>
+              <item>
+               <spacer name="horizontalSpacer_4">
+                <property name="orientation">
+                 <enum>Qt::Horizontal</enum>
+                </property>
+                <property name="sizeHint" stdset="0">
+                 <size>
+                  <width>683</width>
+                  <height>20</height>
+                 </size>
+                </property>
+               </spacer>
+              </item>
+             </layout>
+            </widget>
+           </item>
+          </layout>
+         </widget>
+        </item>
+        <item row="3" column="0">
+         <spacer name="verticalSpacer_2">
+          <property name="orientation">
+           <enum>Qt::Vertical</enum>
+          </property>
+          <property name="sizeHint" stdset="0">
+           <size>
+            <width>20</width>
+            <height>120</height>
+           </size>
+          </property>
+         </spacer>
+        </item>
+       </layout>
+      </widget>
+     </widget>
+    </item>
+    <item row="1" column="0">
+     <layout class="QHBoxLayout" name="horizontalLayout_3">
+      <item>
+       <widget class="QPushButton" name="pushButton_help">
+        <property name="sizePolicy">
+         <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
+          <horstretch>0</horstretch>
+          <verstretch>0</verstretch>
+         </sizepolicy>
+        </property>
+        <property name="maximumSize">
+         <size>
+          <width>25</width>
+          <height>25</height>
+         </size>
+        </property>
+        <property name="text">
+         <string>?</string>
+        </property>
+       </widget>
+      </item>
+      <item>
+       <spacer name="horizontalSpacer">
+        <property name="orientation">
+         <enum>Qt::Horizontal</enum>
+        </property>
+        <property name="sizeHint" stdset="0">
+         <size>
+          <width>158</width>
+          <height>20</height>
+         </size>
+        </property>
+       </spacer>
+      </item>
+      <item>
+       <widget class="QPushButton" name="pushButton_close">
+        <property name="sizePolicy">
+         <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
+          <horstretch>0</horstretch>
+          <verstretch>0</verstretch>
+         </sizepolicy>
+        </property>
+        <property name="text">
+         <string>Close</string>
+        </property>
+       </widget>
+      </item>
+     </layout>
+    </item>
+   </layout>
+  </widget>
+  <action name="actionOpen">
+   <property name="text">
+    <string>&amp;Open...</string>
+   </property>
+  </action>
+  <action name="actionSave">
+   <property name="text">
+    <string>&amp;Save</string>
+   </property>
+  </action>
+  <action name="actionSaveAs">
+   <property name="text">
+    <string>Save As</string>
+   </property>
+  </action>
+ </widget>
+ <tabstops>
+  <tabstop>lineEdit_SCARF_username</tabstop>
+  <tabstop>lineEdit_SCARF_password</tabstop>
+  <tabstop>lineEdit_SCARF_path</tabstop>
+  <tabstop>spinBox_SCARFnumNodes</tabstop>
+  <tabstop>spinBox_SCARFnumCores</tabstop>
+  <tabstop>pushButton_SCARF_login</tabstop>
+  <tabstop>lineEdit_path_FITS</tabstop>
+  <tabstop>lineEdit_path_flat</tabstop>
+  <tabstop>lineEdit_path_dark</tabstop>
+  <tabstop>tabWidget_comp_resource</tabstop>
+  <tabstop>pushButton_SCARF_logout</tabstop>
+  <tabstop>tabMain</tabstop>
+  <tabstop>spinBox_localNumCores</tabstop>
+  <tabstop>pushButton_fits_dir</tabstop>
+  <tabstop>pushButton_flat_dir</tabstop>
+  <tabstop>pushButton_dark_dir</tabstop>
+  <tabstop>checkBox</tabstop>
+  <tabstop>spinBox</tabstop>
+  <tabstop>pushButton_browse_image</tabstop>
+  <tabstop>pushButton_reconstruct</tabstop>
+  <tabstop>pushButton_remote_status</tabstop>
+  <tabstop>comboBox_run_compute_resource</tabstop>
+  <tabstop>comboBox_run_tool</tabstop>
+  <tabstop>pushButton_run_tool_setup</tabstop>
+  <tabstop>tableWidget_run_jobs</tabstop>
+  <tabstop>pushButton_run_job_visualize</tabstop>
+  <tabstop>pushButton_run_job_cancel</tabstop>
+  <tabstop>pushButton_run_refresh</tabstop>
+ </tabstops>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/TomoReconstruction/TomoToolConfigAstra.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/TomoReconstruction/TomoToolConfigAstra.ui
new file mode 100644
index 0000000000000000000000000000000000000000..48ff4e69af6e6ab7f391797b964fb9b3d21602df
--- /dev/null
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/TomoReconstruction/TomoToolConfigAstra.ui
@@ -0,0 +1,233 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>TomoToolConfigAstra</class>
+ <widget class="QDialog" name="TomoToolConfigAstra">
+  <property name="windowModality">
+   <enum>Qt::WindowModal</enum>
+  </property>
+  <property name="geometry">
+   <rect>
+    <x>0</x>
+    <y>0</y>
+    <width>563</width>
+    <height>233</height>
+   </rect>
+  </property>
+  <property name="windowTitle">
+   <string>Astra Toolbox Configuration</string>
+  </property>
+  <layout class="QGridLayout" name="gridLayout_3">
+   <item row="0" column="0">
+    <layout class="QGridLayout" name="gridLayout_2">
+     <item row="4" column="0" colspan="3">
+      <widget class="QGroupBox" name="groupBox">
+       <property name="title">
+        <string>Angles</string>
+       </property>
+       <layout class="QGridLayout" name="gridLayout">
+        <item row="0" column="0">
+         <widget class="QLabel" name="label_runnable_2">
+          <property name="text">
+           <string>Min:</string>
+          </property>
+         </widget>
+        </item>
+        <item row="0" column="4">
+         <spacer name="horizontalSpacer_2">
+          <property name="orientation">
+           <enum>Qt::Horizontal</enum>
+          </property>
+          <property name="sizeHint" stdset="0">
+           <size>
+            <width>174</width>
+            <height>20</height>
+           </size>
+          </property>
+         </spacer>
+        </item>
+        <item row="1" column="0">
+         <widget class="QLabel" name="label_runnable_4">
+          <property name="enabled">
+           <bool>false</bool>
+          </property>
+          <property name="text">
+           <string>List:</string>
+          </property>
+         </widget>
+        </item>
+        <item row="0" column="2">
+         <widget class="QLabel" name="label_runnable_3">
+          <property name="text">
+           <string>Max:</string>
+          </property>
+         </widget>
+        </item>
+        <item row="1" column="1" colspan="4">
+         <widget class="QLineEdit" name="lineEdit">
+          <property name="enabled">
+           <bool>false</bool>
+          </property>
+         </widget>
+        </item>
+        <item row="0" column="3">
+         <widget class="QDoubleSpinBox" name="doubleSpinBox_angle_max">
+          <property name="maximum">
+           <double>360.000000000000000</double>
+          </property>
+          <property name="value">
+           <double>360.000000000000000</double>
+          </property>
+         </widget>
+        </item>
+        <item row="0" column="1">
+         <widget class="QDoubleSpinBox" name="doubleSpinBox_angle_min">
+          <property name="maximum">
+           <double>180.000000000000000</double>
+          </property>
+         </widget>
+        </item>
+       </layout>
+      </widget>
+     </item>
+     <item row="3" column="1">
+      <widget class="QDoubleSpinBox" name="doubleSpinBox_center_rot">
+       <property name="maximum">
+        <double>180.000000000000000</double>
+       </property>
+      </widget>
+     </item>
+     <item row="1" column="0">
+      <widget class="QLabel" name="label">
+       <property name="text">
+        <string>Method:</string>
+       </property>
+      </widget>
+     </item>
+     <item row="2" column="1" colspan="2">
+      <widget class="QLineEdit" name="lineEdit_runnable">
+       <property name="text">
+        <string>/work/imat/runs-scripts/scripts/astra/astra-2d-FBP.py</string>
+       </property>
+      </widget>
+     </item>
+     <item row="2" column="0">
+      <widget class="QLabel" name="label_runnable">
+       <property name="text">
+        <string>Runnable:</string>
+       </property>
+      </widget>
+     </item>
+     <item row="3" column="0">
+      <widget class="QLabel" name="label_cli_options">
+       <property name="text">
+        <string>Center of rotation:</string>
+       </property>
+      </widget>
+     </item>
+     <item row="3" column="2">
+      <spacer name="horizontalSpacer_4">
+       <property name="orientation">
+        <enum>Qt::Horizontal</enum>
+       </property>
+       <property name="sizeHint" stdset="0">
+        <size>
+         <width>40</width>
+         <height>20</height>
+        </size>
+       </property>
+      </spacer>
+     </item>
+     <item row="1" column="1" colspan="2">
+      <widget class="QComboBox" name="comboBox_method">
+       <item>
+        <property name="text">
+         <string>FBP: filtered back propagation</string>
+        </property>
+       </item>
+       <item>
+        <property name="text">
+         <string>SIRT: statistical image reconstruction</string>
+        </property>
+       </item>
+      </widget>
+     </item>
+    </layout>
+   </item>
+   <item row="1" column="0">
+    <spacer name="verticalSpacer">
+     <property name="orientation">
+      <enum>Qt::Vertical</enum>
+     </property>
+     <property name="sizeHint" stdset="0">
+      <size>
+       <width>20</width>
+       <height>0</height>
+      </size>
+     </property>
+    </spacer>
+   </item>
+   <item row="2" column="0">
+    <layout class="QHBoxLayout" name="horizontalLayout">
+     <item>
+      <spacer name="horizontalSpacer">
+       <property name="orientation">
+        <enum>Qt::Horizontal</enum>
+       </property>
+       <property name="sizeHint" stdset="0">
+        <size>
+         <width>178</width>
+         <height>20</height>
+        </size>
+       </property>
+      </spacer>
+     </item>
+     <item>
+      <widget class="QDialogButtonBox" name="buttonBox">
+       <property name="orientation">
+        <enum>Qt::Horizontal</enum>
+       </property>
+       <property name="standardButtons">
+        <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
+       </property>
+      </widget>
+     </item>
+    </layout>
+   </item>
+  </layout>
+ </widget>
+ <resources/>
+ <connections>
+  <connection>
+   <sender>buttonBox</sender>
+   <signal>accepted()</signal>
+   <receiver>TomoToolConfigAstra</receiver>
+   <slot>accept()</slot>
+   <hints>
+    <hint type="sourcelabel">
+     <x>248</x>
+     <y>254</y>
+    </hint>
+    <hint type="destinationlabel">
+     <x>157</x>
+     <y>274</y>
+    </hint>
+   </hints>
+  </connection>
+  <connection>
+   <sender>buttonBox</sender>
+   <signal>rejected()</signal>
+   <receiver>TomoToolConfigAstra</receiver>
+   <slot>reject()</slot>
+   <hints>
+    <hint type="sourcelabel">
+     <x>316</x>
+     <y>260</y>
+    </hint>
+    <hint type="destinationlabel">
+     <x>286</x>
+     <y>274</y>
+    </hint>
+   </hints>
+  </connection>
+ </connections>
+</ui>
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/TomoReconstruction/TomoToolConfigCustom.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/TomoReconstruction/TomoToolConfigCustom.ui
new file mode 100644
index 0000000000000000000000000000000000000000..57122b76646bbc2eaada40f88340112fadc96291
--- /dev/null
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/TomoReconstruction/TomoToolConfigCustom.ui
@@ -0,0 +1,129 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>TomoToolConfigCustom</class>
+ <widget class="QDialog" name="TomoToolConfigCustom">
+  <property name="geometry">
+   <rect>
+    <x>0</x>
+    <y>0</y>
+    <width>802</width>
+    <height>278</height>
+   </rect>
+  </property>
+  <property name="windowTitle">
+   <string>Custom tool configuration</string>
+  </property>
+  <layout class="QGridLayout" name="gridLayout_2">
+   <item row="0" column="0">
+    <layout class="QGridLayout" name="gridLayout">
+     <item row="0" column="0">
+      <widget class="QLabel" name="label_runnable">
+       <property name="text">
+        <string>Runnable:</string>
+       </property>
+      </widget>
+     </item>
+     <item row="0" column="2">
+      <widget class="QLineEdit" name="lineEdit_runnable">
+       <property name="text">
+        <string>/work/imat/runs-scripts/scripts/tomopy/imat_recon_FBP.py</string>
+       </property>
+      </widget>
+     </item>
+     <item row="1" column="0" colspan="2">
+      <widget class="QLabel" name="label_cli_options">
+       <property name="sizePolicy">
+        <sizepolicy hsizetype="Preferred" vsizetype="Fixed">
+         <horstretch>0</horstretch>
+         <verstretch>0</verstretch>
+        </sizepolicy>
+       </property>
+       <property name="text">
+        <string>Command line options:</string>
+       </property>
+      </widget>
+     </item>
+     <item row="1" column="2">
+      <widget class="QTextEdit" name="textEdit_cl_opts">
+       <property name="sizePolicy">
+        <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
+         <horstretch>0</horstretch>
+         <verstretch>0</verstretch>
+        </sizepolicy>
+       </property>
+       <property name="html">
+        <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
+&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
+p, li { white-space: pre-wrap; }
+&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal;&quot;&gt;
+&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;--input_dir /work/imat/tomo_data_CCD/16\ dec\ 2013\ Test\ Wired/sample/ --dark /work/imat/tomo_data_CCD/16\ dec\ 2013\ Test\ Wired/dark --white /work/imat/tomo_data_CCD/16\ dec\ 2013\ Test\ Wired/beam/ --output_file /work/imat/remote/output/test_tomopy_FBP.nxs  --start_angle 0 --end_angle 30 --center_of_rotation 15&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+       </property>
+      </widget>
+     </item>
+     <item row="2" column="1" colspan="2">
+      <layout class="QVBoxLayout" name="verticalLayout">
+       <item>
+        <spacer name="verticalSpacer">
+         <property name="orientation">
+          <enum>Qt::Vertical</enum>
+         </property>
+         <property name="sizeHint" stdset="0">
+          <size>
+           <width>20</width>
+           <height>17</height>
+          </size>
+         </property>
+        </spacer>
+       </item>
+       <item>
+        <widget class="QDialogButtonBox" name="buttonBox">
+         <property name="orientation">
+          <enum>Qt::Horizontal</enum>
+         </property>
+         <property name="standardButtons">
+          <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
+         </property>
+        </widget>
+       </item>
+      </layout>
+     </item>
+    </layout>
+   </item>
+  </layout>
+ </widget>
+ <resources/>
+ <connections>
+  <connection>
+   <sender>buttonBox</sender>
+   <signal>accepted()</signal>
+   <receiver>TomoToolConfigCustom</receiver>
+   <slot>accept()</slot>
+   <hints>
+    <hint type="sourcelabel">
+     <x>248</x>
+     <y>254</y>
+    </hint>
+    <hint type="destinationlabel">
+     <x>157</x>
+     <y>274</y>
+    </hint>
+   </hints>
+  </connection>
+  <connection>
+   <sender>buttonBox</sender>
+   <signal>rejected()</signal>
+   <receiver>TomoToolConfigCustom</receiver>
+   <slot>reject()</slot>
+   <hints>
+    <hint type="sourcelabel">
+     <x>316</x>
+     <y>260</y>
+    </hint>
+    <hint type="destinationlabel">
+     <x>286</x>
+     <y>274</y>
+    </hint>
+   </hints>
+  </connection>
+ </connections>
+</ui>
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/TomoReconstruction/TomoToolConfigDialog.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/TomoReconstruction/TomoToolConfigDialog.h
new file mode 100644
index 0000000000000000000000000000000000000000..8b0ac868aec5a39ee3012f0ee9dff4cc769d310c
--- /dev/null
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/TomoReconstruction/TomoToolConfigDialog.h
@@ -0,0 +1,98 @@
+#ifndef MANTIDQTCUSTOMINTERFACES_TOMOTOOLCONFIGDIALOG_H_
+#define MANTIDQTCUSTOMINTERFACES_TOMOTOOLCONFIGDIALOG_H_
+
+#include "ui_TomoReconstruction.h"
+#include "ui_TomoToolConfigAstra.h"
+#include "ui_TomoToolConfigCustom.h"
+#include "ui_TomoToolConfigSavu.h"
+#include "ui_TomoToolConfigTomoPy.h"
+
+#include <QDialog>
+
+namespace MantidQt {
+namespace CustomInterfaces {
+
+/**
+Third party tool configuration dialog(s) for the tomographic reconstruction
+GUI.
+
+Copyright &copy; 2014,205 ISIS Rutherford Appleton Laboratory, NScD
+Oak Ridge National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid 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 General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+
+class TomoToolConfigTomoPy : public QDialog {
+  Q_OBJECT
+
+public:
+  TomoToolConfigTomoPy(QWidget *parent = 0);
+};
+
+class TomoToolConfigSavu : public QMainWindow {
+  Q_OBJECT
+public:
+  TomoToolConfigSavu(QWidget *parent = 0);
+
+private:
+  void initLayout();
+};
+
+class TomoToolConfigAstra : public QDialog {
+  Q_OBJECT
+public:
+  TomoToolConfigAstra(QWidget *parent = 0);
+
+private:
+  void initLayout();
+};
+
+class TomoToolConfigCustom : public QDialog {
+  Q_OBJECT
+public:
+  TomoToolConfigCustom(QWidget *parent = 0);
+
+private:
+  void initLayout();
+};
+
+class TomoToolConfigDialog : public QDialog {
+  Q_OBJECT
+
+public:
+  TomoToolConfigDialog(QWidget *parent = 0);
+
+private:
+  void initLayout();
+
+private slots:
+  void okClicked();
+  void cancelClicked();
+
+private:
+  QLabel *labelRun, *labelOpt;
+  QLineEdit *editRun, *editOpt;
+  QHBoxLayout *hRun, *hOpt, *hBut;
+  QGridLayout *layout;
+  QPushButton *okButton, *cancelButton;
+};
+}
+}
+
+#endif // MANTIDQTCUSTOMINTERFACES_TOMOTOOLCONFIGDIALOG_H_
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/TomoReconstruction/TomoToolConfigSavu.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/TomoReconstruction/TomoToolConfigSavu.ui
new file mode 100644
index 0000000000000000000000000000000000000000..633f346ec3f629f0c64a424deceda6edbd4f60c4
--- /dev/null
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/TomoReconstruction/TomoToolConfigSavu.ui
@@ -0,0 +1,392 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>TomoToolConfigSavu</class>
+ <widget class="QMainWindow" name="MainWindow">
+  <property name="geometry">
+   <rect>
+    <x>0</x>
+    <y>0</y>
+    <width>800</width>
+    <height>600</height>
+   </rect>
+  </property>
+  <property name="windowTitle">
+   <string>Savu configuration</string>
+  </property>
+  <widget class="QWidget" name="savuConfigCentralWidget">
+   <layout class="QGridLayout" name="gridLayout">
+    <item row="0" column="0">
+     <layout class="QVBoxLayout" name="verticalLayout">
+      <item>
+       <layout class="QVBoxLayout" name="verticalLayout_2">
+        <item>
+         <widget class="QMenuBar" name="menubar_2">
+          <property name="maximumSize">
+           <size>
+            <width>16777215</width>
+            <height>21</height>
+           </size>
+          </property>
+          <widget class="QMenu" name="menuFile">
+           <property name="title">
+            <string>File</string>
+           </property>
+           <addaction name="separator"/>
+          </widget>
+          <addaction name="menuFile"/>
+         </widget>
+        </item>
+        <item>
+         <widget class="QFrame" name="frame_2">
+          <property name="frameShape">
+           <enum>QFrame::Box</enum>
+          </property>
+          <property name="frameShadow">
+           <enum>QFrame::Raised</enum>
+          </property>
+          <layout class="QVBoxLayout" name="verticalLayout_3">
+           <property name="margin">
+            <number>0</number>
+           </property>
+           <item>
+            <widget class="QSplitter" name="splitterPlugins">
+             <property name="orientation">
+              <enum>Qt::Horizontal</enum>
+             </property>
+             <widget class="QFrame" name="frame_3">
+              <property name="frameShape">
+               <enum>QFrame::Box</enum>
+              </property>
+              <property name="frameShadow">
+               <enum>QFrame::Raised</enum>
+              </property>
+              <layout class="QVBoxLayout" name="verticalLayout_4">
+               <item>
+                <widget class="QFrame" name="pluginBar">
+                 <property name="minimumSize">
+                  <size>
+                   <width>0</width>
+                   <height>32</height>
+                  </size>
+                 </property>
+                 <property name="maximumSize">
+                  <size>
+                   <width>16777215</width>
+                   <height>32</height>
+                  </size>
+                 </property>
+                 <property name="baseSize">
+                  <size>
+                   <width>0</width>
+                   <height>32</height>
+                  </size>
+                 </property>
+                 <property name="frameShape">
+                  <enum>QFrame::NoFrame</enum>
+                 </property>
+                 <property name="frameShadow">
+                  <enum>QFrame::Raised</enum>
+                 </property>
+                 <layout class="QHBoxLayout" name="horizontalLayout_2">
+                  <property name="margin">
+                   <number>0</number>
+                  </property>
+                  <item>
+                   <widget class="QLabel" name="lblFilename">
+                    <property name="font">
+                     <font>
+                      <pointsize>10</pointsize>
+                     </font>
+                    </property>
+                    <property name="text">
+                     <string>Available Plugins:</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <spacer name="horizontalSpacer">
+                    <property name="orientation">
+                     <enum>Qt::Horizontal</enum>
+                    </property>
+                    <property name="sizeHint" stdset="0">
+                     <size>
+                      <width>284</width>
+                      <height>20</height>
+                     </size>
+                    </property>
+                   </spacer>
+                  </item>
+                  <item>
+                   <widget class="QPushButton" name="btnTransfer">
+                    <property name="font">
+                     <font>
+                      <pointsize>26</pointsize>
+                      <weight>75</weight>
+                      <bold>true</bold>
+                     </font>
+                    </property>
+                    <property name="text">
+                     <string>→</string>
+                    </property>
+                    <property name="autoDefault">
+                     <bool>false</bool>
+                    </property>
+                    <property name="default">
+                     <bool>false</bool>
+                    </property>
+                    <property name="flat">
+                     <bool>true</bool>
+                    </property>
+                   </widget>
+                  </item>
+                 </layout>
+                </widget>
+               </item>
+               <item>
+                <widget class="QListWidget" name="listAvailablePlugins">
+                 <property name="sizePolicy">
+                  <sizepolicy hsizetype="Expanding" vsizetype="Expanding">
+                   <horstretch>0</horstretch>
+                   <verstretch>3</verstretch>
+                  </sizepolicy>
+                 </property>
+                </widget>
+               </item>
+               <item>
+                <widget class="QTextBrowser" name="availablePluginDesc">
+                 <property name="maximumSize">
+                  <size>
+                   <width>16777215</width>
+                   <height>120</height>
+                  </size>
+                 </property>
+                 <property name="baseSize">
+                  <size>
+                   <width>0</width>
+                   <height>120</height>
+                  </size>
+                 </property>
+                </widget>
+               </item>
+              </layout>
+             </widget>
+             <widget class="QFrame" name="frame_4">
+              <property name="frameShape">
+               <enum>QFrame::Box</enum>
+              </property>
+              <property name="frameShadow">
+               <enum>QFrame::Raised</enum>
+              </property>
+              <layout class="QVBoxLayout" name="verticalLayout_5">
+               <item>
+                <widget class="QFrame" name="currentBar">
+                 <property name="minimumSize">
+                  <size>
+                   <width>0</width>
+                   <height>32</height>
+                  </size>
+                 </property>
+                 <property name="maximumSize">
+                  <size>
+                   <width>16777215</width>
+                   <height>32</height>
+                  </size>
+                 </property>
+                 <property name="baseSize">
+                  <size>
+                   <width>0</width>
+                   <height>32</height>
+                  </size>
+                 </property>
+                 <property name="frameShape">
+                  <enum>QFrame::NoFrame</enum>
+                 </property>
+                 <property name="frameShadow">
+                  <enum>QFrame::Raised</enum>
+                 </property>
+                 <layout class="QHBoxLayout" name="horizontalLayout_3">
+                  <property name="margin">
+                   <number>0</number>
+                  </property>
+                  <item>
+                   <widget class="QLabel" name="label">
+                    <property name="font">
+                     <font>
+                      <pointsize>10</pointsize>
+                     </font>
+                    </property>
+                    <property name="text">
+                     <string>Current configuration</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <spacer name="horizontalSpacer_2">
+                    <property name="orientation">
+                     <enum>Qt::Horizontal</enum>
+                    </property>
+                    <property name="sizeHint" stdset="0">
+                     <size>
+                      <width>239</width>
+                      <height>20</height>
+                     </size>
+                    </property>
+                   </spacer>
+                  </item>
+                  <item>
+                   <widget class="QPushButton" name="btnMoveUp">
+                    <property name="maximumSize">
+                     <size>
+                      <width>45</width>
+                      <height>16777215</height>
+                     </size>
+                    </property>
+                    <property name="font">
+                     <font>
+                      <pointsize>18</pointsize>
+                      <weight>75</weight>
+                      <italic>false</italic>
+                      <bold>true</bold>
+                     </font>
+                    </property>
+                    <property name="text">
+                     <string>â–²</string>
+                    </property>
+                    <property name="flat">
+                     <bool>true</bool>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <widget class="QPushButton" name="btnMoveDown">
+                    <property name="maximumSize">
+                     <size>
+                      <width>45</width>
+                      <height>16777215</height>
+                     </size>
+                    </property>
+                    <property name="font">
+                     <font>
+                      <pointsize>18</pointsize>
+                      <weight>75</weight>
+                      <italic>false</italic>
+                      <bold>true</bold>
+                     </font>
+                    </property>
+                    <property name="text">
+                     <string>â–¼</string>
+                    </property>
+                    <property name="flat">
+                     <bool>true</bool>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <widget class="QPushButton" name="btnRemove">
+                    <property name="maximumSize">
+                     <size>
+                      <width>45</width>
+                      <height>16777215</height>
+                     </size>
+                    </property>
+                    <property name="font">
+                     <font>
+                      <pointsize>16</pointsize>
+                      <weight>75</weight>
+                      <bold>true</bold>
+                     </font>
+                    </property>
+                    <property name="text">
+                     <string>X</string>
+                    </property>
+                    <property name="flat">
+                     <bool>true</bool>
+                    </property>
+                   </widget>
+                  </item>
+                 </layout>
+                </widget>
+               </item>
+               <item>
+                <widget class="QTreeWidget" name="treeCurrentPlugins">
+                 <property name="sizePolicy">
+                  <sizepolicy hsizetype="Expanding" vsizetype="Expanding">
+                   <horstretch>1</horstretch>
+                   <verstretch>0</verstretch>
+                  </sizepolicy>
+                 </property>
+                 <property name="toolTip">
+                  <string>Here you can modify the parameters of the plugins.
+Double-click on them to modify their values.</string>
+                 </property>
+                 <column>
+                  <property name="text">
+                   <string notr="true">1</string>
+                  </property>
+                 </column>
+                </widget>
+               </item>
+               <item>
+                <widget class="QTextBrowser" name="currentPluginDesc">
+                 <property name="sizePolicy">
+                  <sizepolicy hsizetype="Expanding" vsizetype="Expanding">
+                   <horstretch>1</horstretch>
+                   <verstretch>0</verstretch>
+                  </sizepolicy>
+                 </property>
+                 <property name="maximumSize">
+                  <size>
+                   <width>16777215</width>
+                   <height>120</height>
+                  </size>
+                 </property>
+                </widget>
+               </item>
+              </layout>
+             </widget>
+            </widget>
+           </item>
+          </layout>
+         </widget>
+        </item>
+       </layout>
+      </item>
+      <item>
+       <layout class="QHBoxLayout" name="horizontalLayout">
+        <item>
+         <widget class="QPushButton" name="pushButton_Help">
+          <property name="maximumSize">
+           <size>
+            <width>23</width>
+            <height>23</height>
+           </size>
+          </property>
+          <property name="text">
+           <string>?</string>
+          </property>
+         </widget>
+        </item>
+        <item>
+         <spacer name="horizontalSpacer_3">
+          <property name="orientation">
+           <enum>Qt::Horizontal</enum>
+          </property>
+          <property name="sizeHint" stdset="0">
+           <size>
+            <width>728</width>
+            <height>20</height>
+           </size>
+          </property>
+         </spacer>
+        </item>
+       </layout>
+      </item>
+     </layout>
+    </item>
+   </layout>
+  </widget>
+  <widget class="QStatusBar" name="statusbar"/>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/TomoReconstruction/TomoToolConfigTomoPy.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/TomoReconstruction/TomoToolConfigTomoPy.ui
new file mode 100644
index 0000000000000000000000000000000000000000..46115129d691867cc0124690bcb7b9e3ce20795a
--- /dev/null
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/TomoReconstruction/TomoToolConfigTomoPy.ui
@@ -0,0 +1,233 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>TomoToolConfigTomoPy</class>
+ <widget class="QDialog" name="TomoToolConfigTomoPy">
+  <property name="windowModality">
+   <enum>Qt::WindowModal</enum>
+  </property>
+  <property name="geometry">
+   <rect>
+    <x>0</x>
+    <y>0</y>
+    <width>584</width>
+    <height>224</height>
+   </rect>
+  </property>
+  <property name="windowTitle">
+   <string>TomoPy Configuration</string>
+  </property>
+  <layout class="QGridLayout" name="gridLayout_3">
+   <item row="0" column="0">
+    <layout class="QGridLayout" name="gridLayout_2">
+     <item row="4" column="0" colspan="3">
+      <widget class="QGroupBox" name="groupBox">
+       <property name="title">
+        <string>Angles</string>
+       </property>
+       <layout class="QGridLayout" name="gridLayout">
+        <item row="0" column="0">
+         <widget class="QLabel" name="label_runnable_2">
+          <property name="text">
+           <string>Min:</string>
+          </property>
+         </widget>
+        </item>
+        <item row="0" column="4">
+         <spacer name="horizontalSpacer_2">
+          <property name="orientation">
+           <enum>Qt::Horizontal</enum>
+          </property>
+          <property name="sizeHint" stdset="0">
+           <size>
+            <width>174</width>
+            <height>20</height>
+           </size>
+          </property>
+         </spacer>
+        </item>
+        <item row="1" column="0">
+         <widget class="QLabel" name="label_runnable_4">
+          <property name="enabled">
+           <bool>false</bool>
+          </property>
+          <property name="text">
+           <string>List:</string>
+          </property>
+         </widget>
+        </item>
+        <item row="0" column="2">
+         <widget class="QLabel" name="label_runnable_3">
+          <property name="text">
+           <string>Max:</string>
+          </property>
+         </widget>
+        </item>
+        <item row="1" column="1" colspan="4">
+         <widget class="QLineEdit" name="lineEdit">
+          <property name="enabled">
+           <bool>false</bool>
+          </property>
+         </widget>
+        </item>
+        <item row="0" column="3">
+         <widget class="QDoubleSpinBox" name="doubleSpinBox_angle_max">
+          <property name="maximum">
+           <double>180.000000000000000</double>
+          </property>
+          <property name="value">
+           <double>180.000000000000000</double>
+          </property>
+         </widget>
+        </item>
+        <item row="0" column="1">
+         <widget class="QDoubleSpinBox" name="doubleSpinBox_angle_min">
+          <property name="maximum">
+           <double>360.000000000000000</double>
+          </property>
+         </widget>
+        </item>
+       </layout>
+      </widget>
+     </item>
+     <item row="3" column="1">
+      <widget class="QDoubleSpinBox" name="doubleSpinBox_center_rot">
+       <property name="maximum">
+        <double>180.000000000000000</double>
+       </property>
+      </widget>
+     </item>
+     <item row="1" column="0">
+      <widget class="QLabel" name="label">
+       <property name="text">
+        <string>Method:</string>
+       </property>
+      </widget>
+     </item>
+     <item row="2" column="1" colspan="2">
+      <widget class="QLineEdit" name="lineEdit_runnable">
+       <property name="text">
+        <string>/work/imat/runs-scripts/scripts/tomopy/imat_recon_FBP.py</string>
+       </property>
+      </widget>
+     </item>
+     <item row="2" column="0">
+      <widget class="QLabel" name="label_runnable">
+       <property name="text">
+        <string>Runnable:</string>
+       </property>
+      </widget>
+     </item>
+     <item row="3" column="0">
+      <widget class="QLabel" name="label_cli_options">
+       <property name="text">
+        <string>Center of rotation:</string>
+       </property>
+      </widget>
+     </item>
+     <item row="3" column="2">
+      <spacer name="horizontalSpacer_4">
+       <property name="orientation">
+        <enum>Qt::Horizontal</enum>
+       </property>
+       <property name="sizeHint" stdset="0">
+        <size>
+         <width>40</width>
+         <height>20</height>
+        </size>
+       </property>
+      </spacer>
+     </item>
+     <item row="1" column="1" colspan="2">
+      <widget class="QComboBox" name="comboBox_method">
+       <item>
+        <property name="text">
+         <string>FBP: filtered back propagation</string>
+        </property>
+       </item>
+       <item>
+        <property name="text">
+         <string>SIRT: statistical image reconstruction</string>
+        </property>
+       </item>
+      </widget>
+     </item>
+    </layout>
+   </item>
+   <item row="1" column="0">
+    <spacer name="verticalSpacer">
+     <property name="orientation">
+      <enum>Qt::Vertical</enum>
+     </property>
+     <property name="sizeHint" stdset="0">
+      <size>
+       <width>20</width>
+       <height>0</height>
+      </size>
+     </property>
+    </spacer>
+   </item>
+   <item row="2" column="0">
+    <layout class="QHBoxLayout" name="horizontalLayout">
+     <item>
+      <spacer name="horizontalSpacer">
+       <property name="orientation">
+        <enum>Qt::Horizontal</enum>
+       </property>
+       <property name="sizeHint" stdset="0">
+        <size>
+         <width>178</width>
+         <height>20</height>
+        </size>
+       </property>
+      </spacer>
+     </item>
+     <item>
+      <widget class="QDialogButtonBox" name="buttonBox">
+       <property name="orientation">
+        <enum>Qt::Horizontal</enum>
+       </property>
+       <property name="standardButtons">
+        <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
+       </property>
+      </widget>
+     </item>
+    </layout>
+   </item>
+  </layout>
+ </widget>
+ <resources/>
+ <connections>
+  <connection>
+   <sender>buttonBox</sender>
+   <signal>accepted()</signal>
+   <receiver>TomoToolConfigTomoPy</receiver>
+   <slot>accept()</slot>
+   <hints>
+    <hint type="sourcelabel">
+     <x>434</x>
+     <y>200</y>
+    </hint>
+    <hint type="destinationlabel">
+     <x>291</x>
+     <y>111</y>
+    </hint>
+   </hints>
+  </connection>
+  <connection>
+   <sender>buttonBox</sender>
+   <signal>rejected()</signal>
+   <receiver>TomoToolConfigTomoPy</receiver>
+   <slot>reject()</slot>
+   <hints>
+    <hint type="sourcelabel">
+     <x>434</x>
+     <y>200</y>
+    </hint>
+    <hint type="destinationlabel">
+     <x>291</x>
+     <y>111</y>
+    </hint>
+   </hints>
+  </connection>
+ </connections>
+</ui>
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/TomoReconstruction/ToolSettings.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/TomoReconstruction/ToolSettings.h
new file mode 100644
index 0000000000000000000000000000000000000000..db26452e7152a2da16583ae985b79fd519d89995
--- /dev/null
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/TomoReconstruction/ToolSettings.h
@@ -0,0 +1,182 @@
+#ifndef MANTIDQTCUSTOMINTERFACES_TOOLSETTINGS_H_
+#define MANTIDQTCUSTOMINTERFACES_TOOLSETTINGS_H_
+
+#include <string>
+
+namespace MantidQt {
+namespace CustomInterfaces {
+
+/**
+Third party tool settings for the tomographic reconstruction GUI. This
+is under heavy development, and as it is not necessarily related to
+custom interfaces might be moved out of here.
+
+Copyright &copy; 2014,205 ISIS Rutherford Appleton Laboratory, NScD
+Oak Ridge National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid 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 General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+
+/**
+ * General tool settings. This class represents the settings of a
+ * third party or external tool/program/module/etc. that Mantid would
+ * run either locally or on a remote computer. The purpose here is to
+ * produce the command line or similar that will run the third party
+ * tool for certain user requirements/settings/options/preferences.
+ *
+ * TODO: a related class to represent third party tools should be
+ * added that would take care of platform specificities, tool
+ * availability, execute permissions, etc.
+ */
+class ToolSettings {
+public:
+  /**
+   * Construct a settings object, given a 'runnable', which can be an
+   * application, executable, script, etc. - the access point to a
+   * third party tool. If this class is developed to be smart enough,
+   * and with the help of the additional '3rd party tool' class, it
+   * should be able to translate application names into binary paths
+   * and similar internally.
+   *
+   * @param runnable name of the runnable object (application, executable,
+   * etc.). This can be a full path, an application name, etc. At
+   * present it is used in its simplest form: platform and machine
+   * dependent full path to an execuatable or script.
+   */
+  ToolSettings(const std::string &runnable) : m_runnable(runnable) {}
+
+  /**
+   * validate that it is possible to produce a sensible command line
+   * from this settings object.
+   *
+   * @return the tool and its settings are consistent and it looks
+   * like it should be possible to run it.
+   */
+  virtual bool valid() const { return true; }
+
+  /**
+   * Produce a command line to run this tool with these settings.
+   *
+   * @return command line ready to run on a certain platform
+   */
+  virtual std::string toCommand() const {
+    return makeExecutable() + " " + makeCmdLineOptions();
+  }
+
+  /**
+   * Produces a string with the command line options derived from the
+   * different options set.
+   *
+   * @return command line options string
+   */
+  virtual std::string makeCmdLineOptions() const = 0;
+
+  /**
+   * Produces an string that describes the executable, ready to run
+   * as a binary, python or other type of scripts, etc. Normally you
+   * append command line options to this.
+   */
+  virtual std::string makeExecutable() const = 0;
+
+protected:
+  std::string m_runnable;
+
+private:
+  ToolSettings(ToolSettings &);
+};
+
+/**
+ * Custom command line settings. To run a command of the user's choice
+ * with free-form options.
+ */
+class ToolSettingsCustom : public ToolSettings {
+public:
+  ToolSettingsCustom(const std::string &runnable, const std::string &cmdOptions)
+      : ToolSettings(runnable), m_opts(cmdOptions) {}
+
+protected:
+  virtual std::string makeCmdLineOptions() const { return m_opts; }
+
+  virtual std::string makeExecutable() const { return m_runnable; };
+
+private:
+  ToolSettingsCustom(ToolSettings &);
+
+  std::string m_opts;
+};
+
+/**
+ * Third party tool settings class specialized for the settings of the
+ * TomoPy tomographic reconstruction tool (Python + C++):
+ * https://www1.aps.anl.gov/Science/Scientific-Software/TomoPy
+ */
+class ToolSettingsTomoPy : public ToolSettings {
+public:
+  ToolSettingsTomoPy(const std::string &runnable, const std::string &pathOut,
+                     const std::string &pathDark, const std::string &pathOpen,
+                     const std::string &pathSample, double centerRot,
+                     double angleMin, double angleMax);
+
+protected:
+  virtual std::string makeCmdLineOptions() const;
+
+  virtual std::string makeExecutable() const { return m_runnable; };
+
+private:
+  std::string m_pathOut;
+  std::string m_pathDark;
+  std::string m_pathOpen;
+  std::string m_pathSample;
+  double m_centerRot;
+  double m_angleMin;
+  double m_angleMax;
+};
+
+/**
+ * Third party tool settings class specialized for the settings of the
+ * Astra Toolbox tomographic reconstruction tool (C++): Astra Toolbox
+ * <http://sourceforge.net/p/astra-toolbox/wiki/Home/
+ */
+class ToolSettingsAstraToolbox : public ToolSettings {
+public:
+  ToolSettingsAstraToolbox(const std::string &runnable, double centerRot,
+                           double angleMin, double angleMax,
+                           const std::string &pathOut,
+                           const std::string &pathDark,
+                           const std::string &pathOpen,
+                           const std::string &pathSample);
+
+protected:
+  virtual std::string makeCmdLineOptions() const;
+
+  virtual std::string makeExecutable() const { return m_runnable; };
+
+private:
+  double m_centerRot;
+  double m_angleMin;
+  double m_angleMax;
+  std::string m_pathOut;
+  std::string m_pathDark;
+  std::string m_pathOpen;
+  std::string m_pathSample;
+};
+}
+}
+
+#endif // MANTIDQTCUSTOMINTERFACES_TOOLSETTINGS_H_
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/CalcCorr.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/CalcCorr.cpp
index 7177d6f3fad519e6333eeb0f405dd7d4442f37a4..39acdebbae9ffb9814f7b1874a2272c3b3d815a8 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/CalcCorr.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/CalcCorr.cpp
@@ -295,15 +295,26 @@ namespace IDA
       return;
     }
 
-    std::string paramName = "Workflow.beam-width";
     auto instrument = ws->getInstrument();
 
-    if(instrument->hasParameter(paramName))
+    const std::string beamWidthParamName = "Workflow.beam-width";
+    if(instrument->hasParameter(beamWidthParamName))
     {
-      QString beamWidth = QString::fromStdString(instrument->getStringParameter(paramName)[0]);
+      QString beamWidth = QString::fromStdString(instrument->getStringParameter(beamWidthParamName)[0]);
       double beamWidthValue = beamWidth.toDouble();
+
       m_uiForm.spCylBeamWidth->setValue(beamWidthValue);
-      m_uiForm.spCylBeamHeight->setValue(beamWidthValue);
+      m_uiForm.spAnnBeamWidth->setValue(beamWidthValue);
+    }
+
+    const std::string beamHeightParamName = "Workflow.beam-height";
+    if(instrument->hasParameter(beamHeightParamName))
+    {
+      QString beamHeight = QString::fromStdString(instrument->getStringParameter(beamHeightParamName)[0]);
+      double beamHeightValue = beamHeight.toDouble();
+
+      m_uiForm.spCylBeamHeight->setValue(beamHeightValue);
+      m_uiForm.spAnnBeamHeight->setValue(beamHeightValue);
     }
   }
 
@@ -326,8 +337,7 @@ namespace IDA
     }
     else if(shape == "Cylinder")
     {
-      double sampleInnerRadius = m_uiForm.spCylSampleInnerRadius->value();
-      alg->setProperty("SampleInnerRadius", sampleInnerRadius);
+      alg->setProperty("SampleInnerRadius", 0.0);
 
       double sampleOuterRadius = m_uiForm.spCylSampleOuterRadius->value();
       alg->setProperty("SampleOuterRadius", sampleOuterRadius);
@@ -343,7 +353,8 @@ namespace IDA
     }
     else if(shape == "Annulus")
     {
-      alg->setProperty("SampleInnerRadius", 0.0);
+      double sampleInnerRadius = m_uiForm.spAnnSampleInnerRadius->value();
+      alg->setProperty("SampleInnerRadius", sampleInnerRadius);
 
       double sampleOuterRadius = m_uiForm.spAnnSampleOuterRadius->value();
       alg->setProperty("SampleOuterRadius", sampleOuterRadius);
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ConvFit.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ConvFit.cpp
index 4928536fdfdb4eecaafd63fb84c08ecec4d018aa..12332b355a81bae7ab824009ecda92d942f20615 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ConvFit.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ConvFit.cpp
@@ -127,6 +127,9 @@ namespace IDA
     connect(m_uiForm.spPlotSpectrum, SIGNAL(valueChanged(int)), this, SLOT(updatePlot()));
     connect(m_uiForm.dsSampleInput, SIGNAL(dataReady(const QString&)), this, SLOT(newDataLoaded(const QString&)));
 
+    connect(m_uiForm.dsSampleInput, SIGNAL(dataReady(const QString&)), this, SLOT(extendResolutionWorkspace()));
+    connect(m_uiForm.dsResInput, SIGNAL(dataReady(const QString&)), this, SLOT(extendResolutionWorkspace()));
+
     connect(m_uiForm.spSpectraMin, SIGNAL(valueChanged(int)), this, SLOT(specMinChanged(int)));
     connect(m_uiForm.spSpectraMax, SIGNAL(valueChanged(int)), this, SLOT(specMaxChanged(int)));
 
@@ -270,6 +273,44 @@ namespace IDA
     updatePlot();
   }
 
+  /**
+   * Create a resolution workspace with the same number of histograms as in the sample.
+   *
+   * Needed to allow DiffSphere and DiffRotDiscreteCircle fit functions to work as they need
+   * to have the WorkspaceIndex attribute set.
+   */
+  void ConvFit::extendResolutionWorkspace()
+  {
+    if(m_cfInputWS && m_uiForm.dsResInput->isValid())
+    {
+      const QString resWsName = m_uiForm.dsResInput->getCurrentDataName();
+
+      API::BatchAlgorithmRunner::AlgorithmRuntimeProps appendProps;
+      appendProps["InputWorkspace1"] = "__ConvFit_Resolution";
+
+      size_t numHist = m_cfInputWS->getNumberHistograms();
+      for(size_t i = 0; i < numHist; i++)
+      {
+        IAlgorithm_sptr appendAlg = AlgorithmManager::Instance().create("AppendSpectra");
+        appendAlg->initialize();
+        appendAlg->setProperty("InputWorkspace2", resWsName.toStdString());
+        appendAlg->setProperty("OutputWorkspace", "__ConvFit_Resolution");
+
+        if(i == 0)
+        {
+          appendAlg->setProperty("InputWorkspace1", resWsName.toStdString());
+          m_batchAlgoRunner->addAlgorithm(appendAlg);
+        }
+        else
+        {
+          m_batchAlgoRunner->addAlgorithm(appendAlg, appendProps);
+        }
+      }
+
+      m_batchAlgoRunner->executeBatchAsync();
+    }
+  }
+
   namespace
   {
     ////////////////////////////
@@ -389,8 +430,7 @@ namespace IDA
     conv->addFunction(func);
 
     //add resolution file
-    std::string resWorkspace = m_uiForm.dsResInput->getCurrentDataName().toStdString();
-    IFunction::Attribute attr(resWorkspace);
+    IFunction::Attribute attr("__ConvFit_Resolution");
     func->setAttribute("Workspace", attr);
 
     // --------------------------------------------------------
@@ -634,16 +674,21 @@ namespace IDA
   {
     QtProperty* diffRotDiscreteCircleGroup = m_grpManager->addProperty(name);
 
+    m_properties[name+".N"] = m_dblManager->addProperty("N");
+    m_dblManager->setValue(m_properties[name+".N"], 3.0);
+
     m_properties[name+".Intensity"] = m_dblManager->addProperty("Intensity");
     m_properties[name+".Radius"] = m_dblManager->addProperty("Radius");
     m_properties[name+".Decay"] = m_dblManager->addProperty("Decay");
     m_properties[name+".Shift"] = m_dblManager->addProperty("Shift");
 
+    m_dblManager->setDecimals(m_properties[name+".N"], 0);
     m_dblManager->setDecimals(m_properties[name+".Intensity"], NUM_DECIMALS);
     m_dblManager->setDecimals(m_properties[name+".Radius"], NUM_DECIMALS);
     m_dblManager->setDecimals(m_properties[name+".Decay"], NUM_DECIMALS);
     m_dblManager->setDecimals(m_properties[name+".Shift"], NUM_DECIMALS);
 
+    diffRotDiscreteCircleGroup->addSubProperty(m_properties[name+".N"]);
     diffRotDiscreteCircleGroup->addSubProperty(m_properties[name+".Intensity"]);
     diffRotDiscreteCircleGroup->addSubProperty(m_properties[name+".Radius"]);
     diffRotDiscreteCircleGroup->addSubProperty(m_properties[name+".Decay"]);
@@ -669,9 +714,12 @@ namespace IDA
       {
         std::string propName = props[i]->propertyName().toStdString();
         double propValue = props[i]->valueText().toDouble();
-        if ( propValue )
+        if(propValue)
         {
-          func->setParameter(propName, propValue);
+          if(func->hasAttribute(propName))
+            func->setAttributeValue(propName, propValue);
+          else
+            func->setParameter(propName, propValue);
         }
       }
     }
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ISISCalibration.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ISISCalibration.cpp
index 11a8d425db0a29e383bbc6099e4cde2766e74a59..47f571cee9dcce3ca2b2355e12caf263d0feb348 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ISISCalibration.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ISISCalibration.cpp
@@ -430,14 +430,14 @@ namespace CustomInterfaces
     QString detRange = QString::number(m_dblManager->value(m_properties["ResSpecMin"])) + ","
                      + QString::number(m_dblManager->value(m_properties["ResSpecMax"]));
 
-    IAlgorithm_sptr reductionAlg = AlgorithmManager::Instance().create("InelasticIndirectReduction");
+    IAlgorithm_sptr reductionAlg = AlgorithmManager::Instance().create("ISISIndirectEnergyTransfer");
     reductionAlg->initialize();
     reductionAlg->setProperty("Instrument", getInstrumentConfiguration()->getInstrumentName().toStdString());
     reductionAlg->setProperty("Analyser", getInstrumentConfiguration()->getAnalyserName().toStdString());
     reductionAlg->setProperty("Reflection", getInstrumentConfiguration()->getReflectionName().toStdString());
     reductionAlg->setProperty("InputFiles", files.toStdString());
     reductionAlg->setProperty("OutputWorkspace", "__IndirectCalibration_reduction");
-    reductionAlg->setProperty("DetectorRange", detRange.toStdString());
+    reductionAlg->setProperty("SpectraRange", detRange.toStdString());
     reductionAlg->execute();
 
     if(!reductionAlg->isExecuted())
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ISISEnergyTransfer.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ISISEnergyTransfer.cpp
index ae5c94bac4af7dc65a9fd3ccd8dda22f84ce187f..a041765eac19c72fecf784542226b4c92b4a8824 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ISISEnergyTransfer.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ISISEnergyTransfer.cpp
@@ -1,13 +1,13 @@
 #include "MantidQtCustomInterfaces/Indirect/ISISEnergyTransfer.h"
 
 #include "MantidGeometry/IDTypes.h"
-#include "MantidQtCustomInterfaces/Background.h"
 #include "MantidQtCustomInterfaces/UserInputValidator.h"
 
 #include <QFileInfo>
 #include <QInputDialog>
 
 using namespace Mantid::API;
+using MantidQt::API::BatchAlgorithmRunner;
 
 namespace MantidQt
 {
@@ -106,10 +106,9 @@ namespace CustomInterfaces
 
   void ISISEnergyTransfer::run()
   {
-    using MantidQt::API::BatchAlgorithmRunner;
-
-    IAlgorithm_sptr reductionAlg = AlgorithmManager::Instance().create("InelasticIndirectReduction", -1);
+    IAlgorithm_sptr reductionAlg = AlgorithmManager::Instance().create("ISISIndirectEnergyTransfer");
     reductionAlg->initialize();
+    BatchAlgorithmRunner::AlgorithmRuntimeProps reductionRuntimeProps;
 
     reductionAlg->setProperty("Instrument", getInstrumentConfiguration()->getInstrumentName().toStdString());
     reductionAlg->setProperty("Analyser", getInstrumentConfiguration()->getAnalyserName().toStdString());
@@ -119,7 +118,6 @@ namespace CustomInterfaces
     reductionAlg->setProperty("InputFiles", files.toStdString());
 
     reductionAlg->setProperty("SumFiles", m_uiForm.ckSumFiles->isChecked());
-    reductionAlg->setProperty("LoadLogs", m_uiForm.ckLoadLogs->isChecked());
 
     if(m_uiForm.ckUseCalib->isChecked())
     {
@@ -130,7 +128,7 @@ namespace CustomInterfaces
     std::vector<long> detectorRange;
     detectorRange.push_back(m_uiForm.spSpectraMin->value());
     detectorRange.push_back(m_uiForm.spSpectraMax->value());
-    reductionAlg->setProperty("DetectorRange", detectorRange);
+    reductionAlg->setProperty("SpectraRange", detectorRange);
 
     if(m_uiForm.ckBackgroundRemoval->isChecked())
     {
@@ -157,32 +155,23 @@ namespace CustomInterfaces
     if(m_uiForm.ckScaleMultiplier->isChecked())
       reductionAlg->setProperty("ScaleFactor", m_uiForm.spScaleMultiplier->value());
 
-    if(m_uiForm.cbGroupingOptions->currentText() != "Default")
-    {
-      QString grouping = createMapFile(m_uiForm.cbGroupingOptions->currentText());
-      reductionAlg->setProperty("Grouping", grouping.toStdString());
-    }
+    if(m_uiForm.ckCm1Units->isChecked())
+      reductionAlg->setProperty("UnitX", "DeltaE_inWavenumber");
 
-    reductionAlg->setProperty("Fold", m_uiForm.ckFold->isChecked());
-    reductionAlg->setProperty("SaveCM1", m_uiForm.ckCm1Units->isChecked());
-    reductionAlg->setProperty("SaveFormats", getSaveFormats());
+    QPair<QString, QString> grouping = createMapFile(m_uiForm.cbGroupingOptions->currentText());
+    reductionAlg->setProperty("GroupingMethod", grouping.first.toStdString());
 
-    reductionAlg->setProperty("OutputWorkspace", "IndirectEnergyTransfer_Workspaces");
+    if(grouping.first == "Workspace")
+      reductionRuntimeProps["GroupingWorkspace"] = grouping.second.toStdString();
+    else if(grouping.second == "File")
+      reductionAlg->setProperty("MapFile", grouping.second.toStdString());
 
-    // Plot Output options
-    switch(m_uiForm.cbPlotType->currentIndex())
-    {
-      case 0: // "None"
-        break;
-      case 1: // "Spectra"
-        reductionAlg->setProperty("Plot", "spectra");
-        break;
-      case 2: // "Contour"
-        reductionAlg->setProperty("Plot", "contour");
-        break;
-    }
+    reductionAlg->setProperty("FoldMultipleFrames", m_uiForm.ckFold->isChecked());
+    reductionAlg->setProperty("Plot", m_uiForm.cbPlotType->currentText().toStdString());
+    reductionAlg->setProperty("SaveFormats", getSaveFormats());
+    reductionAlg->setProperty("OutputWorkspace", "IndirectEnergyTransfer_Workspaces");
 
-    m_batchAlgoRunner->addAlgorithm(reductionAlg);
+    m_batchAlgoRunner->addAlgorithm(reductionAlg, reductionRuntimeProps);
 
     connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(algorithmComplete(bool)));
     disconnect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(plotRawComplete(bool)));
@@ -244,8 +233,8 @@ namespace CustomInterfaces
     m_uiForm.spSpectraMax->setMaximum(specMax);
     m_uiForm.spSpectraMax->setValue(specMax);
 
-    if(!instDetails["efixed-val"].isEmpty())
-      m_uiForm.leEfixed->setText(instDetails["efixed-val"]);
+    if(!instDetails["Efixed"].isEmpty())
+      m_uiForm.leEfixed->setText(instDetails["Efixed"]);
     else
       m_uiForm.leEfixed->clear();
 
@@ -282,6 +271,12 @@ namespace CustomInterfaces
       m_uiForm.ckCm1Units->setChecked(defaultOptions);
     }
 
+    if(!instDetails["save-nexus-choice"].isEmpty())
+    {
+      bool defaultOptions = instDetails["save-nexus-choice"] == "true";
+      m_uiForm.ckSaveNexus->setChecked(defaultOptions);
+    }
+
     if(!instDetails["save-ascii-choice"].isEmpty())
     {
       bool defaultOptions = instDetails["save-ascii-choice"] == "true";
@@ -320,7 +315,7 @@ namespace CustomInterfaces
    * @param groupType :: Type of grouping (All, Group, Indiviual)
    * @return path to mapping file, or an empty string if file could not be created.
    */
-  QString ISISEnergyTransfer::createMapFile(const QString& groupType)
+  QPair<QString, QString> ISISEnergyTransfer::createMapFile(const QString& groupType)
   {
     QString specRange = m_uiForm.spSpectraMin->text() + "," + m_uiForm.spSpectraMax->text();
 
@@ -328,10 +323,9 @@ namespace CustomInterfaces
     {
       QString groupFile = m_uiForm.dsMapFile->getFirstFilename();
       if(groupFile == "")
-      {
         emit showMessageBox("You must enter a path to the .map file.");
-      }
-      return groupFile;
+
+      return qMakePair(QString("File"), groupFile);
     }
     else if(groupType == "Groups")
     {
@@ -347,18 +341,22 @@ namespace CustomInterfaces
 
       m_batchAlgoRunner->addAlgorithm(groupingAlg);
 
-      return groupWS;
+      return qMakePair(QString("Workspace"), groupWS);
+    }
+    else if (groupType == "Default")
+    {
+      return qMakePair(QString("IPF"), QString());
     }
     else
     {
       // Catch All and Individual
-      return groupType;
+      return qMakePair(groupType, QString());
     }
   }
 
   /**
    * Converts the checkbox selection to a comma delimited list of save formats for the
-   * InelasticIndirectReduction algorithm.
+   * ISISIndirectEnergyTransfer algorithm.
    *
    * @return A vector of save formats
    */
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDataReduction.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDataReduction.cpp
index 3bc7f982fb8738ef2db888419b97e1f06509c6c7..b8d7b76269fd7b96590e247dd8fcd1f497f14e33 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDataReduction.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDataReduction.cpp
@@ -258,13 +258,14 @@ std::map<QString, QString> IndirectDataReduction::getInstrumentDetails()
   ipfElements.push_back("analysis-type");
   ipfElements.push_back("spectra-min");
   ipfElements.push_back("spectra-max");
-  ipfElements.push_back("efixed-val");
+  ipfElements.push_back("Efixed");
   ipfElements.push_back("peak-start");
   ipfElements.push_back("peak-end");
   ipfElements.push_back("back-start");
   ipfElements.push_back("back-end");
   ipfElements.push_back("rebin-default");
   ipfElements.push_back("cm-1-convert-choice");
+  ipfElements.push_back("save-nexus-choice");
   ipfElements.push_back("save-ascii-choice");
   ipfElements.push_back("fold-frames-choice");
 
@@ -293,7 +294,7 @@ std::map<QString, QString> IndirectDataReduction::getInstrumentDetails()
       QString value = getInstrumentParameterFrom(instrument, key);
 
       if(value.isEmpty() && component != NULL)
-        QString value = getInstrumentParameterFrom(component, key);
+        value = getInstrumentParameterFrom(component, key);
 
       instDetails[QString::fromStdString(key)] = value;
     }
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDiffractionReduction.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDiffractionReduction.cpp
index 9516a1d50162596e62d2b2cf206f41d93fd02377..e299035cf7a85655bb8ceb358989904a01bf755c 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDiffractionReduction.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDiffractionReduction.cpp
@@ -245,8 +245,8 @@ void IndirectDiffractionReduction::runOSIRISdiffonlyReduction()
   try
   {
     QString nameBase = QString::fromStdString(Mantid::Kernel::MultiFileNameParsing::suggestWorkspaceName(stlFileNames));
-    tofWsName = "'" + nameBase + "_tof'";
-    drangeWsName = "'" + nameBase + "_dRange'";
+    tofWsName = nameBase + "_tof";
+    drangeWsName = nameBase + "_dRange";
   }
   catch(std::runtime_error & re)
   {
@@ -356,6 +356,9 @@ void IndirectDiffractionReduction::instrumentSelected(const QString & instrument
 {
   UNUSED_ARG(analyserName);
 
+  // Set the search instrument for runs
+  m_uiForm.dem_rawFiles->setInstrumentOverride(instrumentName);
+
   MatrixWorkspace_sptr instWorkspace = loadInstrument(instrumentName.toStdString(), reflectionName.toStdString());
   Instrument_const_sptr instrument = instWorkspace->getInstrument();
 
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectSqw.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectSqw.cpp
index 1958d94efca0e6be134d9aabc79e8ef55ee85b33..84912376515932c000de10622c06fd9b0ae14340 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectSqw.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectSqw.cpp
@@ -84,16 +84,15 @@ namespace CustomInterfaces
       m_batchAlgoRunner->addAlgorithm(energyRebinAlg);
     }
 
-    // Get correct S(Q, w) algorithm
-    QString eFixed = getInstrumentDetails()["efixed-val"];
+    QString eFixed = getInstrumentDetails()["Efixed"];
 
-    IAlgorithm_sptr sqwAlg;
+    IAlgorithm_sptr sqwAlg = AlgorithmManager::Instance().create("SofQW");
     QString rebinType = m_uiForm.cbRebinType->currentText();
 
-    if(rebinType == "Parallelepiped (SofQW2)")
-      sqwAlg = AlgorithmManager::Instance().create("SofQW2");
-    else if(rebinType == "Parallelepiped/Fractional Area (SofQW3)")
-      sqwAlg = AlgorithmManager::Instance().create("SofQW3");
+    if(rebinType == "Parallelepiped")
+      sqwAlg->setProperty("Method", "Polygon");
+    else if(rebinType == "Parallelepiped/Fractional Area")
+      sqwAlg->setProperty("Method", "NormalisedPolygon");
 
     // S(Q, w) algorithm
     sqwAlg->initialize();
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTab.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTab.cpp
index c9a58d50a270da211997e4603f6579a8543fad58..825811403b4de84430121cc21af57ed0a80b54f8 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTab.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTab.cpp
@@ -394,10 +394,21 @@ namespace CustomInterfaces
     if(!inst)
       throw std::runtime_error("No instrument on workspace");
 
-    if(!inst->hasParameter("efixed-val"))
-      throw std::runtime_error("Instrument has no efixed parameter");
+    // Try to get the parameter form the base instrument
+    if(inst->hasParameter("Efixed"))
+      return inst->getNumberParameter("Efixed")[0];
 
-    return inst->getNumberParameter("efixed-val")[0];
+    // Try to get it form the analyser component
+    if(inst->hasParameter("analyser"))
+    {
+      std::string analyserName = inst->getStringParameter("analyser")[0];
+      auto analyserComp = inst->getComponentByName(analyserName);
+
+      if(analyserComp && analyserComp->hasParameter("Efixed"))
+        return analyserComp->getNumberParameter("Efixed")[0];
+    }
+
+    throw std::runtime_error("Instrument has no efixed parameter");
   }
 
 
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFAddWorkspaceDialog.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFAddWorkspaceDialog.cpp
index 034cd0bc993b04600e697665d0978733c5eea41a..c4bd1f1f3c62f85e240ab1fee44bdfd85d9668cc 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFAddWorkspaceDialog.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFAddWorkspaceDialog.cpp
@@ -16,7 +16,7 @@ namespace MDF
 
 /// Constructor.
 /// @param parent :: A parent widget.
-AddWorkspaceDialog::AddWorkspaceDialog(QWidget *parent):QDialog(parent)
+AddWorkspaceDialog::AddWorkspaceDialog(QWidget *parent):QDialog(parent),m_maxIndex(0)
 {
   m_uiForm.setupUi(this);
   // populate the combo box with names of eligible workspaces
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Muon/ALCBaselineModellingModel.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Muon/ALCBaselineModellingModel.cpp
index 9f6258f7fdaafc872cbb3dbbc6c67db3a7eeb24a..688b5f267c1bff5dde68cbc7b451c8cc9602dc37 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/Muon/ALCBaselineModellingModel.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Muon/ALCBaselineModellingModel.cpp
@@ -40,26 +40,20 @@ namespace CustomInterfaces
     fit->execute();
 
     MatrixWorkspace_sptr fitOutput = fit->getProperty("OutputWorkspace");
+    m_parameterTable = fit->getProperty("OutputParameters");
 
-    IAlgorithm_sptr extract = AlgorithmManager::Instance().create("ExtractSingleSpectrum");
-    extract->setChild(true);
-    extract->setProperty("InputWorkspace", fitOutput);
-    extract->setProperty("WorkspaceIndex", 2);
-    extract->setProperty("OutputWorkspace", "__NotUsed__");
-    extract->execute();
+    enableDisabledPoints(fitOutput,m_data);
 
-    setCorrectedData(extract->getProperty("OutputWorkspace"));
+    setCorrectedData(fitOutput);
     setFittedFunction(funcToFit);
     m_sections = sections;
+
   }
 
   void ALCBaselineModellingModel::setData(MatrixWorkspace_const_sptr data)
   {
     m_data = data;
     emit dataChanged();
-
-    setCorrectedData(MatrixWorkspace_const_sptr());
-    setFittedFunction(IFunction_const_sptr());
   }
 
   /**
@@ -102,45 +96,25 @@ namespace CustomInterfaces
     }
   }
 
-  MatrixWorkspace_sptr ALCBaselineModellingModel::exportWorkspace()
+  /**
+   * Enable points that were disabled for fit
+   * @param destWs :: Workspace to enable points in
+   * @param sourceWs :: Workspace with original errors
+   */
+  void ALCBaselineModellingModel::enableDisabledPoints (MatrixWorkspace_sptr destWs, MatrixWorkspace_const_sptr sourceWs)
   {
-    if ( m_data && m_fittedFunction && m_correctedData ) {
-
-      IAlgorithm_sptr clone = AlgorithmManager::Instance().create("CloneWorkspace");
-      clone->setChild(true);
-      clone->setProperty("InputWorkspace", boost::const_pointer_cast<MatrixWorkspace>(m_data));
-      clone->setProperty("OutputWorkspace", "__NotUsed");
-      clone->execute();
-
-      Workspace_sptr cloneResult = clone->getProperty("OutputWorkspace");
-
-      Workspace_sptr baseline = ALCHelper::createWsFromFunction(m_fittedFunction, m_data->readX(0));
-
-      IAlgorithm_sptr join1 = AlgorithmManager::Instance().create("ConjoinWorkspaces");
-      join1->setChild(true);
-      join1->setProperty("InputWorkspace1", cloneResult);
-      join1->setProperty("InputWorkspace2", baseline);
-      join1->setProperty("CheckOverlapping", false);
-      join1->execute();
-
-      MatrixWorkspace_sptr join1Result = join1->getProperty("InputWorkspace1");
-
-      IAlgorithm_sptr join2 = AlgorithmManager::Instance().create("ConjoinWorkspaces");
-      join2->setChild(true);
-      join2->setProperty("InputWorkspace1", join1Result);
-      join2->setProperty("InputWorkspace2", boost::const_pointer_cast<MatrixWorkspace>(m_correctedData));
-      join2->setProperty("CheckOverlapping", false);
-      join2->execute();
-
-      MatrixWorkspace_sptr result = join2->getProperty("InputWorkspace1");
+    // Unwanted points were disabled by setting their errors to very high values.
+    // We recover here the original errors stored in sourceWs
+    destWs->dataE(0) = sourceWs->readE(0);
+  }
 
-      TextAxis* yAxis = new TextAxis(result->getNumberHistograms());
-      yAxis->setLabel(0,"Data");
-      yAxis->setLabel(1,"Baseline");
-      yAxis->setLabel(2,"Corrected");
-      result->replaceAxis(1,yAxis);
+  MatrixWorkspace_sptr ALCBaselineModellingModel::exportWorkspace()
+  {
+    if ( m_data && m_data->getNumberHistograms() == 3 ) {
 
-      return result;
+      // Export results only if data have been fit, that is,
+      // if m_data has three histograms
+      return boost::const_pointer_cast<MatrixWorkspace>(m_data);
 
     } else {
     
@@ -173,16 +147,9 @@ namespace CustomInterfaces
 
   ITableWorkspace_sptr ALCBaselineModellingModel::exportModel()
   {
-    if ( m_fittedFunction ) {
+    if ( m_parameterTable ) {
 
-      ITableWorkspace_sptr table = WorkspaceFactory::Instance().createTable("TableWorkspace");
-
-      table->addColumn("str", "Function");
-
-      TableRow newRow = table->appendRow();
-      newRow << m_fittedFunction->asString();
-
-      return table;
+      return m_parameterTable;
 
     } else {
       
@@ -192,7 +159,7 @@ namespace CustomInterfaces
 
   void ALCBaselineModellingModel::setCorrectedData(MatrixWorkspace_const_sptr data)
   {
-    m_correctedData = data;
+    m_data = data;
     emit correctedDataChanged();
   }
 
@@ -202,5 +169,29 @@ namespace CustomInterfaces
     emit fittedFunctionChanged();
   }
 
+  MatrixWorkspace_const_sptr ALCBaselineModellingModel::data() const
+  {
+    IAlgorithm_sptr extract = AlgorithmManager::Instance().create("ExtractSingleSpectrum");
+    extract->setChild(true);
+    extract->setProperty("InputWorkspace", boost::const_pointer_cast<MatrixWorkspace>(m_data));
+    extract->setProperty("WorkspaceIndex", 0);
+    extract->setProperty("OutputWorkspace", "__NotUsed__");
+    extract->execute();
+    MatrixWorkspace_const_sptr result = extract->getProperty("OutputWorkspace");
+    return result;
+  }
+
+  MatrixWorkspace_const_sptr ALCBaselineModellingModel::correctedData() const
+  {
+    IAlgorithm_sptr extract = AlgorithmManager::Instance().create("ExtractSingleSpectrum");
+    extract->setChild(true);
+    extract->setProperty("InputWorkspace", boost::const_pointer_cast<MatrixWorkspace>(m_data));
+    extract->setProperty("WorkspaceIndex", 2);
+    extract->setProperty("OutputWorkspace", "__NotUsed__");
+    extract->execute();
+    MatrixWorkspace_const_sptr result = extract->getProperty("OutputWorkspace");
+    return result;
+  }
+
 } // namespace CustomInterfaces
 } // namespace Mantid
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Muon/ALCBaselineModellingPresenter.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Muon/ALCBaselineModellingPresenter.cpp
index 48a33ea5fc180e2d5a53b4051b2bb5afcc20d1e6..b24d160c5f2bff1b65306de641a4c73981667394 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/Muon/ALCBaselineModellingPresenter.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Muon/ALCBaselineModellingPresenter.cpp
@@ -31,7 +31,6 @@ namespace CustomInterfaces
 
     // Model updates
     connect(m_model, SIGNAL(dataChanged()), SLOT(updateDataCurve()));
-    connect(m_model, SIGNAL(dataChanged()), SLOT(clearSections()));
     connect(m_model, SIGNAL(correctedDataChanged()), SLOT(updateCorrectedCurve()));
     connect(m_model, SIGNAL(fittedFunctionChanged()), SLOT(updateFunction()));
     connect(m_model, SIGNAL(fittedFunctionChanged()), SLOT(updateBaselineCurve()));
@@ -210,15 +209,5 @@ namespace CustomInterfaces
     }
   }
 
-  void ALCBaselineModellingPresenter::clearSections()
-  {
-    for (int i = 0; i < m_view->noOfSectionRows(); ++i)
-    {
-      m_view->deleteSectionSelector(i);
-    }
-
-    m_view->setNoOfSectionRows(0);
-  }
-
 } // namespace CustomInterfaces
 } // namespace MantidQt
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Muon/ALCDataLoadingPresenter.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Muon/ALCDataLoadingPresenter.cpp
index a9eee4fe131641d2b8289e3b4273e13f8b229a96..44525f8a6f09b1ebe01568c097f683a630de738e 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/Muon/ALCDataLoadingPresenter.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Muon/ALCDataLoadingPresenter.cpp
@@ -6,6 +6,8 @@
 #include "MantidQtCustomInterfaces/Muon/MuonAnalysisHelper.h"
 #include "MantidQtAPI/AlgorithmInputHistory.h"
 
+#include <Poco/ActiveResult.h>
+
 #include <QApplication>
 #include <QFileInfo>
 #include <QDir>
@@ -87,7 +89,17 @@ namespace CustomInterfaces
       }
 
       alg->setPropertyValue("OutputWorkspace", "__NotUsed");
-      alg->execute();
+
+      // Execute async so we can show progress bar
+      Poco::ActiveResult<bool> result(alg->executeAsync());
+      while( !result.available() )
+      {
+        QCoreApplication::processEvents();
+      }
+      if (!result.error().empty())
+      {
+        throw std::runtime_error(result.error());
+      }
 
       m_loadedData = alg->getProperty("OutputWorkspace");
 
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Muon/ALCPeakFittingModel.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Muon/ALCPeakFittingModel.cpp
index 569e6fb0fa28f291ede7738b0c80c484411788cb..9992b2449240dec3030e6b27a46e97b3140ce8c2 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/Muon/ALCPeakFittingModel.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Muon/ALCPeakFittingModel.cpp
@@ -15,43 +15,13 @@ namespace CustomInterfaces
   {
     m_data = newData;
     emit dataChanged();
-
-    setFittedPeaks(IFunction_const_sptr());
   }
 
   MatrixWorkspace_sptr ALCPeakFittingModel::exportWorkspace()
   {
-    if ( m_data && m_fittedPeaks) {
-
-      // Create a new workspace by cloning data one
-      IAlgorithm_sptr clone = AlgorithmManager::Instance().create("CloneWorkspace");
-      clone->setChild(true); // Don't want workspaces in ADS
-      clone->setProperty("InputWorkspace", boost::const_pointer_cast<MatrixWorkspace>(m_data));
-      clone->setProperty("OutputWorkspace", "__NotUsed");
-      clone->execute();
-
-      Workspace_sptr cloneResult = clone->getProperty("OutputWorkspace");
-
-      // Calculate function values for all data X values
-      MatrixWorkspace_sptr peaks = ALCHelper::createWsFromFunction(m_fittedPeaks, m_data->readX(0));
-
-      // Merge two workspaces
-      IAlgorithm_sptr join = AlgorithmManager::Instance().create("ConjoinWorkspaces");
-      join->setChild(true);
-      join->setProperty("InputWorkspace1", cloneResult);
-      join->setProperty("InputWorkspace2", peaks);
-      join->setProperty("CheckOverlapping", false);
-      join->execute();
-
-      MatrixWorkspace_sptr result = join->getProperty("InputWorkspace1");
+    if ( m_data && m_data->getNumberHistograms() == 3 ) {
 
-      // Update axis lables so that it's understandable what's what on workspace data view / plot
-      TextAxis* yAxis = new TextAxis(result->getNumberHistograms());
-      yAxis->setLabel(0,"Data");
-      yAxis->setLabel(1,"FittedPeaks");
-      result->replaceAxis(1,yAxis);
-
-      return result;
+      return boost::const_pointer_cast<MatrixWorkspace>(m_data);
 
     } else {
     
@@ -61,26 +31,9 @@ namespace CustomInterfaces
 
   ITableWorkspace_sptr ALCPeakFittingModel::exportFittedPeaks()
   {
-    if ( m_fittedPeaks ) {
-
-      ITableWorkspace_sptr table = WorkspaceFactory::Instance().createTable("TableWorkspace");
-
-      table->addColumn("str", "Peaks");
+    if ( m_parameterTable ) {
 
-
-      if (auto composite = boost::dynamic_pointer_cast<CompositeFunction const>(m_fittedPeaks))
-      {
-        for (size_t i = 0; i < composite->nFunctions(); ++i)
-        {
-          static_cast<TableRow>(table->appendRow()) << composite->getFunction(i)->asString();
-        }
-      }
-      else
-      {
-        static_cast<TableRow>(table->appendRow()) << m_fittedPeaks->asString();
-      }
-
-      return table;
+      return m_parameterTable;
 
     } else {
     
@@ -103,6 +56,9 @@ namespace CustomInterfaces
     fit->setProperty("CreateOutput", true);
     fit->execute();
 
+    m_data = fit->getProperty("OutputWorkspace");
+    m_parameterTable = fit->getProperty("OutputParameters");
+
     setFittedPeaks(static_cast<IFunction_sptr>(fit->getProperty("Function")));
   }
 
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/SANSAddFiles.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/SANSAddFiles.cpp
index c700e19be24d442298c6d0bb9f0708f12f96e6a4..105195d6a8b7574d61a048b827994b3a8718d2b5 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/SANSAddFiles.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/SANSAddFiles.cpp
@@ -51,7 +51,7 @@ SANSAddFiles::SANSAddFiles(QWidget *parent, Ui::SANSRunWindow *ParWidgets) :
   m_newOutDir(*this, &SANSAddFiles::changeOutputDir)
 {
   initLayout();
-  
+
   //get lists of suported extentions
   IAlgorithm_sptr alg = AlgorithmManager::Instance().create("Load");
   Property *prop = alg->getProperty("Filename");
@@ -120,6 +120,10 @@ void SANSAddFiles::initLayout()
   setToolTips();
 
   setOutDir(ConfigService::Instance().getString("defaultsave.directory"));
+
+  // Track changes in the selection of the histogram option
+  connect(m_SANSForm->comboBox_histogram_choice, SIGNAL(currentIndexChanged (int)), this, SLOT(onCurrentIndexChangedForHistogramChoice(int)));
+
 }
 /**
  * Restore previous input
@@ -257,11 +261,13 @@ void SANSAddFiles::runPythonAddFiles()
   //there are multiple file list inputs that can be filled in loop through them
   for(int i = 0; i < m_SANSForm->toAdd_List->count(); ++i )
   {
-    const QString filename =
+     QString filename =
       m_SANSForm->toAdd_List->item(i)->data(Qt::WhatsThisRole).toString();
     //allow but do nothing with empty entries
     if ( ! filename.isEmpty() )
     {
+      // Make sure that the file separators are valid
+      filename.replace("\\", "/");
       code_torun += "'"+filename+"',";
     }
   }
@@ -288,14 +294,31 @@ void SANSAddFiles::runPythonAddFiles()
   QString lowMem = m_SANSForm->loadSeparateEntries->isChecked()?"True":"False";
   code_torun += ", lowMem="+lowMem;
 
-  if ( m_SANSForm->takeBinningFromMonitors->isChecked() == false )
-    code_torun += ", binning='" + m_SANSForm->eventToHistBinning->text() + "'";
+  // In case of event data, check if the user either wants 
+  // 0. Custom historgram binning
+  // 1. A binning which is set by the data set
+  // 2. To save the actual event data
+  switch (m_SANSForm->comboBox_histogram_choice->currentIndex())
+  {
+    case 0:
+      code_torun += ", binning='" + m_SANSForm->eventToHistBinning->text() + "'";
+      break;
+    case 1:
+      break;
+    case 2:
+      code_torun += ", saveAsEvent=True";
+      break;
+    default:
+      break;
+  }
+
   code_torun += ")\n";
 
   g_log.debug() << "Executing Python: \n" << code_torun.toStdString() << std::endl;
 
   m_SANSForm->sum_Btn->setEnabled(false);
   m_pythonRunning = true;
+
   //call the algorithms by executing the above script as Python
   QString status = runPythonCode(code_torun, false);
   
@@ -403,5 +426,21 @@ void SANSAddFiles::enableSumming()
   m_SANSForm->sum_Btn->setEnabled(nonEmptyItemsCount > 1);
 }
 
+/**
+ * Reacts to changges of the combo box selection for the histogram options for event data
+ * @param index the new index of the combo box.
+ */
+void SANSAddFiles::onCurrentIndexChangedForHistogramChoice(int index) 
+{
+  if (index == 0)
+  {
+    this->m_SANSForm->eventToHistBinning->setEnabled(true);
+  }
+  else
+  {
+    this->m_SANSForm->eventToHistBinning->setEnabled(false);
+  }
+}
+
 }//namespace CustomInterfaces
 }//namespace MantidQt
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/TomoReconstruction/SavuConfigDialog.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/TomoReconstruction/SavuConfigDialog.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..5d3240b660ff63ad23f382113b0043fc3abe8652
--- /dev/null
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/TomoReconstruction/SavuConfigDialog.cpp
@@ -0,0 +1,485 @@
+#include "MantidQtAPI/AlgorithmInputHistory.h"
+#include "MantidQtAPI/AlgorithmRunner.h"
+#include "MantidQtCustomInterfaces/TomoReconstruction/TomoReconstruction.h"
+
+#include <boost/lexical_cast.hpp>
+
+#include <Poco/String.h>
+
+#include <QFileDialog>
+#include <QMessageBox>
+
+using namespace Mantid::API;
+
+namespace MantidQt {
+namespace CustomInterfaces {
+
+// TODO: what's in this file should become a class of its own,
+// 'SavuConfigDialog' or similar
+
+void TomoReconstruction::loadAvailablePlugins() {
+  // TODO:: load actual plugins when we know them
+  // creating a few relatively realistic choices for now (should crossh check
+  //  with the savu api when finalized).
+  // - Should also verify the param string is valid json when setting
+
+  // Create plugin table
+  Mantid::API::TableRow row = m_availPlugins->appendRow();
+  row << "savu.plugins.timeseries_field_corrections"
+      << "{}"
+      << "Time Series Field Corrections"
+      << "Citation info";
+
+  row = m_availPlugins->appendRow();
+  row << "savu.plugins.median_filter"
+      << "{\"kernel_size\":[1, 3, 3]}"
+      << "Median Filter"
+      << "Citation info";
+
+  row = m_availPlugins->appendRow();
+  row << "savu.plugins.vo_centering"
+      << "{}"
+      << "Vo Centering"
+      << "Citation info";
+
+  row = m_availPlugins->appendRow();
+  row << "savu.plugins.simple_recon"
+      << "{\"center_of_rotation\":86}"
+      << "Simple Reconstruction"
+      << "Citation info";
+
+  row = m_availPlugins->appendRow();
+  row << "savu.plugins.astra_recon"
+      << "{\"center_of_rotation\":\"86\", "
+         "\"reconsturction_type\":\"SIRT\", \"number_of_iterations\":5}"
+      << "Simple Reconstruction"
+      << "Citation info";
+
+  // Update the UI
+  refreshAvailablePluginListUI();
+}
+
+// Reloads the GUI list of available plugins from the data object ::
+// Populating only through this ensures correct indexing.
+void TomoReconstruction::refreshAvailablePluginListUI() {
+  // Table WS structure, id/params/name/cite
+  m_uiSavu.listAvailablePlugins->clear();
+  for (size_t i = 0; i < m_availPlugins->rowCount(); ++i) {
+    QString str =
+        QString::fromStdString(m_availPlugins->cell<std::string>(i, 2));
+    m_uiSavu.listAvailablePlugins->addItem(str);
+  }
+}
+
+// Reloads the GUI list of current plugins from the data object ::
+// Populating only through this ensures correct indexing.
+void TomoReconstruction::refreshCurrentPluginListUI() {
+  // Table WS structure, id/params/name/cite
+  m_uiSavu.treeCurrentPlugins->clear();
+  createPluginTreeEntries(m_currPlugins);
+}
+
+// Updates the selected plugin info from Available plugins list.
+void TomoReconstruction::availablePluginSelected() {
+  if (m_uiSavu.listAvailablePlugins->selectedItems().count() != 0) {
+    size_t idx = static_cast<size_t>(
+        m_uiSavu.listAvailablePlugins->currentIndex().row());
+    if (idx < m_availPlugins->rowCount()) {
+      m_uiSavu.availablePluginDesc->setText(
+          tableWSRowToString(m_availPlugins, idx));
+    }
+  }
+}
+
+// Updates the selected plugin info from Current plugins list.
+void TomoReconstruction::currentPluginSelected() {
+  if (m_uiSavu.treeCurrentPlugins->selectedItems().count() != 0) {
+    auto currItem = m_uiSavu.treeCurrentPlugins->selectedItems()[0];
+
+    while (currItem->parent() != NULL)
+      currItem = currItem->parent();
+
+    int topLevelIndex =
+        m_uiSavu.treeCurrentPlugins->indexOfTopLevelItem(currItem);
+
+    m_uiSavu.currentPluginDesc->setText(
+        tableWSRowToString(m_currPlugins, topLevelIndex));
+  }
+}
+
+class OwnTreeWidgetItem : public QTreeWidgetItem {
+public:
+  OwnTreeWidgetItem(QTreeWidgetItem *parent,
+                    QTreeWidgetItem *logicalParent = NULL,
+                    const std::string &key = "")
+      : QTreeWidgetItem(parent), m_rootParent(logicalParent), m_key(key) {}
+
+  OwnTreeWidgetItem(QStringList list, QTreeWidgetItem *logicalParent = NULL,
+                    const std::string &key = "")
+      : QTreeWidgetItem(list), m_rootParent(logicalParent), m_key(key) {}
+
+  OwnTreeWidgetItem(QTreeWidgetItem *parent, QStringList list,
+                    QTreeWidgetItem *logicalParent = NULL,
+                    const std::string &key = "")
+      : QTreeWidgetItem(parent, list), m_rootParent(logicalParent), m_key(key) {
+  }
+
+  QTreeWidgetItem *getRootParent() { return m_rootParent; }
+
+  std::string getKey() { return m_key; }
+
+private:
+  QTreeWidgetItem *m_rootParent;
+  std::string m_key;
+};
+
+// On user editing a parameter tree item, update the data object to match.
+void TomoReconstruction::paramValModified(QTreeWidgetItem *item,
+                                          int /*column*/) {
+  OwnTreeWidgetItem *ownItem = dynamic_cast<OwnTreeWidgetItem *>(item);
+  if (!ownItem)
+    return;
+
+  int topLevelIndex = -1;
+  if (ownItem->getRootParent() != NULL) {
+    topLevelIndex = m_uiSavu.treeCurrentPlugins->indexOfTopLevelItem(
+        ownItem->getRootParent());
+  }
+  if (-1 == topLevelIndex)
+    return;
+
+  // Recreate the json string from the nodes and write back
+  std::string json = m_currPlugins->cell<std::string>(topLevelIndex, 1);
+  // potential new line out, and trim spaces
+  json.erase(std::remove(json.begin(), json.end(), '\n'), json.end());
+  json.erase(std::remove(json.begin(), json.end(), '\r'), json.end());
+  json = Poco::trimInPlace(json);
+
+  ::Json::Reader r;
+  ::Json::Value root;
+  if (r.parse(json, root)) {
+    // Look for the key and replace it
+    root[ownItem->getKey()] = ownItem->text(0).toStdString();
+  }
+
+  m_currPlugins->cell<std::string>(topLevelIndex, 1) =
+      ::Json::FastWriter().write(root);
+  currentPluginSelected();
+}
+
+// When a top level item is expanded, also expand its child items - if tree
+// items
+void TomoReconstruction::expandedItem(QTreeWidgetItem *item) {
+  if (item->parent() == NULL) {
+    for (int i = 0; i < item->childCount(); ++i) {
+      item->child(i)->setExpanded(true);
+    }
+  }
+}
+
+// Adds one plugin from the available plugins list into the list of
+// current plugins
+void TomoReconstruction::transferClicked() {
+  if (0 == m_uiSavu.listAvailablePlugins->selectedItems().count())
+    return;
+
+  int idx = m_uiSavu.listAvailablePlugins->currentIndex().row();
+  Mantid::API::TableRow row = m_currPlugins->appendRow();
+  for (size_t j = 0; j < m_currPlugins->columnCount(); ++j) {
+    row << m_availPlugins->cell<std::string>(idx, j);
+  }
+  createPluginTreeEntry(row);
+}
+
+void TomoReconstruction::moveUpClicked() {
+  if (0 == m_uiSavu.treeCurrentPlugins->selectedItems().count())
+    return;
+
+  size_t idx =
+      static_cast<size_t>(m_uiSavu.treeCurrentPlugins->currentIndex().row());
+  if (idx > 0 && idx < m_currPlugins->rowCount()) {
+    // swap row, all columns
+    for (size_t j = 0; j < m_currPlugins->columnCount(); ++j) {
+      std::string swap = m_currPlugins->cell<std::string>(idx, j);
+      m_currPlugins->cell<std::string>(idx, j) =
+          m_currPlugins->cell<std::string>(idx - 1, j);
+      m_currPlugins->cell<std::string>(idx - 1, j) = swap;
+    }
+    refreshCurrentPluginListUI();
+  }
+}
+
+void TomoReconstruction::moveDownClicked() {
+  // TODO: this can be done with the same function as above...
+  if (0 == m_uiSavu.treeCurrentPlugins->selectedItems().count())
+    return;
+
+  size_t idx =
+      static_cast<size_t>(m_uiSavu.treeCurrentPlugins->currentIndex().row());
+  if (idx < m_currPlugins->rowCount() - 1) {
+    // swap all columns
+    for (size_t j = 0; j < m_currPlugins->columnCount(); ++j) {
+      std::string swap = m_currPlugins->cell<std::string>(idx, j);
+      m_currPlugins->cell<std::string>(idx, j) =
+          m_currPlugins->cell<std::string>(idx + 1, j);
+      m_currPlugins->cell<std::string>(idx + 1, j) = swap;
+    }
+    refreshCurrentPluginListUI();
+  }
+}
+
+void TomoReconstruction::removeClicked() {
+  // Also clear ADS entries
+  if (0 == m_uiSavu.treeCurrentPlugins->selectedItems().count())
+    return;
+
+  int idx = m_uiSavu.treeCurrentPlugins->currentIndex().row();
+  m_currPlugins->removeRow(idx);
+
+  refreshCurrentPluginListUI();
+}
+
+void TomoReconstruction::menuOpenClicked() {
+  QString s =
+      QFileDialog::getOpenFileName(0, "Open file", QDir::currentPath(),
+                                   "NeXus files (*.nxs);;All files (*.*)",
+                                   new QString("NeXus files (*.nxs)"));
+  std::string name = s.toStdString();
+
+  if ("" == name)
+    return;
+
+  bool opening = true;
+  if (m_currPlugins->rowCount() > 0) {
+    QMessageBox::StandardButton reply = QMessageBox::question(
+        this, "Open file confirmation",
+        "Opening the configuration file will clear the current list."
+        "\nWould you like to continue?",
+        QMessageBox::Yes | QMessageBox::No);
+    if (reply == QMessageBox::No) {
+      opening = false;
+    }
+  }
+
+  if (opening) {
+    loadSavuTomoConfig(name, m_currPlugins);
+
+    m_currentParamPath = name;
+    refreshCurrentPluginListUI();
+  }
+}
+
+void TomoReconstruction::menuSaveClicked() {
+  if (m_currentParamPath == "") {
+    menuSaveAsClicked();
+    return;
+  }
+
+  if (0 == m_currPlugins->rowCount()) {
+    // Alert that the plugin list is empty
+    QMessageBox::information(this, tr("Unable to save file"),
+                             "The current plugin list is empty, please add one "
+                             "or more to the list.");
+  } else {
+    AnalysisDataService::Instance().add(createUniqueNameHidden(),
+                                        m_currPlugins);
+    std::string csvWorkspaceNames = m_currPlugins->name();
+
+    auto alg = Algorithm::fromString("SaveTomoConfig");
+    alg->initialize();
+    alg->setPropertyValue("Filename", m_currentParamPath);
+    alg->setPropertyValue("InputWorkspaces", csvWorkspaceNames);
+    alg->execute();
+
+    if (!alg->isExecuted()) {
+      throw std::runtime_error("Error when trying to save config file");
+    }
+  }
+}
+
+void TomoReconstruction::menuSaveAsClicked() {
+  QString s =
+      QFileDialog::getSaveFileName(0, "Save file", QDir::currentPath(),
+                                   "NeXus files (*.nxs);;All files (*.*)",
+                                   new QString("NeXus files (*.nxs)"));
+  std::string name = s.toStdString();
+  if ("" == name)
+    return;
+
+  m_currentParamPath = name;
+  menuSaveClicked();
+}
+
+QString TomoReconstruction::tableWSRowToString(ITableWorkspace_sptr table,
+                                               size_t i) {
+  std::stringstream msg;
+  msg << "ID: " << table->cell<std::string>(i, 0) << std::endl
+      << "Params: " << table->cell<std::string>(i, 1) << std::endl
+      << "Name: " << table->cell<std::string>(i, 2) << std::endl
+      << "Cite: " << table->cell<std::string>(i, 3);
+  return QString::fromStdString(msg.str());
+}
+
+/**
+ * Creates a treewidget item for a row of a table workspace.
+ *
+ * @param row Row from a table workspace with each row specfying a savu plugin
+ */
+void TomoReconstruction::createPluginTreeEntry(TableRow &row) {
+  QStringList idStr, nameStr, citeStr, paramsStr;
+  idStr.push_back(QString::fromStdString("ID: " + row.cell<std::string>(0)));
+  nameStr.push_back(
+      QString::fromStdString("Name: " + row.cell<std::string>(2)));
+  citeStr.push_back(
+      QString::fromStdString("Cite: " + row.cell<std::string>(3)));
+  paramsStr.push_back(QString::fromStdString("Params:"));
+
+  // Setup editable tree items
+  QList<QTreeWidgetItem *> items;
+  OwnTreeWidgetItem *pluginBaseItem = new OwnTreeWidgetItem(nameStr);
+  OwnTreeWidgetItem *pluginParamsItem =
+      new OwnTreeWidgetItem(pluginBaseItem, paramsStr, pluginBaseItem);
+
+  // Add to the tree list. Adding now to build hierarchy for later setItemWidget
+  // call
+  items.push_back(new OwnTreeWidgetItem(pluginBaseItem, idStr, pluginBaseItem));
+  items.push_back(
+      new OwnTreeWidgetItem(pluginBaseItem, nameStr, pluginBaseItem));
+  items.push_back(
+      new OwnTreeWidgetItem(pluginBaseItem, citeStr, pluginBaseItem));
+  items.push_back(pluginParamsItem);
+
+  // Params will be a json string which needs splitting into child tree items
+  // [key/value]
+  ::Json::Value root;
+  std::string paramString = row.cell<std::string>(1);
+  ::Json::Reader r;
+  if (r.parse(paramString, root)) {
+    auto members = root.getMemberNames();
+    for (auto it = members.begin(); it != members.end(); ++it) {
+      OwnTreeWidgetItem *container =
+          new OwnTreeWidgetItem(pluginParamsItem, pluginBaseItem);
+
+      QWidget *w = new QWidget();
+      w->setAutoFillBackground(true);
+
+      QHBoxLayout *layout = new QHBoxLayout(w);
+      layout->setMargin(1);
+      QLabel *label1 = new QLabel(QString::fromStdString((*it) + ": "));
+
+      QTreeWidget *paramContainerTree = new QTreeWidget(w);
+      connect(paramContainerTree, SIGNAL(itemChanged(QTreeWidgetItem *, int)),
+              this, SLOT(paramValModified(QTreeWidgetItem *, int)));
+      paramContainerTree->setHeaderHidden(true);
+      paramContainerTree->setIndentation(0);
+
+      auto jsonVal = root.get(*it, "");
+      std::string valStr = pluginParamValString(jsonVal, *it);
+
+      QStringList paramVal(QString::fromStdString(valStr));
+      OwnTreeWidgetItem *paramValueItem =
+          new OwnTreeWidgetItem(paramVal, pluginBaseItem, *it);
+      paramValueItem->setFlags(Qt::ItemIsEditable | Qt::ItemIsEnabled);
+
+      paramContainerTree->addTopLevelItem(paramValueItem);
+      QRect rect = paramContainerTree->visualItemRect(paramValueItem);
+      paramContainerTree->setMaximumHeight(rect.height());
+      paramContainerTree->setFrameShape(QFrame::NoFrame);
+
+      layout->addWidget(label1);
+      layout->addWidget(paramContainerTree);
+
+      pluginParamsItem->addChild(container);
+      m_uiSavu.treeCurrentPlugins->setItemWidget(container, 0, w);
+    }
+  }
+
+  pluginBaseItem->addChildren(items);
+  m_uiSavu.treeCurrentPlugins->addTopLevelItem(pluginBaseItem);
+}
+
+/**
+ * This is a kind of .asString() method for arrays. It iterates
+ * through the array elements and builds the string enclosed by [].
+ *
+ * @param jsonVal Value of a parameter that seems to be an array
+ *(isArray()==true)
+ * @param name Name of the parameter (to give informative messages)
+ *
+ * @return String with a parameter value(s), enclosed by [] and
+ * separated by commas
+ */
+std::string
+TomoReconstruction::paramValStringFromArray(const Json::Value &jsonVal,
+                                            const std::string &name) {
+  std::string s;
+  s = "[";
+  for (Json::ArrayIndex i = 0; i < jsonVal.size(); ++i) {
+    if (jsonVal[i].isArray()) {
+      userWarning(
+          "Could not recognize parameter value in list/array",
+          "The value of parameter '" + name +
+              "' could not be interpreted "
+              "as a string. It does not seem to be well formed or supported. "
+              "For example, parameter values given as lists of lists are not "
+              "supported.");
+    } else {
+      try {
+        s += jsonVal[i].asString() + " ,";
+      } catch (std::exception &e) {
+        userWarning(
+            "Could not recognize value in list/array of values",
+            "The " + boost::lexical_cast<std::string>(i) +
+                "-th value of the list/array could not be interpreted "
+                "as a text string. It will be empty in the list of current "
+                "plugins. You can still edit it. Error details: " +
+                std::string(e.what()));
+      }
+    }
+  }
+  // this could be s.back() with C++11
+  s[s.length() - 1] = ']'; // and last comma becomes closing ]
+  return s;
+}
+
+/**
+ * Build a string with the value of a parameter in a json
+ * string. Works for scalar and list/array values.
+ *
+ * @param jsonVal Value of a parameter that seems to be an array
+ * @param name Name of the parameter (to give informative messages)
+ *
+ * @return String with a parameter value
+ */
+std::string TomoReconstruction::pluginParamValString(const Json::Value &jsonVal,
+                                                     const std::string &name) {
+  std::string s;
+  // string and numeric values can (normally) be converted to string but arrays
+  // cannot
+  if (!jsonVal.isArray()) {
+    try {
+      s = jsonVal.asString();
+    } catch (std::exception &e) {
+      userWarning(
+          "Could not recognize parameter value",
+          "The value of parameter '" + name +
+              "' could not be interpreted "
+              "as a string. It will be empty in the list of current plugins. "
+              "You can still edit it. Error details: " +
+              std::string(e.what()));
+    }
+  } else {
+    s = paramValStringFromArray(jsonVal, name);
+  }
+  return s;
+}
+
+void TomoReconstruction::createPluginTreeEntries(ITableWorkspace_sptr table) {
+  for (size_t i = 0; i < table->rowCount(); ++i) {
+    TableRow r = table->getRow(i);
+    createPluginTreeEntry(r);
+  }
+}
+
+} // namespace CustomInterfaces
+} // namespace MantidQt
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/TomoReconstruction/TomoReconstruction.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/TomoReconstruction/TomoReconstruction.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..77ef25b865853ae98edd1c20edebb8227a27df4a
--- /dev/null
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/TomoReconstruction/TomoReconstruction.cpp
@@ -0,0 +1,1535 @@
+#include "MantidAPI/TableRow.h"
+#include "MantidKernel/ConfigService.h"
+#include "MantidKernel/FacilityInfo.h"
+#include "MantidKernel/RemoteJobManager.h"
+#include "MantidQtAPI/AlgorithmInputHistory.h"
+#include "MantidQtAPI/AlgorithmRunner.h"
+#include "MantidQtAPI/HelpWindow.h"
+#include "MantidQtCustomInterfaces/TomoReconstruction/TomoReconstruction.h"
+#include "MantidQtCustomInterfaces/TomoReconstruction/ToolSettings.h"
+
+#include <boost/lexical_cast.hpp>
+
+#include <QElapsedTimer>
+#include <QFileDialog>
+#include <QMessageBox>
+#include <QPainter>
+#include <QSettings>
+#include <QThread>
+#include <QTimer>
+
+using namespace Mantid::API;
+using namespace MantidQt::CustomInterfaces;
+
+namespace MantidQt {
+namespace CustomInterfaces {
+
+// Add this class to the list of specialised dialogs in this namespace
+DECLARE_SUBWINDOW(TomoReconstruction)
+
+namespace {
+Mantid::Kernel::Logger g_log("TomoReconstruction");
+}
+
+size_t TomoReconstruction::g_nameSeqNo = 0;
+
+// names by which we know compute resourcess
+const std::string TomoReconstruction::g_SCARFName = "SCARF@STFC";
+
+// names by which we know image/tomography reconstruction tools (3rd party)
+const std::string TomoReconstruction::g_TomoPyTool = "TomoPy";
+const std::string TomoReconstruction::g_AstraTool = "Astra";
+const std::string TomoReconstruction::g_CCPiTool = "CCPi CGLS";
+const std::string TomoReconstruction::g_SavuTool = "Savu";
+const std::string TomoReconstruction::g_CustomCmdTool = "Custom command";
+const std::string TomoReconstruction::g_defOutPath = "/work/imat/runs_output";
+
+/**
+ * Almost default constructor, but note that this interface currently
+ * relies on the SCARF cluster (only in ISIS facility) as the only
+ * supported remote compute resource.
+ *
+ * @param parent Parent window (most likely the Mantid main app window).
+ */
+TomoReconstruction::TomoReconstruction(QWidget *parent)
+    : UserSubWindow(parent), m_loggedIn(false), m_facility("ISIS"),
+      m_computeRes(), m_localCompName("Local"), m_SCARFtools(),
+      m_pathSCARFbase("/work/imat/recon/"),
+      m_pathFITS(m_pathSCARFbase + "data/fits"),
+      m_pathFlat(m_pathSCARFbase + "data/flat"),
+      m_pathDark(m_pathSCARFbase + "data/dark"), m_currentParamPath(),
+      m_settingsGroup("CustomInterfaces/TomoReconstruction"),
+      m_keepAliveTimer(NULL), m_keepAliveThread(NULL) {
+
+  m_computeRes.push_back(g_SCARFName);
+
+  m_SCARFtools.push_back(g_TomoPyTool);
+  m_SCARFtools.push_back(g_AstraTool);
+  m_SCARFtools.push_back(g_CCPiTool);
+  m_SCARFtools.push_back(g_SavuTool);
+  m_SCARFtools.push_back(g_CustomCmdTool);
+
+  m_availPlugins = Mantid::API::WorkspaceFactory::Instance().createTable();
+  m_availPlugins->addColumns("str", "name", 4);
+  m_currPlugins = Mantid::API::WorkspaceFactory::Instance().createTable();
+  m_currPlugins->addColumns("str", "name", 4);
+}
+
+TomoReconstruction::~TomoReconstruction() {
+  cleanup();
+  delete m_keepAliveTimer;
+  delete m_keepAliveThread;
+}
+
+/**
+ * Close open sessions, kill timers/threads etc., save settings, etc. for a
+ * graceful window close/destruct
+ */
+void TomoReconstruction::cleanup() {
+  killKeepAliveMechanism();
+
+  saveSettings();
+
+  // be tidy and always log out if we're in.
+  if (m_loggedIn)
+    SCARFLogoutClicked();
+}
+
+void TomoReconstruction::doSetupSectionParameters() {
+  // TODO: should split the tabs out into their own files?
+
+  // geometry, etc. niceties
+  // on the left (just plugin names) 1/2, right: 2/3
+  QList<int> sizes;
+  sizes.push_back(100);
+  sizes.push_back(200);
+  m_uiSavu.splitterPlugins->setSizes(sizes);
+
+  // Setup Parameter editor tab
+  loadAvailablePlugins();
+  m_uiSavu.treeCurrentPlugins->setHeaderHidden(true);
+
+  // Lists/trees
+  connect(m_uiSavu.listAvailablePlugins, SIGNAL(itemSelectionChanged()), this,
+          SLOT(availablePluginSelected()));
+  connect(m_uiSavu.treeCurrentPlugins, SIGNAL(itemSelectionChanged()), this,
+          SLOT(currentPluginSelected()));
+  connect(m_uiSavu.treeCurrentPlugins, SIGNAL(itemExpanded(QTreeWidgetItem *)),
+          this, SLOT(expandedItem(QTreeWidgetItem *)));
+
+  // Buttons
+  connect(m_uiSavu.btnTransfer, SIGNAL(released()), this,
+          SLOT(transferClicked()));
+  connect(m_uiSavu.btnMoveUp, SIGNAL(released()), this, SLOT(moveUpClicked()));
+  connect(m_uiSavu.btnMoveDown, SIGNAL(released()), this,
+          SLOT(moveDownClicked()));
+  connect(m_uiSavu.btnRemove, SIGNAL(released()), this, SLOT(removeClicked()));
+
+  // Connect slots
+  // Menu Items
+  connect(m_ui.actionOpen, SIGNAL(triggered()), this, SLOT(menuOpenClicked()));
+  connect(m_ui.actionSave, SIGNAL(triggered()), this, SLOT(menuSaveClicked()));
+  connect(m_ui.actionSaveAs, SIGNAL(triggered()), this,
+          SLOT(menuSaveAsClicked()));
+}
+
+void TomoReconstruction::doSetupSectionSetup() {
+  // disable 'local' for now
+  m_ui.tabWidget_comp_resource->setTabEnabled(false, 1);
+  m_ui.tab_local->setEnabled(false);
+
+  m_ui.groupBox_run_config->setEnabled(false);
+
+  connect(m_ui.pushButton_SCARF_login, SIGNAL(released()), this,
+          SLOT(SCARFLoginClicked()));
+  connect(m_ui.pushButton_SCARF_logout, SIGNAL(released()), this,
+          SLOT(SCARFLogoutClicked()));
+
+  // 'browse' buttons
+  connect(m_ui.pushButton_fits_dir, SIGNAL(released()), this,
+          SLOT(fitsPathBrowseClicked()));
+  connect(m_ui.pushButton_flat_dir, SIGNAL(released()), this,
+          SLOT(flatPathBrowseClicked()));
+  connect(m_ui.pushButton_dark_dir, SIGNAL(released()), this,
+          SLOT(darkPathBrowseClicked()));
+}
+
+void TomoReconstruction::doSetupSectionRun() {
+  // geometry, etc. niceties
+  // on the left (just plugin names) 1/2, right: 2/3
+  QList<int> sizes;
+  sizes.push_back(420);
+  sizes.push_back(80);
+  m_ui.splitter_run_main_vertical->setSizes(sizes);
+
+  sizes[0] = 470;
+  sizes[1] = 30;
+  m_ui.splitter_image_resource->setSizes(sizes);
+
+  sizes[0] = 400;
+  sizes[1] = 100;
+  m_ui.splitter_run_jobs->setSizes(sizes);
+
+  m_ui.label_image_name->setText("none");
+
+  m_ui.pushButton_reconstruct->setEnabled(false);
+  m_ui.pushButton_run_tool_setup->setEnabled(false);
+  m_ui.pushButton_run_job_cancel->setEnabled(false);
+  m_ui.pushButton_run_job_visualize->setEnabled(false);
+
+  try {
+    setupComputeResource();
+    setupRunTool();
+  } catch (std::runtime_error &e) {
+    g_log.error() << "Failed to initialize remote compute resource(s). This "
+                     "custom interface will not work. Error description: "
+                  << e.what() << std::endl;
+  }
+
+  enableLoggedActions(m_loggedIn);
+
+  // Button signals
+  connect(m_ui.pushButton_browse_image, SIGNAL(released()), this,
+          SLOT(browseImageClicked()));
+  connect(m_ui.pushButton_reconstruct, SIGNAL(released()), this,
+          SLOT(reconstructClicked()));
+  connect(m_ui.pushButton_run_tool_setup, SIGNAL(released()), this,
+          SLOT(toolSetupClicked()));
+  connect(m_ui.pushButton_run_refresh, SIGNAL(released()), this,
+          SLOT(jobTableRefreshClicked()));
+  connect(m_ui.pushButton_run_job_visualize, SIGNAL(released()), this,
+          SLOT(runVisualizeClicked()));
+  connect(m_ui.pushButton_run_job_cancel, SIGNAL(released()), this,
+          SLOT(jobCancelClicked()));
+
+  // update tools for a resource
+  connect(m_ui.comboBox_run_compute_resource, SIGNAL(currentIndexChanged(int)),
+          this, SLOT(compResourceIndexChanged(int)));
+
+  connect(m_ui.comboBox_run_tool, SIGNAL(currentIndexChanged(int)), this,
+          SLOT(runToolIndexChanged(int)));
+
+  m_ui.pushButton_reconstruct->setEnabled(false);
+  m_ui.pushButton_run_tool_setup->setEnabled(true);
+  m_ui.pushButton_run_job_cancel->setEnabled(false);
+  m_ui.pushButton_run_job_visualize->setEnabled(false);
+}
+
+void TomoReconstruction::doSetupGeneralWidgets() {
+  connect(m_ui.pushButton_help, SIGNAL(released()), this, SLOT(openHelpWin()));
+  // note connection to the parent window, otherwise you'll be left
+  // with an empty frame window
+  connect(m_ui.pushButton_close, SIGNAL(released()), this->parent(),
+          SLOT(close()));
+}
+
+void TomoReconstruction::initLayout() {
+  m_ui.setupUi(this);
+
+  readSettings();
+
+  doSetupGeneralWidgets();
+  doSetupSectionSetup();
+  doSetupSectionRun();
+}
+
+/**
+ * Enables/disables buttons that require the user to be logged into
+ * the (remote) compute resource, for example: reconstruct (submit job),
+ * cancel job, etc.
+ */
+void TomoReconstruction::enableLoggedActions(bool enable) {
+  // TODO: this may not make sense anymore when/if the "Local" compute
+  // resource is used in the future (except when none of the tools
+  // supported are available/detected on "Local")
+  std::vector<QPushButton *> buttons;
+  buttons.push_back(m_ui.pushButton_run_refresh);
+  buttons.push_back(m_ui.pushButton_run_job_cancel);
+  // no visualization yet, need vsi etc. support
+  // buttons.push_back(m_ui.pushButton_run_job_visualize);
+  buttons.push_back(m_ui.pushButton_reconstruct);
+
+  for (size_t i = 0; i < buttons.size(); ++i) {
+    buttons[i]->setEnabled(enable);
+  }
+
+  if (!enable) {
+    m_ui.pushButton_reconstruct->setToolTip(
+        "Start reconstruction job. You need to be logged in to use this");
+  } else {
+    m_ui.pushButton_reconstruct->setToolTip("");
+  }
+}
+
+/**
+ * Handle display of the current status of the remote/local compute resource
+ * that is selected by the user.
+ *
+ * @param online whether to show good/working/online status
+ */
+void TomoReconstruction::updateCompResourceStatus(bool online) {
+  const std::string res = getComputeResource();
+  if (res == g_SCARFName) {
+    if (online)
+      m_ui.pushButton_remote_status->setText("Online");
+    else
+      m_ui.pushButton_remote_status->setText("Offline");
+  } else if (res == m_localCompName) {
+    if (online)
+      m_ui.pushButton_remote_status->setText("Tools available");
+    else
+      m_ui.pushButton_remote_status->setText("No tools available!");
+  }
+}
+
+void TomoReconstruction::SCARFLoginClicked() {
+  try {
+    doLogin(getPassword());
+    m_loggedIn = true;
+  } catch (std::exception &e) {
+    throw(std::string("Problem when logging in. Error description: ") +
+          e.what());
+  }
+
+  try {
+    jobTableRefreshClicked();
+  } catch (std::exception &e) {
+    throw(std::string("The login operation went apparently fine but an issue "
+                      "was found while trying to retrieve the status of the "
+                      "jobs currently running on the remote resource. Error "
+                      "description: ") +
+          e.what());
+  }
+
+  enableLoggedActions(true);
+  updateCompResourceStatus(true);
+
+  m_ui.pushButton_SCARF_login->setEnabled(false);
+  m_ui.pushButton_SCARF_logout->setEnabled(true);
+
+  int kat = m_settings.useKeepAlive;
+  if (kat > 0) {
+    g_log.notice()
+        << "Reconstruction GUI: starting mechanism to periodically query the "
+           "status of jobs. This will update the status of running jobs every "
+        << kat << " seconds. You can also update it at any moment by clicking "
+                  "on the refresh button. This periodic update mechanism is "
+                  "also expected to keep sessions on remote compute resources "
+                  "alive after logging in." << std::endl;
+    startKeepAliveMechanism(kat);
+  }
+}
+
+void TomoReconstruction::SCARFLogoutClicked() {
+  try {
+    doLogout();
+  } catch (std::exception &e) {
+    throw(std::string("Problem when logging out. Error description: ") +
+          e.what());
+  }
+
+  enableLoggedActions(false);
+  m_loggedIn = false;
+
+  m_ui.pushButton_SCARF_login->setEnabled(true);
+  m_ui.pushButton_SCARF_logout->setEnabled(false);
+}
+
+/**
+ * Load the settings for the tabs and widgets of the interface. This
+ * relies on Qt settings functionality (QSettings class).
+ *
+ * This includes setting the default browsing directory to be the
+ * default save directory.
+ */
+void TomoReconstruction::readSettings() {
+  QSettings qs;
+  qs.beginGroup(QString::fromStdString(m_settingsGroup));
+
+  m_settings.SCARFBasePath =
+      qs.value("SCARF-base-path",
+               QString::fromStdString(m_settings.SCARFBasePath))
+          .toString()
+          .toStdString();
+  // WARNING: it's critical to keep 'false' as default value, otherwise
+  // scripted runs may have issues. The CI builds could get stuck when
+  // closing this interface.
+  m_settings.onCloseAskForConfirmation =
+      qs.value("on-close-ask-for-confirmation", false).toBool();
+
+  m_settings.useKeepAlive =
+      qs.value("use-keep-alive", m_settings.useKeepAlive).toInt();
+  restoreGeometry(qs.value("interface-win-geometry").toByteArray());
+  qs.endGroup();
+
+  m_ui.lineEdit_SCARF_path->setText(
+      QString::fromStdString(m_settings.SCARFBasePath));
+}
+
+/**
+ * Save persistent settings. Qt based.
+ */
+void TomoReconstruction::saveSettings() {
+  QSettings qs;
+  qs.beginGroup(QString::fromStdString(m_settingsGroup));
+  QString s = m_ui.lineEdit_SCARF_path->text();
+  qs.setValue("SCARF-base-path", s);
+  qs.setValue("on-close-ask-for-confirmation",
+              m_settings.onCloseAskForConfirmation);
+  qs.setValue("use-keep-alive", m_settings.useKeepAlive);
+  qs.setValue("interface-win-geometry", saveGeometry());
+  qs.endGroup();
+}
+
+/**
+ * Load a savu tomo config file into the current plugin list, overwriting it.
+ * Uses the algorithm LoadSavuTomoConfig
+ */
+void TomoReconstruction::loadSavuTomoConfig(
+    std::string &filePath, Mantid::API::ITableWorkspace_sptr &currentPlugins) {
+  // try to load tomo reconstruction parametereization file
+  auto alg = Algorithm::fromString("LoadSavuTomoConfig");
+  alg->initialize();
+  alg->setPropertyValue("Filename", filePath);
+  alg->setPropertyValue("OutputWorkspace", createUniqueNameHidden());
+  try {
+    alg->execute();
+  } catch (std::runtime_error &e) {
+    throw std::runtime_error(
+        std::string("Error when trying to load tomographic reconstruction "
+                    "parameter file: ") +
+        e.what());
+  }
+
+  // new processing plugins list
+  try {
+    currentPlugins = alg->getProperty("OutputWorkspace");
+  } catch (std::exception &e) {
+    userError("Could not load config file", "Failed to load the file "
+                                            "with the following error: " +
+                                                std::string(e.what()));
+  }
+}
+
+// Build a unique (and hidden) name for the table ws
+std::string TomoReconstruction::createUniqueNameHidden() {
+  std::string name;
+  do {
+    // with __ prefix => hidden
+    name = "__TomoConfigTableWS_Seq_" +
+           boost::lexical_cast<std::string>(g_nameSeqNo++);
+  } while (AnalysisDataService::Instance().doesExist(name));
+
+  return name;
+}
+
+/**
+ * Sets the compute resource that will be used to run reconstruction
+ * jobs. It checks that the facility and compute resource are fine
+ * (the one expected). Otherwise, shows an error and not much can be
+ * done.
+ */
+void TomoReconstruction::setupComputeResource() {
+  // set up the compute resource
+  QComboBox *cr = m_ui.comboBox_run_compute_resource;
+  if (cr) {
+    cr->clear();
+
+    const Mantid::Kernel::FacilityInfo &fac =
+        Mantid::Kernel::ConfigService::Instance().getFacility();
+    if (fac.name() != m_facility) {
+      g_log.error()
+          << "Facility not supported. This interface is designed "
+             "to be used at " +
+                 m_facility +
+                 ". You will probably not be able to use it in a useful way "
+                 "because your facility is " +
+                 fac.name() +
+                 ". If you have set that facility by mistake in your settings, "
+                 "please update it." << std::endl;
+      throw std::runtime_error(
+          "Failed to initialize because the facility is  " + fac.name() +
+          " (and not " + m_facility + ").");
+    }
+
+    if (m_computeRes.size() < 1) {
+      userWarning("No remote compute resource set!",
+                  "No remote compute "
+                  "resource has been set. Please note that without a "
+                  "remote compute resource the functionality of this "
+                  "interface might be limited.");
+    } else {
+      // assume the present reality: just SCARF
+      const std::string &required = m_computeRes.front();
+      std::vector<std::string> res = Mantid::Kernel::ConfigService::Instance()
+                                         .getFacility()
+                                         .computeResources();
+      if (res.end() == std::find(res.begin(), res.end(), required)) {
+        userError("Compute resource " + required + "not found ",
+                  "This interface requires the " + required +
+                      " compute resource. Even though your facility is " +
+                      fac.name() +
+                      ", the compute resource was not found. "
+                      "In principle the compute resource should have been "
+                      "defined in the facilities file for you facility. "
+                      "Please check your settings.");
+      }
+      cr->addItem(QString::fromStdString(required));
+    }
+
+    // put local but disable, as it's not yet sorted out how it will work
+    cr->addItem(QString::fromStdString(m_localCompName));
+    QModelIndex idx = cr->model()->index(1, 0);
+    QVariant disabled(0);
+    cr->model()->setData(idx, disabled, Qt::UserRole - 1);
+  }
+}
+
+void TomoReconstruction::setupRunTool() {
+  // set up the reconstruction tool
+  QComboBox *rt = m_ui.comboBox_run_tool;
+  if (rt) {
+    std::vector<std::string> tools;
+    // catch all the useable/relevant tools for the compute
+    // resources. For the time being this is rather simple (just
+    // SCARF) and will probably stay like this for a while.
+    const std::string res = getComputeResource();
+    if ("ISIS" == m_facility && g_SCARFName == res) {
+      tools = m_SCARFtools;
+    }
+    // others would/could come here
+
+    rt->clear();
+    for (size_t i = 0; i < tools.size(); i++) {
+      rt->addItem(QString::fromStdString(tools[i].c_str()));
+
+      // put CCPi but disable it, as it's not yet sorted out how it is
+      // configured / run
+      if (g_CCPiTool == tools[i]) {
+        QModelIndex idx = rt->model()->index(static_cast<int>(i), 0);
+        QVariant disabled(0);
+        rt->model()->setData(idx, disabled, Qt::UserRole - 1);
+      }
+
+      // We cannot run Savu at present
+      if (g_SavuTool == tools[i] || g_CCPiTool == tools[i]) {
+        m_ui.pushButton_reconstruct->setEnabled(false);
+      }
+    }
+  }
+}
+
+/// needs to at least update the 'tool' combo box
+void TomoReconstruction::compResourceIndexChanged(int i) {
+  UNUSED_ARG(i);
+  setupRunTool();
+}
+
+void TomoReconstruction::runToolIndexChanged(int /* i */) {
+  QComboBox *rt = m_ui.comboBox_run_tool;
+
+  if (!rt)
+    return;
+
+  std::string tool = rt->currentText().toStdString();
+  // disallow reconstruct on tools that don't run yet: Savu and CCPi
+  if (g_CCPiTool == tool) {
+    m_ui.pushButton_run_tool_setup->setEnabled(false);
+    m_ui.pushButton_reconstruct->setEnabled(false);
+  } else if (g_SavuTool == tool) {
+    // for now, show setup dialog, but cannot run
+    m_ui.pushButton_run_tool_setup->setEnabled(true);
+    m_ui.pushButton_reconstruct->setEnabled(false);
+  } else {
+    m_ui.pushButton_run_tool_setup->setEnabled(true);
+    m_ui.pushButton_reconstruct->setEnabled(m_loggedIn);
+  }
+}
+
+/**
+ * Log into remote compute resource.
+ *
+ * @param pw Password/authentication credentials as a string
+ */
+void TomoReconstruction::doLogin(const std::string &pw) {
+  if (m_loggedIn) {
+    userError("Better to logout before logging in again",
+              "You're currently logged in. Please, log out before logging in "
+              "again if that's what you meant.");
+  }
+
+  const std::string user = getUsername();
+  if (user.empty()) {
+    userError("Cannot log in",
+              "To log in you need to specify a username (and a password!).");
+    return;
+  }
+
+  // TODO (trac #11538): once the remote algorithms are rearranged
+  // into the 'RemoteJobManager' design, this will use...
+  // auto alg = Algorithm::fromString("Authenticate");
+  auto alg = Algorithm::fromString("SCARFTomoReconstruction");
+  alg->initialize();
+  alg->setPropertyValue("UserName", user);
+  alg->setPropertyValue("Action", "LogIn");
+  alg->setPropertyValue("Password", pw);
+  try {
+    alg->execute();
+  } catch (std::runtime_error &e) {
+    throw std::runtime_error(
+        "Error when trying to log into the remote compute resource " +
+        getComputeResource() + " with username " + user + ": " + e.what());
+  }
+}
+
+void TomoReconstruction::doLogout() {
+  // TODO: once the remote algorithms are rearranged into the
+  // 'RemoteJobManager' design, this will use...
+  // auto alg = Algorithm::fromString("???"); - need an alg for this
+  auto alg = Algorithm::fromString("SCARFTomoReconstruction");
+  alg->initialize();
+  const std::string user = getUsername();
+  alg->setPropertyValue("UserName", user);
+  alg->setPropertyValue("Action", "LogOut");
+  try {
+    alg->execute();
+  } catch (std::runtime_error &e) {
+    throw std::runtime_error(
+        "Error when trying to log out from the remote compute resource " +
+        getComputeResource() + " with username " + user + ": " + e.what());
+  }
+}
+
+/**
+ * Ping the compute resource / server to check if it's alive and
+ * responding.
+ *
+ * @return True if ping succeeded
+ */
+bool TomoReconstruction::doPing() {
+  // TODO: once the remote algorithms are rearranged into the
+  // 'RemoteJobManager' design, this will use...
+  // auto alg = Algorithm::fromString("???");
+  auto alg = Algorithm::fromString("SCARFTomoReconstruction");
+  alg->initialize();
+  alg->setPropertyValue("UserName", getUsername());
+  alg->setPropertyValue("Action", "Ping");
+  try {
+    alg->execute();
+  } catch (std::runtime_error &e) {
+    throw std::runtime_error(
+        "Error when trying to ping the remote compute resource " +
+        getComputeResource() + ": " + e.what());
+  }
+  return true;
+}
+
+/**
+ * Handle the job submission request relies on a submit algorithm.
+ */
+void TomoReconstruction::doSubmitReconstructionJob() {
+  std::string run, opt;
+  try {
+    makeRunnableWithOptions(run, opt);
+  } catch (std::exception &e) {
+    g_log.warning() << "Could not prepare the requested reconstruction job "
+                       "submission. There was an error: " +
+                           std::string(e.what());
+  }
+
+  // TODO: once the remote algorithms are rearranged into the
+  // 'RemoteJobManager' design, this will use:
+  // auto transAlg = Algorithm::fromString("StartRemoteTransaction");
+  // auto submitAlg = Algorithm::fromString("SubmitRemoteJob");
+  // submitAlg->setPropertyValue("ComputeResource", res);
+  auto alg = Algorithm::fromString("SCARFTomoReconstruction");
+  alg->initialize();
+  alg->setPropertyValue("Action", "SubmitJob");
+  alg->setPropertyValue("UserName", getUsername());
+
+  alg->setProperty("RunnablePath", run);
+  alg->setProperty("JobOptions", opt);
+
+  try {
+    alg->execute();
+  } catch (std::runtime_error &e) {
+    throw std::runtime_error(
+        "Error when trying to cancel a reconstruction job: " +
+        std::string(e.what()));
+  }
+}
+
+/**
+ * Build the components of the command line to run on the remote
+ * compute resource.Produces a (normally full) path to a runnable, and
+ * the options (quite like $0 and $* in scripts).
+ *
+ * @param run Path to a runnable application (script, python module, etc.)
+ * @param opt Command line parameters to the application
+ */
+void TomoReconstruction::makeRunnableWithOptions(std::string &run,
+                                                 std::string &opt) {
+  std::string comp =
+      m_ui.comboBox_run_compute_resource->currentText().toStdString();
+
+  checkDataPathsSet();
+
+  // For now we only know how to 'aproximately' run commands on SCARF
+  if (g_SCARFName == comp) {
+    const std::string tool =
+        m_ui.comboBox_run_tool->currentText().toStdString();
+
+    if (tool == g_TomoPyTool) {
+      checkWarningToolNotSetup(tool, m_toolsSettings.tomoPy);
+      // this should get something like:
+      // run = "/work/imat/z-tests-fedemp/scripts/tomopy/imat_recon_FBP.py";
+      // opt = "--input_dir " + base + currentPathFITS() + " " + "--dark " +
+      // base +
+      //      currentPathDark() + " " + "--white " + base + currentPathFlat();
+
+      // TODO this is very unreliable, it will go away better when the
+      // settings are properly stored as toool-settings objects
+      splitCmdLine(m_toolsSettings.tomoPy, run, opt);
+    } else if (tool == g_AstraTool) {
+      checkWarningToolNotSetup(tool, m_toolsSettings.astra);
+      // this should produce something like this:
+      // run = "/work/imat/scripts/astra/astra-3d-SIRT3D.py";
+      // opt = base + currentPathFITS();
+      splitCmdLine(m_toolsSettings.astra, run, opt);
+    } else if (tool == g_CustomCmdTool) {
+      checkWarningToolNotSetup(tool, m_toolsSettings.custom);
+      splitCmdLine(m_toolsSettings.custom, run, opt);
+    } else {
+      userWarning("Unable to use this tool",
+                  "I do not know how to submit jobs to use this tool: " + tool +
+                      ". It seems that this interface is "
+                      "misconfigured or there has been an unexpected "
+                      "failure.");
+    }
+  } else {
+    run = "error_dont_know_what_to_do";
+    opt = "no_options_known";
+
+    userWarning("Unrecognized remote compute resource",
+                "The remote compute resource that you are trying not used is "
+                "not known: " +
+                    comp + ". This seems to indicate that this interface is "
+                           "misconfigured or there has been an unexpected "
+                           "failure.");
+    throw std::runtime_error(
+        "Could not recognize the remote compute resource: " + comp);
+  }
+}
+
+void TomoReconstruction::doCancelJob(const std::string &id) {
+  // TODO: once the remote algorithms are rearranged into the
+  // 'RemoteJobManager' design, this will use:
+  // auto alg = Algorithm::fromString("EndRemoteTransaction");
+  auto alg = Algorithm::fromString("SCARFTomoReconstruction");
+  alg->initialize();
+  alg->setPropertyValue("UserName", getUsername());
+  alg->setPropertyValue("Action", "CancelJob");
+  alg->setPropertyValue("JobID", id);
+  try {
+    alg->execute();
+  } catch (std::runtime_error &e) {
+    throw std::runtime_error(
+        "Error when trying to cancel a reconstruction job: " +
+        std::string(e.what()));
+  }
+}
+
+void TomoReconstruction::toolSetupClicked() {
+  QComboBox *rt = m_ui.comboBox_run_tool;
+  if (!rt)
+    return;
+
+  const std::string tool = rt->currentText().toStdString();
+  if (g_CCPiTool != tool) {
+    showToolConfig(tool);
+  }
+}
+
+void TomoReconstruction::showToolConfig(const std::string &name) {
+  if (g_TomoPyTool == name) {
+    TomoToolConfigTomoPy tomopy;
+    m_uiTomoPy.setupUi(&tomopy);
+    int res = tomopy.exec();
+    if (QDialog::Accepted == res) {
+      // TODO: move this
+      int mi = m_uiTomoPy.comboBox_method->currentIndex();
+      QString run = m_uiTomoPy.lineEdit_runnable->text();
+      if (1 == mi) {
+        // hard-coded for now, this is a different script on SCARF that should
+        // be
+        // integrated with the FBP script
+        run = "/work/imat/runs-scripts/scripts/tomopy/imat_recon_SIRT.py";
+      }
+      double minAngle = m_uiTomoPy.doubleSpinBox_angle_min->value();
+      double maxAngle = m_uiTomoPy.doubleSpinBox_angle_max->value();
+      double cor = m_uiTomoPy.doubleSpinBox_center_rot->value();
+
+      ToolSettingsTomoPy settings(run.toStdString(), g_defOutPath,
+                                  currentPathDark(), currentPathFlat(),
+                                  currentPathFITS(), cor, minAngle, maxAngle);
+      m_toolsSettings.tomoPy = settings.toCommand();
+    }
+  } else if (g_AstraTool == name) {
+    TomoToolConfigAstra astra;
+    m_uiAstra.setupUi(&astra);
+    int res = astra.exec();
+    if (QDialog::Accepted == res) {
+      // TODO: move this
+      int mi = m_uiAstra.comboBox_method->currentIndex();
+      QString run = m_uiAstra.lineEdit_runnable->text();
+      if (1 == mi) {
+        // hard-coded for now, this is a different script on SCARF
+        run = "/work/imat/runs-scripts/scripts/astra/astra-3d-SIRT3D.py";
+      }
+      double cor = m_uiAstra.doubleSpinBox_center_rot->value();
+      double minAngle = m_uiAstra.doubleSpinBox_angle_min->value();
+      double maxAngle = m_uiAstra.doubleSpinBox_angle_max->value();
+
+      ToolSettingsAstraToolbox settings(
+          run.toStdString(), cor, minAngle, maxAngle, g_defOutPath,
+          currentPathDark(), currentPathFlat(), currentPathFITS());
+
+      m_toolsSettings.astra = settings.toCommand();
+    }
+  } else if (g_SavuTool == name) {
+    // TODO: savu not ready. This is a temporary kludge, it just shows
+    // the setup dialog so we can chat about it.
+    TomoToolConfigSavu savu;
+    m_uiSavu.setupUi(&savu);
+    doSetupSectionParameters();
+    savu.setWindowModality(Qt::ApplicationModal);
+    savu.show();
+    QEventLoop el;
+    connect(this, SIGNAL(destroyed()), &el, SLOT(quit()));
+    el.exec();
+  } else if (g_CustomCmdTool == name) {
+    TomoToolConfigCustom cmd;
+    m_uiCustom.setupUi(&cmd);
+    int res = cmd.exec();
+    if (QDialog::Accepted == res) {
+      // TODO: move this
+      QString run = m_uiCustom.lineEdit_runnable->text();
+      QString opts = m_uiCustom.textEdit_cl_opts->toPlainText();
+
+      ToolSettingsCustom settings(run.toStdString(), opts.toStdString());
+      m_toolsSettings.custom = settings.toCommand();
+    }
+  }
+  // TODO: 'CCPi CGLS' not ready
+}
+
+void TomoReconstruction::reconstructClicked() {
+  if (!m_loggedIn)
+    return;
+
+  const std::string &resource = getComputeResource();
+
+  if (m_localCompName != resource) {
+    doSubmitReconstructionJob();
+
+    jobTableRefreshClicked();
+  }
+}
+
+void TomoReconstruction::runVisualizeClicked() {
+  QTableWidget *tbl = m_ui.tableWidget_run_jobs;
+  const int idCol = 2;
+  QTableWidgetItem *hdr = tbl->horizontalHeaderItem(idCol);
+  if ("ID" != hdr->text())
+    throw std::runtime_error("Expected to get the Id of jobs from the "
+                             "second column of the table of jobs, but I "
+                             "found this at that column: " +
+                             hdr->text().toStdString());
+
+  QModelIndexList idSel = tbl->selectionModel()->selectedRows();
+  if (idSel.count() <= 0)
+    return;
+
+  const std::string id = tbl->item(idSel[0].row(), idCol)->text().toStdString();
+  if (idSel.count() > 1)
+    g_log.information() << " Visualizing only the first job: " << id
+                        << std::endl;
+}
+
+/// processes (cancels) all the jobs selected in the table
+void TomoReconstruction::jobCancelClicked() {
+  const std::string &resource = getComputeResource();
+
+  QTableWidget *tbl = m_ui.tableWidget_run_jobs;
+  const int idCol = 2;
+  QTableWidgetItem *hdr = tbl->horizontalHeaderItem(idCol);
+  if ("ID" != hdr->text())
+    throw std::runtime_error("Expected to get the Id of jobs from the "
+                             "second column of the table of jobs, but I "
+                             "found this at that column: " +
+                             hdr->text().toStdString());
+
+  QModelIndexList idSel = tbl->selectionModel()->selectedRows();
+  for (int i = 0; i < idSel.count(); ++i) {
+    std::string id = tbl->item(idSel[i].row(), idCol)->text().toStdString();
+    if (m_localCompName != resource) {
+      doCancelJob(id);
+    }
+  }
+}
+
+void TomoReconstruction::jobTableRefreshClicked() {
+  // get the info from the server into data members. This operation is subject
+  // to delays in the connection, etc.
+  try {
+    getJobStatusInfo();
+  } catch (std::runtime_error &e) {
+    g_log.warning() << "There was an issue while trying to retrieve job status "
+                       "information from the remote compute resource ("
+                    << getComputeResource()
+                    << "). Stopping periodic (automatic) status update to "
+                       "prevent more failures. You can start the automatic "
+                       "update mechanism again by logging in, as apparently "
+                       "there is some problem with the last session: "
+                    << e.what() << std::endl;
+  }
+
+  // update widgets from that info
+  updateJobsTable();
+}
+
+void TomoReconstruction::getJobStatusInfo() {
+  if (!m_loggedIn)
+    return;
+
+  std::vector<std::string> ids, names, status, cmds;
+  doQueryJobStatus(ids, names, status, cmds);
+
+  size_t jobMax = ids.size();
+  if (ids.size() != names.size() || ids.size() != status.size() ||
+      ids.size() != cmds.size()) {
+    // this should not really happen
+    jobMax = std::min(ids.size(), names.size());
+    jobMax = std::min(jobMax, status.size());
+    jobMax = std::min(jobMax, cmds.size());
+    userWarning("Problem retrieving job status information",
+                "The response from the compute resource did not seem "
+                "correct. The table of jobs may not be fully up to date.");
+  }
+
+  {
+    QMutexLocker lockit(&m_statusMutex);
+    m_jobsStatus.clear();
+    m_jobsStatusCmds.clear();
+    // TODO: udate when we update to remote algorithms v2
+    // As SCARF doesn't provide all the info at the moment, and as we're
+    // using the SCARFTomoReconstruction algorithm, the
+    // IRemoteJobManager::RemoteJobInfo struct is for now used only partially
+    // (cmds out). So this loop feels both incomplete and an unecessary second
+    // step that could be avoided.
+    for (size_t i = 0; i < ids.size(); ++i) {
+      IRemoteJobManager::RemoteJobInfo ji;
+      ji.id = ids[i];
+      ji.name = names[i];
+      ji.status = status[i];
+      m_jobsStatus.push_back(ji);
+      m_jobsStatusCmds.push_back(cmds[i]);
+    }
+  }
+}
+
+void TomoReconstruction::doQueryJobStatus(std::vector<std::string> &ids,
+                                          std::vector<std::string> &names,
+                                          std::vector<std::string> &status,
+                                          std::vector<std::string> &cmds) {
+  // TODO: once the remote algorithms are rearranged into the
+  // 'RemoteJobManager' design, this will use...
+  // auto alg = Algorithm::fromString("QueryAllRemoteJobs");
+  // and
+  // auto alg = Algorithm::fromString("QueryRemoteJob");
+
+  // output properties to get: RemoteJobsID, RemoteJobsNames,
+  //    RemoteJobsStatus, RemoteJobsCommands
+  auto alg = Algorithm::fromString("SCARFTomoReconstruction");
+  alg->initialize();
+  alg->setPropertyValue("UserName", getUsername());
+  alg->setPropertyValue("Action", "JobStatus");
+  try {
+    alg->execute();
+  } catch (std::runtime_error &e) {
+    throw std::runtime_error(
+        "Error when trying to query the status of jobs in " +
+        getComputeResource() + ": " + e.what());
+  }
+  ids = alg->getProperty("RemoteJobsID");
+  names = alg->getProperty("RemoteJobsNames");
+  status = alg->getProperty("RemoteJobsStatus");
+  cmds = alg->getProperty("RemoteJobsCommands");
+}
+
+/**
+ * Update the job status and general info table/tree from the info
+ * stored in this class' data members, which ideally should have
+ * information from a recent query to the server.
+ */
+void TomoReconstruction::updateJobsTable() {
+
+  QTableWidget *t = m_ui.tableWidget_run_jobs;
+  bool sort = t->isSortingEnabled();
+  t->setRowCount(static_cast<int>(m_jobsStatus.size()));
+
+  {
+    QMutexLocker lockit(&m_statusMutex);
+    for (size_t i = 0; i < m_jobsStatus.size(); ++i) {
+      int ii = static_cast<int>(i);
+      t->setItem(ii, 0,
+                 new QTableWidgetItem(QString::fromStdString(g_SCARFName)));
+      t->setItem(ii, 1, new QTableWidgetItem(
+                            QString::fromStdString(m_jobsStatus[i].name)));
+      t->setItem(ii, 2, new QTableWidgetItem(
+                            QString::fromStdString(m_jobsStatus[i].id)));
+      t->setItem(ii, 3, new QTableWidgetItem(
+                            QString::fromStdString(m_jobsStatus[i].status)));
+      t->setItem(ii, 4, new QTableWidgetItem(
+                            QString::fromStdString(m_jobsStatusCmds[i])));
+    }
+  }
+
+  t->setSortingEnabled(sort);
+}
+
+void TomoReconstruction::browseImageClicked() {
+  // get path
+  QString fitsStr = QString("Supported formats: FITS, TIFF and PNG "
+                            "(*.fits *.fit *.tiff *.tif *.png);;"
+                            "FITS, Flexible Image Transport System images "
+                            "(*.fits *.fit);;"
+                            "TIFF, Tagged Image File Format "
+                            "(*.tif *.tiff);;"
+                            "PNG, Portable Network Graphics "
+                            "(*.png);;"
+                            "Other extensions/all files (*.*)");
+  // Note that this could be done using UserSubWindow::openFileDialog(),
+  // but that method doesn't give much control over the text used for the
+  // allowed extensions.
+  QString prevPath =
+      MantidQt::API::AlgorithmInputHistory::Instance().getPreviousDirectory();
+  QString path(QFileDialog::getOpenFileName(this, tr("Open image file"),
+                                            prevPath, fitsStr));
+  if (!path.isEmpty()) {
+    MantidQt::API::AlgorithmInputHistory::Instance().setPreviousDirectory(
+        QFileInfo(path).absoluteDir().path());
+  } else {
+    return;
+  }
+
+  QString suf = QFileInfo(path).suffix();
+  bool loaded = false;
+  // This is not so great, as we check extensions and not really file
+  // content/headers, as it should be.
+  if ((0 == QString::compare(suf, "fit", Qt::CaseInsensitive)) ||
+      (0 == QString::compare(suf, "fits", Qt::CaseInsensitive))) {
+    WorkspaceGroup_sptr wsg = loadFITSImage(path.toStdString());
+    if (!wsg)
+      return;
+    MatrixWorkspace_sptr ws =
+        boost::dynamic_pointer_cast<MatrixWorkspace>(wsg->getItem(0));
+    if (!ws)
+      return;
+    drawImage(ws);
+    loaded = true;
+    // clean-up container group workspace
+    if (wsg)
+      AnalysisDataService::Instance().remove(wsg->getName());
+  } else if ((0 == QString::compare(suf, "tif", Qt::CaseInsensitive)) ||
+             (0 == QString::compare(suf, "tiff", Qt::CaseInsensitive)) ||
+             (0 == QString::compare(suf, "png", Qt::CaseInsensitive))) {
+    QImage rawImg(path);
+    QPainter painter;
+    QPixmap pix(rawImg.width(), rawImg.height());
+    painter.begin(&pix);
+    painter.drawImage(0, 0, rawImg);
+    painter.end();
+    m_ui.label_image->setPixmap(pix);
+    m_ui.label_image->show();
+    loaded = true;
+  } else {
+    userWarning("Failed to load image - format issue",
+                "Could not load image because the extension of the file " +
+                    path.toStdString() + ", suffix: " + suf.toStdString() +
+                    " does not correspond to FITS or TIFF files.");
+  }
+
+  if (loaded)
+    m_ui.label_image_name->setText(path);
+}
+
+/**
+ * Helper to get a FITS image into a workspace. Uses the LoadFITS
+ * algorithm. If the algorithm throws, this method shows user (pop-up)
+ * warning/error messages but does not throw.
+ *
+ * This method returns a workspace group which most probably you want
+ * to delete after using the image to draw it.
+ *
+ * @param path Path to a FITS image
+ *
+ * @return Group Workspace containing a Matrix workspace with a FITS
+ * image, one pixel per histogram, as loaded by LoadFITS (can be empty
+ * if the load goes wrong and the workspace is not available from the
+ * ADS).
+ */
+WorkspaceGroup_sptr TomoReconstruction::loadFITSImage(const std::string &path) {
+  // get fits file into workspace and retrieve it from the ADS
+  auto alg = Algorithm::fromString("LoadFITS");
+  alg->initialize();
+  alg->setPropertyValue("Filename", path);
+  std::string wsName = "__fits_ws_imat_tomography_gui";
+  alg->setProperty("OutputWorkspace", wsName);
+  try {
+    alg->execute();
+  } catch (std::exception &e) {
+    userWarning("Failed to load image", "Could not load this file as a "
+                                        "FITS image: " +
+                                            std::string(e.what()));
+    return WorkspaceGroup_sptr();
+  }
+  if (!alg->isExecuted()) {
+    userWarning("Failed to load image correctly",
+                "Note that even though "
+                "the image file has been loaded it seems to contain "
+                "errors.");
+  }
+  WorkspaceGroup_sptr wsg;
+  MatrixWorkspace_sptr ws;
+  try {
+    wsg = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(wsName);
+    ws = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(
+        wsg->getNames()[0]);
+  } catch (std::exception &e) {
+    userWarning("Could not load image contents",
+                "An unrecoverable error "
+                "happened when trying to load the image contents. Cannot "
+                "display it. Error details: " +
+                    std::string(e.what()));
+    return WorkspaceGroup_sptr();
+  }
+
+  // draw image from workspace
+  if (wsg && ws &&
+      Mantid::API::AnalysisDataService::Instance().doesExist(ws->name())) {
+    return wsg;
+  } else {
+    return WorkspaceGroup_sptr();
+  }
+}
+
+/**
+ * Check that the selected compute resource is listed as supported and
+ * usable for the remote manager (if it is not local). Local jobs are
+ * not supported for the time being, so this currently raises an
+ * exception if the local resource has been selected.
+ *
+ * This should never throw an exception if the
+ * construction/initialization and setup steps went fine and the rest
+ * of the code is kept consistent with those steps.
+ *
+ * @param res Name of the compute resource selected in the interface
+ *
+ * @return Name of a compute resource (which can be the 'Local' one)
+ *
+ * @throws std::runtime_error on inconsistent selection of compute
+ * resource
+ */
+std::string TomoReconstruction::validateCompResource(const std::string &res) {
+  if (res == m_localCompName) {
+    // Nothing yet
+    throw std::runtime_error("There is no support for the local compute "
+                             "resource. You should not have got here.");
+  }
+
+  if (m_computeRes.size() <= 0) {
+    throw std::runtime_error("No compute resource registered in the list "
+                             "of supported resources. This graphical interface "
+                             "is in an inconsistent status.");
+  }
+
+  const std::string supported = m_computeRes.front();
+  if (supported.empty()) {
+    throw std::runtime_error("The first compute resource registered in this "
+                             "interface has an empty name.");
+  }
+
+  if (res != supported) {
+    throw std::runtime_error("The compute resource selected (" + res +
+                             ") is not the one in principle supported by this "
+                             "interface: " +
+                             supported);
+  }
+
+  return supported;
+}
+
+/**
+ * Gets the compute resource that is currently selected by the user.
+ * This calls a validation method that can throw in case of
+ * inconsistencies.
+ *
+ * @return Name of the compute resource as a string.
+ */
+std::string TomoReconstruction::getComputeResource() {
+  QComboBox *cb = m_ui.comboBox_run_compute_resource;
+  QString rs = cb->currentText();
+  return validateCompResource(rs.toStdString());
+}
+
+/**
+ * Retrieve the username being used for the selected compute resource.
+ *
+ * @return Username ready to be used in remote queries
+ */
+std::string TomoReconstruction::getUsername() {
+  if (g_SCARFName ==
+      m_ui.comboBox_run_compute_resource->currentText().toStdString())
+    return m_ui.lineEdit_SCARF_username->text().toStdString();
+  else
+    return "invalid";
+}
+
+std::string TomoReconstruction::currentPathSCARF() {
+  return m_ui.lineEdit_SCARF_path->text().toStdString();
+}
+
+std::string TomoReconstruction::currentPathFITS() {
+  return m_ui.lineEdit_path_FITS->text().toStdString();
+}
+
+std::string TomoReconstruction::currentPathFlat() {
+  return m_ui.lineEdit_path_flat->text().toStdString();
+}
+
+std::string TomoReconstruction::currentPathDark() {
+  return m_ui.lineEdit_path_dark->text().toStdString();
+}
+
+void TomoReconstruction::fitsPathBrowseClicked() {
+  processPathBrowseClick(m_ui.lineEdit_path_FITS, m_pathFITS);
+}
+
+void TomoReconstruction::flatPathBrowseClicked() {
+  processPathBrowseClick(m_ui.lineEdit_path_flat, m_pathFlat);
+}
+
+void TomoReconstruction::darkPathBrowseClicked() {
+  processPathBrowseClick(m_ui.lineEdit_path_dark, m_pathDark);
+}
+
+/**
+ * Get path from user and update a line edit and a variable.
+ *
+ * @param le a line edit where the path is shown.
+ * @param data variable where the path is stored (in addition to the line
+ * edit object).
+ */
+void TomoReconstruction::processPathBrowseClick(QLineEdit *le,
+                                                std::string &data) {
+  QString algPrev =
+      MantidQt::API::AlgorithmInputHistory::Instance().getPreviousDirectory();
+  QString prev;
+  if (le->text().isEmpty()) {
+    prev = algPrev;
+  } else {
+    prev = le->text();
+  }
+
+  QString path(QFileDialog::getExistingDirectory(
+      this, tr("Open directory/folder"), prev));
+
+  if (!path.isEmpty()) {
+    std::string pp = path.toStdString();
+    // to UNIX, assuming SCARF or similar
+    boost::replace_all(pp, "\\", "/");
+    if (pp.length() >= 2 && ':' == pp[1]) {
+      if (2 == pp.length())
+        pp = ""; // don't accept '/'
+      else
+        pp = pp.substr(2);
+    }
+
+    le->setText(QString::fromStdString(pp));
+    data = pp;
+  }
+}
+
+/**
+ * Retrieve the username being used for the selected compute resource.
+ *
+ * @return Username ready to be used in remote queries
+ */
+std::string TomoReconstruction::getPassword() {
+  if (g_SCARFName ==
+      m_ui.comboBox_run_compute_resource->currentText().toStdString())
+    return m_ui.lineEdit_SCARF_password->text().toStdString();
+  else
+    return "none";
+}
+
+/**
+ * draw an image on screen using Qt's QPixmap and QImage. It assumes
+ * that the workspace contains an image in the form in which LoadFITS
+ * loads FITS images. Checks dimensions and workspace structure and
+ * shows user warning/error messages appropriately. But in principle
+ * it should not raise any exceptions under reasonable circumstances.
+ *
+ * @param ws Workspace where a FITS image has been loaded with LoadFITS
+ */
+void TomoReconstruction::drawImage(const MatrixWorkspace_sptr &ws) {
+  // From logs we expect a name "run_title", width "Axis1" and height "Axis2"
+  const size_t MAXDIM = 2048 * 16;
+  size_t width;
+  try {
+    width = boost::lexical_cast<size_t>(ws->run().getLogData("Axis1")->value());
+    // TODO: add a settings option for this (like max mem allocation for images)?
+    if (width >= MAXDIM)
+      width = MAXDIM;
+  } catch (std::exception &e) {
+    userError("Cannot load image", "There was a problem while trying to "
+                                   "find the width of the image: " +
+                                       std::string(e.what()));
+    return;
+  }
+  size_t height;
+  try {
+    height =
+        boost::lexical_cast<size_t>(ws->run().getLogData("Axis2")->value());
+    if (height >= MAXDIM)
+      height = MAXDIM;
+  } catch (std::exception &e) {
+    userError("Cannot load image", "There was a problem while trying to "
+                                   "find the height of the image: " +
+                                       std::string(e.what()));
+    return;
+  }
+  try {
+    std::string name = ws->run().getLogData("run_title")->value();
+    g_log.information() << " Visualizing image: " << name << std::endl;
+  } catch (std::exception &e) {
+    userWarning("Cannot load image information",
+                "There was a problem while "
+                " trying to find the name of the image: " +
+                    std::string(e.what()));
+  }
+
+  // images are loaded as 1 histogram == 1 pixel (1 bin per histogram):
+  if ((width * height) != ws->getNumberHistograms()) {
+    userError("Image dimensions do not match", "Could not load the expected "
+                                               "number of pixels.");
+    return;
+  }
+  // find min and max to scale pixel values
+  double min = std::numeric_limits<double>::max(),
+         max = std::numeric_limits<double>::min();
+  for (size_t i = 0; i < ws->getNumberHistograms(); ++i) {
+    const double &v = ws->readY(i)[0];
+    if (v < min)
+      min = v;
+    if (v > max)
+      max = v;
+  }
+  if (min >= max) {
+    userWarning("Empty image!",
+                "The image could be loaded but it contains "
+                "effectively no information, all pixels have the same value.");
+    // black picture
+    QPixmap pix(static_cast<int>(width), static_cast<int>(height));
+    pix.fill(QColor(0, 0, 0));
+    m_ui.label_image->setPixmap(pix);
+    m_ui.label_image->show();
+    return;
+  }
+
+  // load / transfer image into a QImage
+  QImage rawImg(QSize(static_cast<int>(width), static_cast<int>(height)),
+                QImage::Format_RGB32);
+  size_t i = 0;
+  double max_min = max - min;
+  for (size_t yi = 0; yi < width; ++yi) {
+    for (size_t xi = 0; xi < width; ++xi) {
+      const double &v = ws->readY(i)[0];
+      // color the range min-max in gray scale. To apply different color
+      // maps you'd need to use rawImg.setColorTable() or similar.
+      int scaled = static_cast<int>(255.0 * (v - min) / max_min);
+      QRgb vRgb = qRgb(scaled, scaled, scaled);
+      rawImg.setPixel(static_cast<int>(xi), static_cast<int>(yi), vRgb);
+      ++i;
+    }
+  }
+
+  // paint and show image
+  QPainter painter;
+  QPixmap pix(static_cast<int>(width), static_cast<int>(height));
+  painter.begin(&pix);
+  painter.drawImage(0, 0, rawImg);
+  painter.end();
+  m_ui.label_image->setPixmap(pix);
+  m_ui.label_image->show();
+}
+
+/**
+  * Temporary helper to do an operation that shouldn't be needed any longer when
+  * the code is reorganized to use the tool settings objetcs better.
+  */
+void TomoReconstruction::splitCmdLine(const std::string &cmd, std::string &run,
+                                      std::string &opts) {
+  if (cmd.empty())
+    return;
+
+  auto pos = cmd.find(' ');
+  if (std::string::npos == pos)
+    return;
+
+  run = cmd.substr(0, pos);
+  opts = cmd.substr(pos + 1);
+}
+
+/**
+ * Make sure that the data paths (sample, dark, open beam) make
+ * sense. Otherwise, warn the user and log error.
+ *
+ * @throw std::runtime_error if the required fields are not set
+ * properly
+ */
+void TomoReconstruction::checkDataPathsSet() {
+  if (currentPathFITS().empty() || currentPathFlat().empty() ||
+      currentPathDark().empty()) {
+    userWarning("Please define the paths to your dataset images",
+                "You have not defined some of the following paths: sample, "
+                "dark, or open beam images. "
+                "They are all required to run reconstruction jobs. Please "
+                "define these paths in the settings tab. ");
+    throw std::runtime_error("Cannot run any reconstruction job without the "
+                             "paths to the sample, dark and open beam images");
+  }
+}
+
+/**
+ * A specific warning that can be shown for multiple tools
+ *
+ * @param tool Name of the tool this warning applies to
+ * @param settings current settings for the tool
+ */
+void TomoReconstruction::checkWarningToolNotSetup(const std::string &tool,
+                                                  const std::string &settings) {
+  if (settings.empty()) {
+    userWarning("Please define the settings of this tool",
+                "You have not defined any settings for this tool: " + tool +
+                    ". Before running it you need to define its settings "
+                    "(parameters). You can do so by clicking on the setup "
+                    "button.");
+    throw std::runtime_error("Cannot run the tool " + tool +
+                             " before its settings have been defined.");
+  }
+}
+
+/**
+* Show a warning message to the user (pop up)
+*
+* @param err Basic error title
+* @param description More detailed explanation, hints, additional
+* information, etc.
+*/
+void TomoReconstruction::userWarning(const std::string &err,
+                                     const std::string &description) {
+  QMessageBox::warning(this, QString::fromStdString(err),
+                       QString::fromStdString(description), QMessageBox::Ok,
+                       QMessageBox::Ok);
+}
+
+/**
+ * Show an error (serious) message to the user (pop up)
+ *
+ * @param err Basic error title
+ * @param description More detailed explanation, hints, additional
+ * information, etc.
+ */
+void TomoReconstruction::userError(const std::string &err,
+                                   const std::string &description) {
+  QMessageBox::critical(this, QString::fromStdString(err),
+                        QString::fromStdString(description), QMessageBox::Ok,
+                        QMessageBox::Ok);
+}
+
+void TomoReconstruction::openHelpWin() {
+  MantidQt::API::HelpWindow::showCustomInterface(
+      NULL, QString("Tomographic_Reconstruction"));
+}
+
+void TomoReconstruction::periodicStatusUpdateRequested() {
+  // does just the widgets update
+  updateJobsTable();
+}
+
+void TomoReconstruction::startKeepAliveMechanism(int period) {
+  if (m_keepAliveThread)
+    delete m_keepAliveThread;
+  QThread *m_keepAliveThread = new QThread();
+
+  if (m_keepAliveTimer)
+    delete m_keepAliveTimer;
+  m_keepAliveTimer = new QTimer(NULL); // no-parent so it can be moveToThread
+
+  m_keepAliveTimer->setInterval(1000 * period);
+  m_keepAliveTimer->moveToThread(m_keepAliveThread);
+  // direct connection from the thread
+  connect(m_keepAliveTimer, SIGNAL(timeout()), SLOT(jobTableRefreshClicked()),
+          Qt::DirectConnection);
+  QObject::connect(m_keepAliveThread, SIGNAL(started()), m_keepAliveTimer,
+                   SLOT(start()));
+  m_keepAliveThread->start();
+}
+
+void TomoReconstruction::killKeepAliveMechanism() {
+  if (m_keepAliveTimer)
+    m_keepAliveTimer->stop();
+}
+
+void TomoReconstruction::closeEvent(QCloseEvent *event) {
+  int answer = QMessageBox::AcceptRole;
+
+  bool ask = m_settings.onCloseAskForConfirmation;
+  if (ask) {
+    QMessageBox msgBox;
+    msgBox.setWindowTitle("Close the tomographic reconstruction interface");
+    // with something like this, we'd have layout issues:
+    // msgBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
+    // msgBox.setDefaultButton(QMessageBox::Yes);
+    msgBox.setIconPixmap(QPixmap(":/win/unknown.png"));
+    QCheckBox confirmCheckBox("Always ask for confirmation", &msgBox);
+    confirmCheckBox.setCheckState(Qt::Checked);
+    msgBox.layout()->addItem(new QSpacerItem(0, 0, QSizePolicy::Expanding));
+    msgBox.layout()->addWidget(&confirmCheckBox);
+    QPushButton *bYes = msgBox.addButton("Yes", QMessageBox::YesRole);
+    bYes->setIcon(style()->standardIcon(QStyle::SP_DialogYesButton));
+    QPushButton *bNo = msgBox.addButton("No", QMessageBox::NoRole);
+    bNo->setIcon(style()->standardIcon(QStyle::SP_DialogNoButton));
+    msgBox.setDefaultButton(bNo);
+    msgBox.setText("You are about to close this interface");
+    msgBox.setInformativeText(
+        "If you close this interface you will need to log in again "
+        "and you might loose some of the current state. Jobs running on remote "
+        "compute resources will remain unaffected though. Are you sure?");
+
+    m_settings.onCloseAskForConfirmation = confirmCheckBox.isChecked();
+    answer = msgBox.exec();
+  }
+
+  if (answer == QMessageBox::AcceptRole) {
+    cleanup();
+    event->accept();
+  } else {
+    event->ignore();
+  }
+}
+
+} // namespace CustomInterfaces
+} // namespace MantidQt
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/TomoReconstruction/TomoToolConfigDialog.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/TomoReconstruction/TomoToolConfigDialog.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..7739cc8c7330af4ca0cee3cd2a62cc7d031ee101
--- /dev/null
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/TomoReconstruction/TomoToolConfigDialog.cpp
@@ -0,0 +1,48 @@
+#include "MantidQtCustomInterfaces/TomoReconstruction/TomoToolConfigDialog.h"
+
+namespace MantidQt {
+namespace CustomInterfaces {
+
+TomoToolConfigTomoPy::TomoToolConfigTomoPy(QWidget *parent) : QDialog(parent) {}
+
+TomoToolConfigSavu::TomoToolConfigSavu(QWidget *parent) : QMainWindow(parent) {}
+
+TomoToolConfigAstra::TomoToolConfigAstra(QWidget *parent) : QDialog(parent) {}
+
+TomoToolConfigCustom::TomoToolConfigCustom(QWidget *parent) : QDialog(parent) {}
+
+TomoToolConfigDialog::TomoToolConfigDialog(QWidget *parent) : QDialog(parent) {
+  labelRun = new QLabel("Runnable script");
+  editRun = new QLineEdit("/work/imat/");
+  hRun = new QHBoxLayout();
+  hRun->addWidget(labelRun);
+  hRun->addWidget(editRun);
+
+  labelOpt = new QLabel("Command line options");
+  editOpt = new QLineEdit("/work/imat");
+  hOpt = new QHBoxLayout();
+  hOpt->addWidget(labelOpt);
+  hOpt->addWidget(editOpt);
+
+  okButton = new QPushButton("Ok");
+  cancelButton = new QPushButton("Cancel");
+  hBut = new QHBoxLayout();
+  hBut->insertStretch(0,1);
+  hBut->addWidget(okButton);
+  hBut->addWidget(cancelButton);
+
+  layout = new QGridLayout();
+  layout->addLayout(hRun, 0, 0);
+  layout->addLayout(hOpt, 1, 0);
+  layout->addLayout(hOpt, 2, 0);
+
+  connect(okButton, SIGNAL(clicked()), this, SLOT(okClicked()));
+  connect(cancelButton, SIGNAL(clicked()), this, SLOT(cancelClicked()));
+}
+
+void TomoToolConfigDialog::okClicked() {}
+
+void TomoToolConfigDialog::cancelClicked() {}
+
+} // namespace CustomInterfaces
+} // namespace MantidQt
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/TomoReconstruction/ToolSettings.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/TomoReconstruction/ToolSettings.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..43e36d203e22c3ff886c6232478305d5c7d6178c
--- /dev/null
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/TomoReconstruction/ToolSettings.cpp
@@ -0,0 +1,46 @@
+#include "MantidQtCustomInterfaces/TomoReconstruction/ToolSettings.h"
+
+#include <boost/lexical_cast.hpp>
+
+namespace MantidQt {
+namespace CustomInterfaces {
+
+ToolSettingsTomoPy::ToolSettingsTomoPy(const std::string &runnable,
+                                       const std::string &pathOut,
+                                       const std::string &pathDark,
+                                       const std::string &pathOpen,
+                                       const std::string &pathSample,
+                                       double centerRot, double angleMin,
+                                       double angleMax)
+    : ToolSettings(runnable), m_pathOut(pathOut), m_pathDark(pathDark),
+      m_pathOpen(pathOpen), m_pathSample(pathSample), m_centerRot(centerRot),
+      m_angleMin(angleMin), m_angleMax(angleMax) {}
+
+std::string ToolSettingsTomoPy::makeCmdLineOptions() const {
+  return "--input_dir " + m_pathSample + " --dark " + m_pathDark + " --white " +
+         m_pathOpen + " --output " + m_pathOut + " --start_angle " +
+         boost::lexical_cast<std::string>(m_angleMin) + " --end_angle " +
+         boost::lexical_cast<std::string>(m_angleMax) +
+         " --center_of_rotation " +
+         boost::lexical_cast<std::string>(m_centerRot);
+}
+
+ToolSettingsAstraToolbox::ToolSettingsAstraToolbox(
+    const std::string &runnable, double centerRot, double angleMin,
+    double angleMax, const std::string &pathOut, const std::string &pathDark,
+    const std::string &pathOpen, const std::string &pathSample)
+    : ToolSettings(runnable), m_centerRot(centerRot), m_angleMin(angleMin),
+      m_angleMax(angleMax), m_pathOut(pathOut), m_pathDark(pathDark),
+      m_pathOpen(pathOpen), m_pathSample(pathSample) {}
+
+std::string ToolSettingsAstraToolbox::makeCmdLineOptions() const {
+  return "--start_slice " + boost::lexical_cast<std::string>(m_angleMin) +
+         " --end_slice " + boost::lexical_cast<std::string>(m_angleMax) +
+         " --center_of_rotation " +
+         boost::lexical_cast<std::string>(m_centerRot) + "--input_dir " +
+         m_pathSample + " --dark " + m_pathDark + " --white " + m_pathOpen +
+         " --output " + m_pathOut;
+}
+
+} // namespace CustomInterfaces
+} // namespace MantidQt
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/test/ALCBaselineModellingModelTest.h b/Code/Mantid/MantidQt/CustomInterfaces/test/ALCBaselineModellingModelTest.h
index 8e10f1d1f5bf7f6d93263cc291674f04bea9c264..fdffada96387f32aa510d35426a04e0c9ddde52f 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/test/ALCBaselineModellingModelTest.h
+++ b/Code/Mantid/MantidQt/CustomInterfaces/test/ALCBaselineModellingModelTest.h
@@ -44,14 +44,24 @@ public:
 
   void test_setData()
   {
-    MatrixWorkspace_sptr data = WorkspaceFactory::Instance().create("Workspace2D", 1, 1, 1);
+    std::vector<double> y = boost::assign::list_of(100)(1)(2)(100)(100)(3)(4)(5)(100);
+    std::vector<double> x = boost::assign::list_of(1)(2)(3)(4)(5)(6)(7)(8)(9);
+
+    MatrixWorkspace_sptr data = WorkspaceFactory::Instance().create("Workspace2D", 1, y.size(), y.size());
+    data->dataY(0) = y;
+    data->dataX(0) = x;
 
     QSignalSpy spy(m_model, SIGNAL(dataChanged()));
 
     TS_ASSERT_THROWS_NOTHING(m_model->setData(data));
 
     TS_ASSERT_EQUALS(spy.size(), 1);
-    TS_ASSERT_EQUALS(m_model->data(), data);
+
+    MatrixWorkspace_const_sptr modelData = m_model->data();
+
+    TS_ASSERT_EQUALS(modelData->readX(0), data->readX(0));
+    TS_ASSERT_EQUALS(modelData->readY(0), data->readY(0));
+    TS_ASSERT_EQUALS(modelData->readE(0), data->readE(0));
   }
 
   void test_fit()
@@ -98,22 +108,40 @@ public:
       TS_ASSERT_DELTA(corrected->readY(0)[8], 97, 1E-8);
     }
 
+    ITableWorkspace_sptr parameters = m_model->parameterTable();
+    TS_ASSERT(parameters);
+
+    if (parameters)
+    {
+      // Check table dimensions
+      TS_ASSERT_EQUALS(parameters->rowCount(), 2);
+      TS_ASSERT_EQUALS(parameters->columnCount(), 3);
+
+      // Check table entries
+      TS_ASSERT_EQUALS(parameters->String(0,0), "A0");
+      TS_ASSERT_EQUALS(parameters->Double(0,1), 3);
+      TS_ASSERT_DELTA (parameters->Double(0,2), 0.447214,1E-6);
+      TS_ASSERT_EQUALS(parameters->String(1,0), "Cost function value");
+      TS_ASSERT_DELTA (parameters->Double(1,1), 1.250000,1E-6);
+      TS_ASSERT_EQUALS(parameters->Double(1,2), 0);
+    }
+
     TS_ASSERT_EQUALS(m_model->sections(), sections);
   }
 
   void test_exportWorkspace()
   {
-    // TODO: implement
+    TS_ASSERT_THROWS_NOTHING(m_model->exportWorkspace());
   }
 
   void test_exportTable()
   {
-    // TODO: implement
+    TS_ASSERT_THROWS_NOTHING(m_model->exportSections());
   }
 
   void test_exportModel()
   {
-    // TODO: implement
+    TS_ASSERT_THROWS_NOTHING(m_model->exportModel());
   }
 
 };
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/test/ALCBaselineModellingPresenterTest.h b/Code/Mantid/MantidQt/CustomInterfaces/test/ALCBaselineModellingPresenterTest.h
index 43c74631af9fd5b59f3b50536be4e0f659d42792..9dda8ed8f64a95e07797254eb4b5e45114efaad7 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/test/ALCBaselineModellingPresenterTest.h
+++ b/Code/Mantid/MantidQt/CustomInterfaces/test/ALCBaselineModellingPresenterTest.h
@@ -152,12 +152,6 @@ public:
                                             QwtDataX(0, 1, 1E-8), QwtDataX(2, 3, 1E-8),
                                             QwtDataY(0, 2, 1E-8), QwtDataY(2, 4, 1E-8))));
 
-    // Data changed -> clear sections
-    EXPECT_CALL(*m_view, setNoOfSectionRows(0));
-    EXPECT_CALL(*m_view, deleteSectionSelector(0));
-    EXPECT_CALL(*m_view, deleteSectionSelector(1));
-    EXPECT_CALL(*m_view, deleteSectionSelector(2));
-
     m_model->changeData();
   }
 
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/test/ALCDataLoadingPresenterTest.h b/Code/Mantid/MantidQt/CustomInterfaces/test/ALCDataLoadingPresenterTest.h
index e61879312c74af0428c2825ca5acd6ba8308326c..dc3c9dfa8bc6347a9cd1335d4bd53b7ac5b4bd4d 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/test/ALCDataLoadingPresenterTest.h
+++ b/Code/Mantid/MantidQt/CustomInterfaces/test/ALCDataLoadingPresenterTest.h
@@ -157,7 +157,7 @@ public:
   void test_updateAvailableLogs()
   {
     EXPECT_CALL(*m_view, firstRun()).WillRepeatedly(Return("MUSR00015189.nxs"));
-    EXPECT_CALL(*m_view, setAvailableLogs(AllOf(Property(&std::vector<std::string>::size, 33),
+    EXPECT_CALL(*m_view, setAvailableLogs(AllOf(Property(&std::vector<std::string>::size, 37),
                                                 Contains("run_number"),
                                                 Contains("sample_magn_field"),
                                                 Contains("Field_Danfysik"))));
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/test/ALCPeakFittingModelTest.h b/Code/Mantid/MantidQt/CustomInterfaces/test/ALCPeakFittingModelTest.h
new file mode 100644
index 0000000000000000000000000000000000000000..0ffc73fb4f8b36c4a3a07300c4a44c138e3d1075
--- /dev/null
+++ b/Code/Mantid/MantidQt/CustomInterfaces/test/ALCPeakFittingModelTest.h
@@ -0,0 +1,109 @@
+#ifndef MANTID_CUSTOMINTERFACES_ALCPEAKFITTINGMODELTEST_H_
+#define MANTID_CUSTOMINTERFACES_ALCPEAKFITTINGMODELTEST_H_
+
+#include <cxxtest/TestSuite.h>
+
+#include <boost/assign.hpp>
+
+#include "MantidAPI/MatrixWorkspace.h"
+#include "MantidAPI/WorkspaceFactory.h"
+#include "MantidAPI/FunctionFactory.h"
+#include "MantidAPI/FrameworkManager.h"
+
+#include "MantidQtCustomInterfaces/Muon/ALCPeakFittingModel.h"
+
+#include <QtTest/QSignalSpy>
+
+using namespace Mantid::API;
+using namespace MantidQt::CustomInterfaces;
+
+class ALCPeakFittingModelTest : public CxxTest::TestSuite
+{
+  ALCPeakFittingModel* m_model;
+
+public:
+  // This pair of boilerplate methods prevent the suite being created statically
+  // This means the constructor isn't called when running other tests
+  static ALCPeakFittingModelTest *createSuite() { return new ALCPeakFittingModelTest(); }
+  static void destroySuite( ALCPeakFittingModelTest *suite ) { delete suite; }
+
+  ALCPeakFittingModelTest()
+  {
+    FrameworkManager::Instance(); // To make sure everything is initialized
+  }
+
+  void setUp()
+  {
+    m_model = new ALCPeakFittingModel();
+  }
+
+  void tearDown()
+  {
+    delete m_model;
+  }
+
+  void test_setData()
+  {
+    MatrixWorkspace_sptr data = WorkspaceFactory::Instance().create("Workspace2D", 1, 1, 1);
+
+    QSignalSpy spy(m_model, SIGNAL(dataChanged()));
+
+    TS_ASSERT_THROWS_NOTHING(m_model->setData(data));
+
+    TS_ASSERT_EQUALS(spy.size(), 1);
+    TS_ASSERT_EQUALS(m_model->data(), data);
+  }
+
+  void test_fit()
+  {
+    std::vector<double> x = boost::assign::list_of(1.00)(2.00)(3.00)(4.00)(5.00)(6.00)(7.00)(8.00);
+    std::vector<double> y = boost::assign::list_of(0.00)(0.01)(0.02)(0.37)(1.00)(0.37)(0.01)(0.00);
+
+    MatrixWorkspace_sptr data = WorkspaceFactory::Instance().create("Workspace2D", 1, y.size(), y.size());
+    data->dataY(0) = y;
+    data->dataX(0) = x;
+
+    m_model->setData(data);
+
+    IFunction_const_sptr func = FunctionFactory::Instance().createInitialized("name=FlatBackground");
+
+    TS_ASSERT_THROWS_NOTHING(m_model->fitPeaks(func));
+
+    IFunction_const_sptr fittedFunc = m_model->fittedPeaks();
+    TS_ASSERT(fittedFunc);
+
+    if (fittedFunc)
+    {
+      TS_ASSERT_EQUALS(fittedFunc->name(), "FlatBackground");
+      TS_ASSERT_DELTA (fittedFunc->getParameter("A0"), 0.2225, 1E-4);
+    }
+
+    ITableWorkspace_sptr parameters = m_model->parameterTable();
+    TS_ASSERT(parameters);
+
+    if (parameters)
+    {
+      // Check table dimensions
+      TS_ASSERT_EQUALS(parameters->rowCount(), 2);
+      TS_ASSERT_EQUALS(parameters->columnCount(), 3);
+
+      // Check table entries
+      TS_ASSERT_EQUALS(parameters->String(0,0), "A0");
+      TS_ASSERT_DELTA (parameters->Double(0,1), 0.2225, 1E-4);
+      TS_ASSERT_DELTA (parameters->Double(0,2), 0.3535, 1E-4);
+      TS_ASSERT_EQUALS(parameters->String(1,0), "Cost function value");
+      TS_ASSERT_DELTA (parameters->Double(1,1), 0.1254, 1E-4);
+      TS_ASSERT_DELTA (parameters->Double(1,2), 0.0000, 1E-4);
+    }
+
+  }
+
+  void test_exportWorkspace()
+  {
+    TS_ASSERT_THROWS_NOTHING (m_model->exportWorkspace());
+  }
+
+};
+
+
+#endif /* MANTID_CUSTOMINTERFACES_ALCPEAKFITTINGMODELTEST_H_ */
diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/SlicingAlgorithmDialog.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/SlicingAlgorithmDialog.cpp
index 61a4e257246bafb4a8b61222f6f709c85e87ca92..7a157fe63bee473e6c1d792bbd550a4cfa696e94 100644
--- a/Code/Mantid/MantidQt/MantidWidgets/src/SlicingAlgorithmDialog.cpp
+++ b/Code/Mantid/MantidQt/MantidWidgets/src/SlicingAlgorithmDialog.cpp
@@ -442,12 +442,12 @@ namespace MantidQt
       ui.file_backend_layout->setVisible(false);
 
       // Output workspace
-      ui.lbl_workspace_output->setVisible(false);
-      ui.txt_output->setVisible(false);
+      ui.lbl_workspace_output->setDisabled(true);
+      ui.txt_output->setDisabled(true);
 
       // Input workspace
-      ui.workspace_selector->setVisible(false);
-      ui.lbl_workspace_input->setVisible(false);
+      ui.workspace_selector->setDisabled(true);
+      ui.lbl_workspace_input->setDisabled(true);
 
       // Reset the input workspace
       ui.workspace_selector->clear();
diff --git a/Code/Mantid/MantidQt/SliceViewer/inc/MantidQtSliceViewer/LineViewer.h b/Code/Mantid/MantidQt/SliceViewer/inc/MantidQtSliceViewer/LineViewer.h
index c03cfd1981b6fead2ce072d6c1fe03cb7198b973..fe90ee770551eef126782fb841a455a3478f521b 100644
--- a/Code/Mantid/MantidQt/SliceViewer/inc/MantidQtSliceViewer/LineViewer.h
+++ b/Code/Mantid/MantidQt/SliceViewer/inc/MantidQtSliceViewer/LineViewer.h
@@ -156,6 +156,11 @@ private:
     /// Index of the Y dimension in the 2D slice
     int m_freeDimY;
 
+    /// Index of the first selected X dimension in the 2D slice
+    int m_initFreeDimX;
+    /// Index of the first selected Y dimension in the 2D slice
+    int m_initFreeDimY;
+
     /// When True, then the bin width is fixed and the number of bins changes
     bool m_fixedBinWidthMode;
 
diff --git a/Code/Mantid/MantidQt/SliceViewer/src/LineOverlay.cpp b/Code/Mantid/MantidQt/SliceViewer/src/LineOverlay.cpp
index d6c316a4be0247b29995d4fce58701dac8e801d4..dd3f765dd9913f3a3cc53fd467aac18f28eb8add 100644
--- a/Code/Mantid/MantidQt/SliceViewer/src/LineOverlay.cpp
+++ b/Code/Mantid/MantidQt/SliceViewer/src/LineOverlay.cpp
@@ -387,10 +387,21 @@ namespace SliceViewer
     double distance = fabs( diff.x()*(current.y()-pixA.y()) - (current.x() - pixA.x())*diff.y() )
         / sqrt(diff.x()*diff.x() + diff.y()*diff.y());
 
-    // Margin of 6 pixels, and must be between the 2 limits
-    return ((distance < 7) &&
-        isBetween( current.x(), pixA.x(), pixB.x()) &&
-        isBetween( current.y(), pixA.y(), pixB.y()) );
+    // Margin of 6 pixels, and must be between the 2 limits (if the limits are not the same)
+    bool retval = false;
+    if (distance < 7)
+    {
+      retval = true;
+      if ((pixA.x() != pixB.x()) && (!isBetween( current.x(), pixA.x(), pixB.x())))
+      {
+        retval = false;
+      }
+      if ((pixA.y() != pixB.y()) && (!isBetween( current.y(), pixA.y(), pixB.y())))
+      {
+        retval = false;
+      }
+    }
+    return retval;
   }
 
   //-----------------------------------------------------------------------------------------------
diff --git a/Code/Mantid/MantidQt/SliceViewer/src/LineViewer.cpp b/Code/Mantid/MantidQt/SliceViewer/src/LineViewer.cpp
index 6201328b653383db637246c2ac271eaec7b90a8d..870bac3ab286739ca6ab1bc79b56db351b2c8c27 100644
--- a/Code/Mantid/MantidQt/SliceViewer/src/LineViewer.cpp
+++ b/Code/Mantid/MantidQt/SliceViewer/src/LineViewer.cpp
@@ -86,8 +86,8 @@ void setThicknessUsingDimensionInfo(IMDWorkspace_sptr ws, size_t dimIndex,
 
 LineViewer::LineViewer(QWidget *parent)
     : QWidget(parent), m_planeWidth(0), m_numBins(100), m_allDimsFree(false),
-      m_freeDimX(0), m_freeDimY(1), m_fixedBinWidthMode(false),
-      m_fixedBinWidth(0.1), m_binWidth(0.1) {
+      m_freeDimX(0), m_freeDimY(1), m_initFreeDimX(-1), m_initFreeDimY(-1),
+      m_fixedBinWidthMode(false), m_fixedBinWidth(0.1), m_binWidth(0.1) {
   ui.setupUi(this);
 
   // Other setup
@@ -314,75 +314,77 @@ void LineViewer::readTextboxes() {
  */
 IAlgorithm_sptr
 LineViewer::applyMatrixWorkspace(Mantid::API::MatrixWorkspace_sptr ws) {
-  try {
-    if (getPlanarWidth() <= 0)
-      throw std::runtime_error("Planar Width must be > 0");
+  // (half-width in the plane)
+  const double planeWidth = getPlanarWidth();
+
+  if (planeWidth <= 0) {
+    g_log.error() << "Planar width must be > 0" << std::endl;
+    g_log.error() << "Planar width is: " << planeWidth << std::endl;
+    return IAlgorithm_sptr();
+  }
+
+  // Length of the line
+  const double lengthX = m_end[m_freeDimX] - m_start[m_freeDimX];
+  const double lengthY = m_end[m_freeDimY] - m_start[m_freeDimY];
+  const bool lineIsHorizontal = fabs(lengthX) > fabs(lengthY);
+  const bool axesAreFlipped = m_freeDimX == m_initFreeDimY &&
+    m_freeDimY == m_initFreeDimX;
+  // True when (NOT lineIsHorizontal) XOR axesAreFlipped
+  // The truth table simplifies down to lineIsHorizontal == axesAreFlipped
+  const bool shouldTranspose = lineIsHorizontal == axesAreFlipped;
+
+  IAlgorithm_sptr alg = AlgorithmManager::Instance().createUnmanaged("Rebin2D");
+  alg->initialize();
 
-    IAlgorithm_sptr alg =
-        AlgorithmManager::Instance().createUnmanaged("Rebin2D");
-    alg->initialize();
+  try {
     alg->setProperty("InputWorkspace", ws);
     alg->setPropertyValue("OutputWorkspace", m_integratedWSName);
-    if (ws->id() == "RebinnedOutput") {
-      alg->setProperty("UseFractionalArea", true);
-    } else {
-      alg->setProperty("UseFractionalArea", false);
-    }
-    // (half-width in the plane)
-    double planeWidth = this->getPlanarWidth();
-    // Length of the line
-    double dx = m_end[m_freeDimX] - m_start[m_freeDimX];
-    double dy = m_end[m_freeDimY] - m_start[m_freeDimY];
-    size_t numBins = m_numBins;
-
-    if (fabs(dx) > fabs(dy)) {
+    alg->setProperty("UseFractionalArea", (ws->id() == "RebinnedOutput"));
+    alg->setProperty("Transpose", shouldTranspose);
+
+    // Swap the axes if the line is NOT horizontal (i.e. vertical)
+    const int axisX = lineIsHorizontal ? m_freeDimX : m_freeDimY;
+    const int axisY = lineIsHorizontal ? m_freeDimY : m_freeDimX;
+
+    // If necessary, swap the start and end around so that start < end
+    const bool swapEnds = m_start[axisX] > m_end[axisX];
+    const double start = swapEnds ? m_end[axisX] : m_start[axisX];
+    const double end = swapEnds ? m_start[axisX] : m_end[axisX];
+
+    // Calculate the bin width
+    const double binWidth = (end - start) / static_cast<double>(m_numBins);
+
+    // The start value of the opposite axis
+    const double vertical = m_start[axisY];
+
+    // Output stringstreams for the binning
+    std::stringstream axis1Binning, axis2Binning;
+
+    if (binWidth <= 0)
+      return IAlgorithm_sptr();
+
+    axis1Binning << start << "," << binWidth << "," << end;
+    axis2Binning << (vertical - planeWidth) << "," << (planeWidth * 2) << ","
+                 << (vertical + planeWidth);
+
+    // If the line is vertical we swap the axes binning order
+    if (!shouldTranspose) {
       // Horizontal line
-      double start = m_start[m_freeDimX];
-      double end = m_end[m_freeDimX];
-      if (end < start) {
-        start = end;
-        end = m_start[m_freeDimX];
-      }
-      double vertical = m_start[m_freeDimY];
-      double binWidth = (end - start) / static_cast<double>(numBins);
-      if (binWidth <= 0)
-        return IAlgorithm_sptr();
-
-      alg->setPropertyValue("Axis1Binning", Strings::toString(start) + "," +
-                                                Strings::toString(binWidth) +
-                                                "," + Strings::toString(end));
-      alg->setPropertyValue("Axis2Binning",
-                            Strings::toString(vertical - planeWidth) + "," +
-                                Strings::toString(planeWidth * 2) + "," +
-                                Strings::toString(vertical + planeWidth));
-      alg->setProperty("Transpose", false);
+      alg->setPropertyValue("Axis1Binning", axis1Binning.str());
+      alg->setPropertyValue("Axis2Binning", axis2Binning.str());
     } else {
       // Vertical line
-      double start = m_start[m_freeDimY];
-      double end = m_end[m_freeDimY];
-      if (end < start) {
-        start = end;
-        end = m_start[m_freeDimY];
-      }
-      double binWidth = (end - start) / static_cast<double>(numBins);
-
-      double vertical = m_start[m_freeDimX];
-      alg->setPropertyValue("Axis1Binning",
-                            Strings::toString(vertical - planeWidth) + "," +
-                                Strings::toString(planeWidth * 2) + "," +
-                                Strings::toString(vertical + planeWidth));
-      alg->setPropertyValue("Axis2Binning", Strings::toString(start) + "," +
-                                                Strings::toString(binWidth) +
-                                                "," + Strings::toString(end));
-      alg->setProperty("Transpose", true);
+      alg->setPropertyValue("Axis1Binning", axis2Binning.str());
+      alg->setPropertyValue("Axis2Binning", axis1Binning.str());
     }
-    return alg;
   } catch (std::exception &e) {
     // Log the error
     g_log.error() << "Invalid property passed to Rebin2D:" << std::endl;
     g_log.error() << e.what() << std::endl;
     return IAlgorithm_sptr();
   }
+
+  return alg;
 }
 
 //----------------------------------------------------------------------------------------
@@ -643,6 +645,8 @@ bool LineViewer::getFixedBinWidthMode() const { return m_fixedBinWidthMode; }
 void LineViewer::setWorkspace(Mantid::API::IMDWorkspace_sptr ws) {
   if (!ws)
     throw std::runtime_error("LineViewer::setWorkspace(): Invalid workspace.");
+  m_initFreeDimX = -1;
+  m_initFreeDimY = -1;
   m_ws = ws;
   m_thickness = VMD(ws->getNumDims());
   createDimensionWidgets();
@@ -732,6 +736,12 @@ void LineViewer::setFreeDimensions(bool all, int dimX, int dimY) {
   if (dimY < 0 || dimY >= nd)
     throw std::runtime_error("LineViewer::setFreeDimensions(): Free Y "
                              "dimension index is out of range.");
+
+  if(m_initFreeDimX < 0)
+    m_initFreeDimX = int(dimX);
+  if(m_initFreeDimY < 0)
+    m_initFreeDimY = int(dimY);
+
   m_allDimsFree = all;
   m_freeDimX = dimX;
   m_freeDimY = dimY;
@@ -744,6 +754,11 @@ void LineViewer::setFreeDimensions(bool all, int dimX, int dimY) {
  * @param dimY :: index of the Y-dimension of the plane
  */
 void LineViewer::setFreeDimensions(size_t dimX, size_t dimY) {
+  if(m_initFreeDimX < 0)
+    m_initFreeDimX = int(dimX);
+  if(m_initFreeDimY < 0)
+    m_initFreeDimY = int(dimY);
+
   m_allDimsFree = false;
   m_freeDimX = int(dimX);
   m_freeDimY = int(dimY);
diff --git a/Code/Mantid/MantidQt/SliceViewer/src/SliceViewer.cpp b/Code/Mantid/MantidQt/SliceViewer/src/SliceViewer.cpp
index facd7c614295268a10843406af5671d486025864..21ac4ff3106b0a6552597b1afe33f7fb352b9eed 100644
--- a/Code/Mantid/MantidQt/SliceViewer/src/SliceViewer.cpp
+++ b/Code/Mantid/MantidQt/SliceViewer/src/SliceViewer.cpp
@@ -68,19 +68,18 @@ using MantidQt::API::AlgorithmRunner;
 namespace MantidQt {
 namespace SliceViewer {
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Constructor */
 SliceViewer::SliceViewer(QWidget *parent)
     : QWidget(parent), m_ws(), m_firstWorkspaceOpen(false), m_dimensions(),
       m_data(NULL), m_X(), m_Y(), m_dimX(0), m_dimY(1), m_logColor(false),
       m_fastRender(true), m_rebinMode(false), m_rebinLocked(true),
-      m_mdSettings(new MantidQt::API::MdSettings()),
-      m_logger("SliceViewer"),
+      m_mdSettings(new MantidQt::API::MdSettings()), m_logger("SliceViewer"),
       m_peaksPresenter(boost::make_shared<CompositePeaksPresenter>(this)),
       m_proxyPeaksPresenter(
-      boost::make_shared<ProxyCompositePeaksPresenter>(m_peaksPresenter)),
-      m_peaksSliderWidget(NULL){
-      
+          boost::make_shared<ProxyCompositePeaksPresenter>(m_peaksPresenter)),
+      m_peaksSliderWidget(NULL) {
+
   ui.setupUi(this);
 
   m_inf = std::numeric_limits<double>::infinity();
@@ -118,10 +117,10 @@ SliceViewer::SliceViewer(QWidget *parent)
 
   initZoomer();
 
-  //hide unused buttons
-  ui.btnZoom->hide();  // hidden for a long time
-  ui.btnRebinLock->hide();  // now replaced by auto rebin mode
-  //ui.btnClearLine->hide();  // turning off line mode now removes line
+  // hide unused buttons
+  ui.btnZoom->hide();      // hidden for a long time
+  ui.btnRebinLock->hide(); // now replaced by auto rebin mode
+  // ui.btnClearLine->hide();  // turning off line mode now removes line
 
   // ----------- Toolbar button signals ----------------
   QObject::connect(ui.btnResetZoom, SIGNAL(clicked()), this, SLOT(resetZoom()));
@@ -169,7 +168,7 @@ SliceViewer::SliceViewer(QWidget *parent)
   this->setAcceptDrops(true);
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /// Destructor
 SliceViewer::~SliceViewer() {
   saveSettings();
@@ -177,21 +176,20 @@ SliceViewer::~SliceViewer() {
   // Don't delete Qt objects, I think these are auto-deleted
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Load QSettings from .ini-type files */
 void SliceViewer::loadSettings() {
   QSettings settings;
   settings.beginGroup("Mantid/SliceViewer");
   bool scaleType = (bool)settings.value("LogColorScale", 0).toInt();
 
-  //Load Colormap. If the file is invalid the default stored colour map is used. If the 
-  // user selected a unified color map for the SliceViewer and the VSI, then this is loaded.
-  if (m_mdSettings != NULL && m_mdSettings->getUsageGeneralMdColorMap())
-  {
+  // Load Colormap. If the file is invalid the default stored colour map is
+  // used.
+  // If the user selected a unified color map for the SliceViewer and the VSI,
+  // then this is loaded.
+  if (m_mdSettings != NULL && m_mdSettings->getUsageGeneralMdColorMap()) {
     m_currentColorMapFile = m_mdSettings->getGeneralMdColorMapFile();
-  }
-  else
-  {
+  } else {
     m_currentColorMapFile = settings.value("ColormapFile", "").toString();
   }
 
@@ -213,7 +211,7 @@ void SliceViewer::loadSettings() {
   settings.endGroup();
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Save settings for next time. */
 void SliceViewer::saveSettings() {
   QSettings settings;
@@ -228,7 +226,7 @@ void SliceViewer::saveSettings() {
   settings.endGroup();
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Create the menus */
 void SliceViewer::initMenus() {
   // ---------------------- Build the menu bar -------------------------
@@ -274,10 +272,9 @@ void SliceViewer::initMenus() {
   connect(action, SIGNAL(triggered()), this, SLOT(resetZoom()));
   {
     QIcon icon;
-    icon.addFile(QString::fromStdString(g_iconViewFull),
-                 QSize(), QIcon::Normal, QIcon::Off);
+    icon.addFile(QString::fromStdString(g_iconViewFull), QSize(), QIcon::Normal,
+                 QIcon::Off);
     action->setIcon(icon);
-
   }
   m_menuView->addAction(action);
 
@@ -314,7 +311,7 @@ void SliceViewer::initMenus() {
   m_syncRebinLock = new SyncedCheckboxes(action, ui.btnRebinLock, true);
   connect(m_syncRebinLock, SIGNAL(toggled(bool)), this,
           SLOT(RebinLock_toggled(bool)));
-  action->setVisible(false);  //hide this action
+  action->setVisible(false); // hide this action
   m_menuView->addAction(action);
 
   action = new QAction(QPixmap(), "Rebin Current View", this);
@@ -374,9 +371,8 @@ void SliceViewer::initMenus() {
   action->setIconVisibleInMenu(true);
   {
     QIcon icon;
-    icon.addFile(
-        QString::fromStdString(g_iconZoomPlus),
-        QSize(), QIcon::Normal, QIcon::Off);
+    icon.addFile(QString::fromStdString(g_iconZoomPlus), QSize(), QIcon::Normal,
+                 QIcon::Off);
     action->setIcon(icon);
   }
   m_menuColorOptions->addAction(action);
@@ -385,8 +381,8 @@ void SliceViewer::initMenus() {
   connect(action, SIGNAL(triggered()), this, SLOT(setColorScaleAutoFull()));
   {
     QIcon icon;
-    icon.addFile(QString::fromStdString(g_iconZoomMinus),
-                 QSize(), QIcon::Normal, QIcon::Off);
+    icon.addFile(QString::fromStdString(g_iconZoomMinus), QSize(),
+                 QIcon::Normal, QIcon::Off);
     action->setIcon(icon);
   }
   m_menuColorOptions->addAction(action);
@@ -452,7 +448,7 @@ void SliceViewer::initMenus() {
   bar->addMenu(m_menuHelp);
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Intialize the zooming/panning tools */
 void SliceViewer::initZoomer() {
   //  QwtPlotZoomer * zoomer = new CustomZoomer(m_plot->canvas());
@@ -501,7 +497,7 @@ void SliceViewer::initZoomer() {
                    SLOT(showInfoAt(double, double)));
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Programmatically show/hide the controls (sliders etc)
  *
  * @param visible :: true if you want to show the controls.
@@ -510,7 +506,7 @@ void SliceViewer::showControls(bool visible) {
   ui.frmControls->setVisible(visible);
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Add (as needed) and update DimensionSliceWidget's. */
 void SliceViewer::updateDimensionSliceWidgets() {
   // Create all necessary widgets
@@ -577,7 +573,7 @@ void SliceViewer::updateDimensionSliceWidgets() {
   }
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Set the displayed workspace. Updates UI.
  *
  * @param ws :: IMDWorkspace to show.
@@ -683,7 +679,7 @@ void SliceViewer::setWorkspace(Mantid::API::IMDWorkspace_sptr ws) {
   emit changedShownDim(m_dimX, m_dimY);
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Set the workspace to view using its name.
  * The workspace should be a MDHistoWorkspace or a MDEventWorkspace,
  * with at least 2 dimensions.
@@ -704,11 +700,11 @@ void SliceViewer::setWorkspace(const QString &wsName) {
   this->setWorkspace(ws);
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** @return the workspace in the SliceViewer */
 Mantid::API::IMDWorkspace_sptr SliceViewer::getWorkspace() { return m_ws; }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Load a color map from a file
  *
  * @param filename :: file to open; empty to ask via a dialog box.
@@ -731,12 +727,11 @@ void SliceViewer::loadColorMap(QString filename) {
   this->updateDisplay();
 }
 
-//=================================================================================================
-//========================================== SLOTS
-//================================================
-//=================================================================================================
+//==============================================================================
+//================================ SLOTS =======================================
+//==============================================================================
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Automatically sets the min/max of the color scale,
  * using the limits in the entire data set of the workspace
  * (every bin, even those not currently visible).
@@ -747,7 +742,7 @@ void SliceViewer::setColorScaleAutoFull() {
   this->updateDisplay();
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Automatically sets the min/max of the color scale,
  * using the limits in the data that is currently visible
  * in the plot (only the bins in this slice and within the
@@ -759,14 +754,14 @@ void SliceViewer::setColorScaleAutoSlice() {
   this->updateDisplay();
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /// Slot called when the ColorBarWidget changes the range of colors
 void SliceViewer::colorRangeChanged() {
   m_spect->setColorMap(m_colorBar->getColorMap());
   this->updateDisplay();
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Set whether to display 0 signal as "transparent" color.
  *
  * @param transparent :: true if you want zeros to be transparent.
@@ -780,7 +775,7 @@ void SliceViewer::setTransparentZeros(bool transparent) {
   this->updateDisplay();
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /// Slot called when changing the normalization menu
 void SliceViewer::changeNormalizationNone() {
   this->setNormalization(Mantid::API::NoNormalization, true);
@@ -794,7 +789,7 @@ void SliceViewer::changeNormalizationNumEvents() {
   this->setNormalization(Mantid::API::NumEventsNormalization, true);
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Set the normalization mode for viewing the data
  *
  * @param norm :: MDNormalization enum. 0=none; 1=volume; 2=# of events
@@ -821,13 +816,13 @@ void SliceViewer::setNormalization(Mantid::API::MDNormalization norm,
     this->updateDisplay();
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** @return the current normalization */
 Mantid::API::MDNormalization SliceViewer::getNormalization() const {
   return m_data->getNormalization();
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Set the thickness (above and below the plane) for dynamic rebinning.
  *
  * @param dim :: index of the dimension to adjust
@@ -845,7 +840,7 @@ void SliceViewer::setRebinThickness(int dim, double thickness) {
   m_dimWidgets[dim]->setThickness(thickness);
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Set the number of bins for dynamic rebinning.
  *
  * @param xBins :: number of bins in the viewed X direction
@@ -860,7 +855,7 @@ void SliceViewer::setRebinNumBins(int xBins, int yBins) {
   m_dimWidgets[m_dimY]->setNumBins(yBins);
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Sets the SliceViewer in dynamic rebin mode.
  * In this mode, the current view area (see setXYLimits()) is used as the
  * limits to rebin.
@@ -877,22 +872,22 @@ void SliceViewer::setRebinMode(bool mode, bool locked) {
   m_syncRebinLock->toggle(locked);
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** When in dynamic rebinning mode, this refreshes the rebinned area to be the
  * currently viewed area. See setXYLimits(), setRebinNumBins(),
  * setRebinThickness()
  */
 void SliceViewer::refreshRebin() { this->rebinParamsChanged(); }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /// Slot called when the btnDoLine button is checked/unchecked
 void SliceViewer::LineMode_toggled(bool checked) {
   m_lineOverlay->setShown(checked);
-  
+
   QIcon icon;
   if (checked) {
-    icon.addFile(QString::fromStdString(g_iconCutOn),
-              QSize(), QIcon::Normal, QIcon::On);
+    icon.addFile(QString::fromStdString(g_iconCutOn), QSize(), QIcon::Normal,
+                 QIcon::On);
     ui.btnDoLine->setIcon(icon);
     QString text;
     if (m_lineOverlay->getCreationMode())
@@ -902,18 +897,17 @@ void SliceViewer::LineMode_toggled(bool checked) {
     QToolTip::showText(ui.btnDoLine->mapToGlobal(ui.btnDoLine->pos()), text,
                        this);
   }
-  if (!checked)
-  {
-    //clear the old line
+  if (!checked) {
+    // clear the old line
     clearLine();
-    icon.addFile(QString::fromStdString(g_iconCut),
-          QSize(), QIcon::Normal, QIcon::Off);
+    icon.addFile(QString::fromStdString(g_iconCut), QSize(), QIcon::Normal,
+                 QIcon::Off);
     ui.btnDoLine->setIcon(icon);
   }
   emit showLineViewer(checked);
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Toggle "line-drawing" mode (to draw 1D lines using the mouse)
  *
  * @param lineMode :: True to go into line mode, False to exit it.
@@ -922,20 +916,19 @@ void SliceViewer::toggleLineMode(bool lineMode) {
   // This should send events to start line mode
   m_syncLineMode->toggle(lineMode);
   m_lineOverlay->setCreationMode(false);
-
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /// Slot called to clear the line in the line overlay
 void SliceViewer::clearLine() {
   m_lineOverlay->reset();
   m_plot->update();
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /// Slot called when the snap to grid is checked
 void SliceViewer::SnapToGrid_toggled(bool checked) {
-  
+
   QIcon icon;
   if (checked) {
     SnapToGridDialog *dlg = new SnapToGridDialog(this);
@@ -944,25 +937,24 @@ void SliceViewer::SnapToGrid_toggled(bool checked) {
       m_lineOverlay->setSnapEnabled(true);
       m_lineOverlay->setSnapX(dlg->getSnapX());
       m_lineOverlay->setSnapY(dlg->getSnapY());
-      icon.addFile(QString::fromStdString(g_iconGridOn),
-                   QSize(), QIcon::Normal, QIcon::On);
+      icon.addFile(QString::fromStdString(g_iconGridOn), QSize(), QIcon::Normal,
+                   QIcon::On);
     } else {
       // Uncheck - the user clicked cancel
       ui.btnSnapToGrid->setChecked(false);
       m_lineOverlay->setSnapEnabled(false);
-      icon.addFile(QString::fromStdString(g_iconGrid),
-                   QSize(), QIcon::Normal, QIcon::Off);
+      icon.addFile(QString::fromStdString(g_iconGrid), QSize(), QIcon::Normal,
+                   QIcon::Off);
     }
   } else {
     m_lineOverlay->setSnapEnabled(false);
-    icon.addFile(QString::fromStdString(g_iconGrid),
-                  QSize(), QIcon::Normal, QIcon::Off);
+    icon.addFile(QString::fromStdString(g_iconGrid), QSize(), QIcon::Normal,
+                 QIcon::Off);
   }
   ui.btnSnapToGrid->setIcon(icon);
-  
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Slot called when going into or out of dynamic rebinning mode */
 void SliceViewer::RebinMode_toggled(bool checked) {
   for (size_t d = 0; d < m_dimWidgets.size(); d++)
@@ -975,8 +967,8 @@ void SliceViewer::RebinMode_toggled(bool checked) {
 
   QIcon icon;
   if (!m_rebinMode) {
-    icon.addFile(QString::fromStdString(g_iconRebin),
-                 QSize(), QIcon::Normal, QIcon::Off);
+    icon.addFile(QString::fromStdString(g_iconRebin), QSize(), QIcon::Normal,
+                 QIcon::Off);
     ui.btnRebinMode->setIcon(icon);
     // uncheck auto-rebin
     ui.btnAutoRebin->setChecked(false);
@@ -985,15 +977,15 @@ void SliceViewer::RebinMode_toggled(bool checked) {
     this->m_data->setOverlayWorkspace(m_overlayWS);
     this->updateDisplay();
   } else {
-    icon.addFile(QString::fromStdString(g_iconRebinOn),
-              QSize(), QIcon::Normal, QIcon::On);
+    icon.addFile(QString::fromStdString(g_iconRebinOn), QSize(), QIcon::Normal,
+                 QIcon::On);
     ui.btnRebinMode->setIcon(icon);
     // Start the rebin
     this->rebinParamsChanged();
   }
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Slot called when locking/unlocking the dynamically rebinned
  * overlaid workspace
  * @param checked :: DO lock the workspace in place
@@ -1005,7 +997,7 @@ void SliceViewer::RebinLock_toggled(bool checked) {
     this->rebinParamsChanged();
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /// Slot for zooming into
 void SliceViewer::zoomInSlot() { this->zoomBy(1.1); }
 
@@ -1043,7 +1035,7 @@ void SliceViewer::helpPeaksViewer() {
       QUrl(QString("http://www.mantidproject.org/") + helpPage));
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Automatically resets the zoom view to full axes.
  * This will reset the XY limits to the full range of the workspace.
  * Use zoomBy() or setXYLimits() to modify the view range.
@@ -1059,7 +1051,7 @@ void SliceViewer::resetZoom() {
   updatePeaksOverlay();
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /// SLOT to open a dialog to set the XY limits
 void SliceViewer::setXYLimitsDialog() {
   // Initialize the dialog with the current values
@@ -1077,7 +1069,7 @@ void SliceViewer::setXYLimitsDialog() {
   }
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Slot to redraw when the slice point changes */
 void SliceViewer::updateDisplaySlot(int index, double value) {
   UNUSED_ARG(index)
@@ -1088,11 +1080,11 @@ void SliceViewer::updateDisplaySlot(int index, double value) {
     this->rebinParamsChanged();
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** SLOT to open a dialog to choose a file, load a color map from that file */
 void SliceViewer::loadColorMapSlot() { this->loadColorMap(QString()); }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Grab the 2D view as an image. The image is rendered at the current window
  * size, with the color scale but without the text boxes for changing them.
  *
@@ -1122,7 +1114,7 @@ QPixmap SliceViewer::getImage() {
   return pix;
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Copy the rendered 2D image to the clipboard
  */
 void SliceViewer::copyImageToClipboard() {
@@ -1148,7 +1140,7 @@ QString SliceViewer::ensurePngExtension(const QString &fname) const {
   return res;
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Save the rendered 2D slice to an image file.
  *
  * @param filename :: full path to the file to save, including extension
@@ -1178,9 +1170,9 @@ void SliceViewer::saveImage(const QString &filename) {
   pix.save(finalName);
 }
 
-//=================================================================================================
-//=================================================================================================
-//=================================================================================================
+//==============================================================================
+//==============================================================================
+//==============================================================================
 /** Zoom in or out, keeping the center of the plot in the same position.
  *
  * @param factor :: double, if > 1 : zoom in by this factor.
@@ -1207,7 +1199,7 @@ void SliceViewer::zoomBy(double factor) {
   this->updatePeaksOverlay();
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Manually set the center of the plot, in X Y coordinates.
  * This keeps the plot the same size as previously.
  * Use setXYLimits() to modify the size of the plot by setting the X/Y edges,
@@ -1226,7 +1218,7 @@ void SliceViewer::setXYCenter(double x, double y) {
                     y + halfWidthY);
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Reset the axis and scale it
  *
  * @param axis :: int for X or Y
@@ -1237,7 +1229,7 @@ void SliceViewer::resetAxis(int axis, const IMDDimension_const_sptr &dim) {
   m_plot->setAxisTitle(axis, API::PlotAxis(*dim).title());
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /// Find the full range of values in the workspace
 void SliceViewer::findRangeFull() {
   IMDWorkspace_sptr workspace_used = m_ws;
@@ -1258,7 +1250,7 @@ void SliceViewer::findRangeFull() {
       API::SignalRange(*workspace_used, this->getNormalization()).interval();
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Find the full range of values ONLY in the currently visible
 part of the workspace */
 void SliceViewer::findRangeSlice() {
@@ -1310,7 +1302,7 @@ void SliceViewer::findRangeSlice() {
     m_colorRangeSlice = m_colorRangeFull;
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Slot to show the mouse info at the mouse position
  *
  * @param x :: position of the mouse in plot coords
@@ -1354,7 +1346,7 @@ void SliceViewer::showInfoAt(double x, double y) {
   }
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Update the 2D plot using all the current controls settings */
 void SliceViewer::updateDisplay(bool resetAxes) {
   if (!m_ws)
@@ -1433,7 +1425,7 @@ void SliceViewer::updateDisplay(bool resetAxes) {
   emit changedSlicePoint(m_slicePoint);
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** The user changed the shown dimension somewhere.
  *
  * @param index :: index of the dimension
@@ -1467,10 +1459,9 @@ void SliceViewer::changedShownDim(int index, int dim, int oldDim) {
   emit changedShownDim(m_dimX, m_dimY);
 }
 
-//=================================================================================================
-//========================================== PYTHON METHODS
-//=======================================
-//=================================================================================================
+//==============================================================================
+//================================ PYTHON METHODS ==============================
+//==============================================================================
 
 /** @return the name of the workspace selected, or a blank string
  * if no workspace is set.
@@ -1482,7 +1473,7 @@ QString SliceViewer::getWorkspaceName() const {
     return QString();
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** @return the index of the dimension that is currently
  * being shown as the X axis of the plot.
  */
@@ -1493,7 +1484,7 @@ int SliceViewer::getDimX() const { return int(m_dimX); }
  */
 int SliceViewer::getDimY() const { return int(m_dimY); }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Set the index of the dimensions that will be shown as
  * the X and Y axis of the plot.
  * You cannot set both axes to be the same.
@@ -1531,7 +1522,7 @@ void SliceViewer::setXYDim(int indexX, int indexY) {
   emit changedShownDim(m_dimX, m_dimY);
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Set the dimensions that will be shown as the X and Y axes
  *
  * @param dimX :: name of the X dimension. Must match the workspace dimension
@@ -1548,7 +1539,7 @@ void SliceViewer::setXYDim(const QString &dimX, const QString &dimY) {
   this->setXYDim(indexX, indexY);
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Sets the slice point in the given dimension:
  * that is, what is the position of the plane in that dimension
  *
@@ -1565,7 +1556,7 @@ void SliceViewer::setSlicePoint(int dim, double value) {
   m_dimWidgets[dim]->setSlicePoint(value);
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Returns the slice point in the given dimension
  *
  * @param dim :: index of the dimension
@@ -1580,7 +1571,7 @@ double SliceViewer::getSlicePoint(int dim) const {
   return m_slicePoint[dim];
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Sets the slice point in the given dimension:
  * that is, what is the position of the plane in that dimension
  *
@@ -1597,7 +1588,7 @@ void SliceViewer::setSlicePoint(const QString &dim, double value) {
   return this->setSlicePoint(index, value);
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Returns the slice point in the given dimension
  *
  * @param dim :: name of the dimension
@@ -1612,7 +1603,7 @@ double SliceViewer::getSlicePoint(const QString &dim) const {
   return this->getSlicePoint(index);
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Set the color scale limits and log mode via a method call.
  *
  * @param min :: minimum value corresponding to the lowest color on the map
@@ -1632,7 +1623,7 @@ void SliceViewer::setColorScale(double min, double max, bool log) {
   this->colorRangeChanged();
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Set the "background" color to use in the color map. Default is white.
  *
  * This is the color that is shown when:
@@ -1651,7 +1642,7 @@ void SliceViewer::setColorMapBackground(int r, int g, int b) {
   this->colorRangeChanged();
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Set the minimum value corresponding to the lowest color on the map
  *
  * @param min :: minimum value corresponding to the lowest color on the map
@@ -1662,7 +1653,7 @@ void SliceViewer::setColorScaleMin(double min) {
   this->setColorScale(min, this->getColorScaleMax(), this->getColorScaleLog());
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Set the maximum value corresponding to the lowest color on the map
  *
  * @param max :: maximum value corresponding to the lowest color on the map
@@ -1673,7 +1664,7 @@ void SliceViewer::setColorScaleMax(double max) {
   this->setColorScale(this->getColorScaleMin(), max, this->getColorScaleLog());
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Set whether the color scale is logarithmic
  *
  * @param log :: true for a log color scale, false for linear
@@ -1684,7 +1675,7 @@ void SliceViewer::setColorScaleLog(bool log) {
   this->setColorScale(this->getColorScaleMin(), this->getColorScaleMax(), log);
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** @return the value that corresponds to the lowest color on the color map */
 double SliceViewer::getColorScaleMin() const {
   return m_colorBar->getMinimum();
@@ -1698,7 +1689,7 @@ double SliceViewer::getColorScaleMax() const {
 /** @return True if the color scale is in logarithmic mode */
 bool SliceViewer::getColorScaleLog() const { return m_colorBar->getLog(); }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Sets whether the image should be rendered in "fast" mode, where
  * the workspace's resolution is used to guess how many pixels to render.
  *
@@ -1725,7 +1716,7 @@ void SliceViewer::setFastRender(bool fast) {
  */
 bool SliceViewer::getFastRender() const { return m_fastRender; }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Set the limits in X and Y to be shown in the plot.
  * The X and Y values are in the units of their respective dimensions.
  * You can change the mapping from X/Y in the plot to specific
@@ -1749,7 +1740,7 @@ void SliceViewer::setXYLimits(double xleft, double xright, double ybottom,
   updatePeaksOverlay();
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** @return Returns the [left, right] limits of the view in the X axis. */
 QwtDoubleInterval SliceViewer::getXLimits() const {
   return m_plot->axisScaleDiv(m_spect->xAxis())->interval();
@@ -1760,7 +1751,7 @@ QwtDoubleInterval SliceViewer::getYLimits() const {
   return m_plot->axisScaleDiv(m_spect->yAxis())->interval();
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Opens a workspace and sets the view and slice points
  * given the XML from the MultiSlice view in XML format.
  *
@@ -1944,7 +1935,7 @@ void SliceViewer::openFromXML(const QString &xml) {
     this->setSlicePoint(d, slicePoint[d]);
 }
 
-//------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** This slot is called when the dynamic rebinning parameters are changed.
  * It recalculates the dynamically rebinned workspace and plots it
  */
@@ -2017,7 +2008,7 @@ void SliceViewer::rebinParamsChanged() {
   // complete.
 }
 
-//--------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Slot called by the observer when the BinMD call has completed.
  * This returns the execution to the main GUI thread, and
  * so can update the GUI.
@@ -2110,10 +2101,10 @@ void SliceViewer::disablePeakOverlays() {
   m_peaksPresenter->clear();
   emit showPeaksViewer(false);
   m_menuPeaks->setEnabled(false);
-  
+
   QIcon icon;
-  icon.addFile(QString::fromStdString(g_iconPeakList),
-                QSize(), QIcon::Normal, QIcon::Off);
+  icon.addFile(QString::fromStdString(g_iconPeakList), QSize(), QIcon::Normal,
+               QIcon::Off);
   ui.btnPeakOverlay->setIcon(icon);
   ui.btnPeakOverlay->setChecked(false);
 }
@@ -2188,10 +2179,10 @@ SliceViewer::setPeaksWorkspaces(const QStringList &list) {
   updatePeakOverlaySliderWidget();
   emit showPeaksViewer(true);
   m_menuPeaks->setEnabled(true);
-  
+
   QIcon icon;
-  icon.addFile(QString::fromStdString(g_iconPeakList),
-                 QSize(), QIcon::Normal, QIcon::Off);
+  icon.addFile(QString::fromStdString(g_iconPeakList), QSize(), QIcon::Normal,
+               QIcon::Off);
   ui.btnPeakOverlay->setIcon(icon);
   ui.btnPeakOverlay->setChecked(true);
   return m_proxyPeaksPresenter.get();
@@ -2204,8 +2195,9 @@ Allow user to choose a suitable input peaks workspace
 
 */
 void SliceViewer::peakOverlay_clicked() {
-  MantidQt::MantidWidgets::SelectWorkspacesDialog dlg(this, "PeaksWorkspace", "Remove All");
-  
+  MantidQt::MantidWidgets::SelectWorkspacesDialog dlg(this, "PeaksWorkspace",
+                                                      "Remove All");
+
   int ret = dlg.exec();
   if (ret == QDialog::Accepted) {
     QStringList list = dlg.getSelectedNames();
@@ -2215,18 +2207,18 @@ void SliceViewer::peakOverlay_clicked() {
     }
   }
   if (ret == MantidQt::MantidWidgets::SelectWorkspacesDialog::CustomButton) {
-        disablePeakOverlays();
+    disablePeakOverlays();
   }
   QIcon icon;
-  if (m_peaksPresenter->size()>0)  {
-    icon.addFile(QString::fromStdString(g_iconPeakListOn),
-                   QSize(), QIcon::Normal, QIcon::On);
+  if (m_peaksPresenter->size() > 0) {
+    icon.addFile(QString::fromStdString(g_iconPeakListOn), QSize(),
+                 QIcon::Normal, QIcon::On);
     ui.btnPeakOverlay->setIcon(icon);
     ui.btnPeakOverlay->setChecked(true);
-  }  else {
+  } else {
 
-    icon.addFile(QString::fromStdString(g_iconPeakList),
-                   QSize(), QIcon::Normal, QIcon::Off);
+    icon.addFile(QString::fromStdString(g_iconPeakList), QSize(), QIcon::Normal,
+                 QIcon::Off);
     ui.btnPeakOverlay->setIcon(icon);
     ui.btnPeakOverlay->setChecked(false);
   }
diff --git a/Code/Mantid/MantidQt/SliceViewer/src/SliceViewerWindow.cpp b/Code/Mantid/MantidQt/SliceViewer/src/SliceViewerWindow.cpp
index b70f51e707f8085010a74e25ffa8d48da93c063f..a67032e8314063c4804156ae0645af117c896cc0 100644
--- a/Code/Mantid/MantidQt/SliceViewer/src/SliceViewerWindow.cpp
+++ b/Code/Mantid/MantidQt/SliceViewer/src/SliceViewerWindow.cpp
@@ -135,7 +135,7 @@ SliceViewerWindow::SliceViewerWindow(const QString &wsName,
 
 SliceViewerWindow::~SliceViewerWindow() {}
 
-//------------------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Build the menus */
 void SliceViewerWindow::initMenus() {
   // Make File->Close() close the window
@@ -143,7 +143,7 @@ void SliceViewerWindow::initMenus() {
           SLOT(close()));
 }
 
-//------------------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Get the SliceViewer widget inside the SliceViewerWindow.
  * This is the main widget for controlling the 2D views
  * and slice points.
@@ -154,7 +154,7 @@ MantidQt::SliceViewer::SliceViewer *SliceViewerWindow::getSlicer() {
   return m_slicer;
 }
 
-//------------------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Get the LineViewer widget inside the SliceViewerWindow.
  * This is the widget for controlling the 1D line integration
  * settings.
@@ -165,31 +165,31 @@ MantidQt::SliceViewer::LineViewer *SliceViewerWindow::getLiner() {
   return m_liner;
 }
 
-//------------------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** @return the label that was attached to this SliceViewerWindow's title */
 const QString &SliceViewerWindow::getLabel() const { return m_label; }
 
-//------------------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 void SliceViewerWindow::resizeEvent(QResizeEvent * /*event*/) {
   //  if (m_liner->isVisible())
-    //    m_lastLinerWidth = m_liner->width();
+  //    m_lastLinerWidth = m_liner->width();
 }
 
-//------------------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Slot to close the window */
 void SliceViewerWindow::closeWindow() {
   // askOnCloseEvent(false); //(MdiSubWindow)
   close();
 }
 
-//------------------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Slot to replace the workspace being looked at. */
 void SliceViewerWindow::updateWorkspace() {
   m_liner->setWorkspace(m_ws);
   m_slicer->setWorkspace(m_ws);
 }
 
-//------------------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Slot called when the SliceViewer changes which workspace
  * is being viewed. */
 void SliceViewerWindow::slicerWorkspaceChanged() {
@@ -198,7 +198,7 @@ void SliceViewerWindow::slicerWorkspaceChanged() {
   m_liner->setWorkspace(m_ws);
 }
 
-//------------------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Slot called when the LineViewer is setting a fixed bin width mode
  *
  * @param fixed :: True for fixed bin width
@@ -214,7 +214,7 @@ void SliceViewerWindow::lineViewer_changedFixedBinWidth(bool fixed,
     m_slicer->getLineOverlay()->setSnapLength(0.0);
 }
 
-//------------------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Show or hide the LineViewer widget (on the right of the SliceViewer)
  *
  * @param visible :: True to show the LineViewer widget.
@@ -261,7 +261,7 @@ void SliceViewerWindow::showLineViewer(bool visible) {
   this->setUpdatesEnabled(true);
 }
 
-//------------------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Show or hide the LineViewer widget (on the right of the SliceViewer)
  *
  * @param visible :: True to show the PeaksViewer widget.
@@ -292,8 +292,7 @@ void SliceViewerWindow::showPeaksViewer(bool visible) {
     // Shrink the window to exclude the liner
     int w =
         this->width() - (m_peaksViewer->width() + m_splitter->handleWidth());
-    if (m_peaksViewer->width() > 0)
-    {
+    if (m_peaksViewer->width() > 0) {
       m_lastPeaksViewerWidth = m_peaksViewer->width();
     }
     m_peaksViewer->hide();
@@ -313,14 +312,14 @@ void SliceViewerWindow::showPeaksViewer(bool visible) {
   this->setUpdatesEnabled(true);
 }
 
-//------------------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Special slot called to resize the window
  * after some events have been processed. */
 void SliceViewerWindow::resizeWindow() {
   this->resize(m_desiredWidth, this->height());
 }
 
-//------------------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Using the positions from the LineOverlay, set the values in the LineViewer,
  * but don't update view. */
 void SliceViewerWindow::setLineViewerValues(QPointF start2D, QPointF end2D,
@@ -336,7 +335,7 @@ void SliceViewerWindow::setLineViewerValues(QPointF start2D, QPointF end2D,
   m_liner->setPlanarWidth(width);
 }
 
-//------------------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Slot called when the line overlay position is changing (being dragged) */
 void SliceViewerWindow::lineChanging(QPointF start2D, QPointF end2D,
                                      double width) {
@@ -388,7 +387,7 @@ void SliceViewerWindow::changePlanarWidth(double width) {
   m_slicer->getLineOverlay()->update();
 }
 
-//------------------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Signal to close this window if the workspace has just been deleted */
 void SliceViewerWindow::preDeleteHandle(
     const std::string &wsName,
@@ -409,7 +408,7 @@ void SliceViewerWindow::preDeleteHandle(
   }
 }
 
-//------------------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /**
  * @brief After replace handle
  * @param oldName
@@ -419,21 +418,22 @@ void SliceViewerWindow::renameHandle(const std::string &oldName,
                                      const std::string &newName) {
 
   if (oldName == m_wsName) {
-      IMDWorkspace_sptr new_md_ws = boost::dynamic_pointer_cast<IMDWorkspace>(
-                  AnalysisDataService::Instance().retrieve(newName));
+    IMDWorkspace_sptr new_md_ws = boost::dynamic_pointer_cast<IMDWorkspace>(
+        AnalysisDataService::Instance().retrieve(newName));
     if (new_md_ws) {
       m_ws = new_md_ws;
       emit needToUpdate();
     }
 
   } else {
-        // Remove any legacy workspace widgets + presenters bearing the old name. Remember, naming is a deep copy process. So the old name is the only reference we have.
-        m_peaksViewer->removePeaksWorkspace(oldName);
+    // Remove any legacy workspace widgets + presenters bearing the old name.
+    // Remember, naming is a deep copy process. So the old name is the only
+    // reference we have.
+    m_peaksViewer->removePeaksWorkspace(oldName);
   }
 }
 
-
-//------------------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 /** Signal that the workspace being looked at was just replaced with a different
  * one */
 void SliceViewerWindow::afterReplaceHandle(
diff --git a/Code/Mantid/MantidQt/SpectrumViewer/src/SVConnections.cpp b/Code/Mantid/MantidQt/SpectrumViewer/src/SVConnections.cpp
index faca780fd6f2f5e25a51a170cdee0574c803efe4..36372496030a35a3d1f347762b99b1fb3498c518 100644
--- a/Code/Mantid/MantidQt/SpectrumViewer/src/SVConnections.cpp
+++ b/Code/Mantid/MantidQt/SpectrumViewer/src/SVConnections.cpp
@@ -3,6 +3,7 @@
 
 #include <QDesktopServices>
 
+#include "MantidQtAPI/HelpWindow.h"
 #include "MantidQtAPI/MantidColorMap.h"
 
 #include "MantidQtSpectrumViewer/SVConnections.h"
@@ -730,7 +731,7 @@ void SVConnections::showColorScale( std::vector<QRgb> & positiveColorTable,
  */
 void SVConnections::openOnlineHelp()
 {
-  QDesktopServices::openUrl(QUrl("http://www.mantidproject.org/MantidPlot:_ImageViewer"));
+  MantidQt::API::HelpWindow::showCustomInterface(NULL, QString("SpectrumViewer"));
 }
 
 } // namespace SpectrumView
diff --git a/Code/Mantid/Testing/Data/DocTest/SXD23767.peaks.md5 b/Code/Mantid/Testing/Data/DocTest/SXD23767.peaks.md5
new file mode 100644
index 0000000000000000000000000000000000000000..2e5f1e9a1d8987af739d7d71be9aeccc2a29cc41
--- /dev/null
+++ b/Code/Mantid/Testing/Data/DocTest/SXD23767.peaks.md5
@@ -0,0 +1 @@
+4ee45970b3107254198f7b132fbfacf9
diff --git a/Code/Mantid/Testing/Data/SystemTest/REF_L_124168_event.nxs.md5 b/Code/Mantid/Testing/Data/SystemTest/REF_L_124168_event.nxs.md5
new file mode 100644
index 0000000000000000000000000000000000000000..36da1f53fca763203e3958674a20f5e39ec0d9ef
--- /dev/null
+++ b/Code/Mantid/Testing/Data/SystemTest/REF_L_124168_event.nxs.md5
@@ -0,0 +1 @@
+2b1c0e651eeaa364f44f34e33d34ae40
diff --git a/Code/Mantid/Testing/Data/SystemTest/REF_L_124169_event.nxs.md5 b/Code/Mantid/Testing/Data/SystemTest/REF_L_124169_event.nxs.md5
new file mode 100644
index 0000000000000000000000000000000000000000..9a83b2cbfb311bca83ac5b9a5bc32e1e66a0a09d
--- /dev/null
+++ b/Code/Mantid/Testing/Data/SystemTest/REF_L_124169_event.nxs.md5
@@ -0,0 +1 @@
+07307d1436f2755c64eea998e915fab3
diff --git a/Code/Mantid/Testing/Data/SystemTest/REF_L_124170_event.nxs.md5 b/Code/Mantid/Testing/Data/SystemTest/REF_L_124170_event.nxs.md5
new file mode 100644
index 0000000000000000000000000000000000000000..ba915f5311e0ecbd4cb46b211e47e560f71c16a7
--- /dev/null
+++ b/Code/Mantid/Testing/Data/SystemTest/REF_L_124170_event.nxs.md5
@@ -0,0 +1 @@
+68151e99b3c9812dd2c2e9cc06964f09
diff --git a/Code/Mantid/Testing/Data/SystemTest/REF_L_124171_event.nxs.md5 b/Code/Mantid/Testing/Data/SystemTest/REF_L_124171_event.nxs.md5
new file mode 100644
index 0000000000000000000000000000000000000000..30de34da5b17a9b3a32caeb5a25d3c4bb1936800
--- /dev/null
+++ b/Code/Mantid/Testing/Data/SystemTest/REF_L_124171_event.nxs.md5
@@ -0,0 +1 @@
+66254999c0f6bbc6a79bee8db4f6b4c6
diff --git a/Code/Mantid/Testing/Data/SystemTest/REF_L_124172_event.nxs.md5 b/Code/Mantid/Testing/Data/SystemTest/REF_L_124172_event.nxs.md5
new file mode 100644
index 0000000000000000000000000000000000000000..594584f765708d1d11b30925b893e3b76f19042c
--- /dev/null
+++ b/Code/Mantid/Testing/Data/SystemTest/REF_L_124172_event.nxs.md5
@@ -0,0 +1 @@
+bf5ac23fae900efaec8445050c16ec3f
diff --git a/Code/Mantid/Testing/Data/SystemTest/poldi2015n000977.hdf.md5 b/Code/Mantid/Testing/Data/SystemTest/poldi2015n000977.hdf.md5
new file mode 100644
index 0000000000000000000000000000000000000000..b2cd5dc1876b7706540855bbffbf50001d2408c5
--- /dev/null
+++ b/Code/Mantid/Testing/Data/SystemTest/poldi2015n000977.hdf.md5
@@ -0,0 +1 @@
+ba219b53856c045827563542e4c40ad1
diff --git a/Code/Mantid/Testing/SystemTests/scripts/mantidinstaller.py b/Code/Mantid/Testing/SystemTests/scripts/mantidinstaller.py
index 1723b34f29ff4bbf7646aada3fbae00aebdd3839..42c4277f17ceac37c14752898322b14ca7f4925b 100644
--- a/Code/Mantid/Testing/SystemTests/scripts/mantidinstaller.py
+++ b/Code/Mantid/Testing/SystemTests/scripts/mantidinstaller.py
@@ -82,14 +82,14 @@ def run(cmd):
     """Run a command in a subprocess"""
     try:
         p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
-        out = p.communicate()[0]
+        stdout, stderr = p.communicate()
         if p.returncode != 0:
-            raise Exception('Returned with code '+str(p.returncode)+'\n'+out)
+            raise Exception('Returned with code '+str(p.returncode)+'\n'+ stdout)
     except Exception,err:
         log('Error in subprocess %s:\n' % str(err))
         raise
-    log(out)
-    return out
+    log(stdout)
+    return stdout
     
 
 class MantidInstaller(object):
@@ -206,13 +206,17 @@ class RPMInstaller(MantidInstaller):
     def do_install(self):
         """Uses yum to run the install. Current user must be in sudoers
         """
+        try:
+            run('sudo rpm -e ' + self.mantidInstaller)
+        except Exception:
+            # Assume it doesn't exist
+            pass
         try:
             run('sudo yum -y install ' + self.mantidInstaller)
         except Exception, exc:
             # This reports an error if the same package is already installed
-            if 'is already installed' in str(exc):
+            if 'does not update installed package' in str(exc):
                 log("Current version is up-to-date, continuing.\n")
-                pass
             else:
                 raise
 
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/BuildSQWTest.py b/Code/Mantid/Testing/SystemTests/tests/analysis/BuildSQWTest.py
index f97d908b12a552b0c2597d5871c8498bddf98e5d..99e7da5989780b097de968f70f4799123c0a91ff 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/BuildSQWTest.py
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/BuildSQWTest.py
@@ -88,7 +88,7 @@ class BuildSQWTest(stresstesting.MantidStressTest):
 
         # Do the final merge
         sqw_file = os.path.join(config["defaultsave.directory"],"BuildSQWTestCurrent.nxs")
-        finalSQW = MergeMDFiles(",".join(self._created_files),OutputFilename=sqw_file,Parallel='0')
+        dummy_finalSQW = MergeMDFiles(",".join(self._created_files),OutputFilename=sqw_file,Parallel='0')
         self._created_files.append(sqw_file)
 
     def validate(self):
@@ -101,14 +101,14 @@ class BuildSQWTest(stresstesting.MantidStressTest):
         for filename in self._created_files:
             try:
                 os.remove(filename)
-            except OSError,exc:
+            except OSError:
                 mantid.logger.warning("Unable to remove created file '%s'" % filename)
 
 class LoadSQW_FileBasedTest(BuildSQWTest):
     """ The test checks loading MD workspace from SQW file when target file is file based"""
 
     def __init__(self):
-
+        super(LoadSQW_FileBasedTest, self).__init__()
         self._input_data = ["Test22meV2f.sqw","Test22meVMD.nxs"]
 
     def runTest(self):
@@ -116,7 +116,7 @@ class LoadSQW_FileBasedTest(BuildSQWTest):
         MDws_file = os.path.join(config["defaultsave.directory"],"LoadSQWTestFileBased.nxs")
         sqw_file = os.path.join(self._input_location,self._input_data[0])
 
-        wsMD=LoadSQW(Filename=sqw_file, OutputFilename=MDws_file)
+        dummy_wsMD=LoadSQW(Filename=sqw_file, OutputFilename=MDws_file)
 
         self._created_files=MDws_file
 
@@ -127,7 +127,7 @@ class LoadSQW_FileBasedTest(BuildSQWTest):
         Reference=LoadMD(Filename=ref_file, FileBackEnd=True, Memory=100)
         rez = CompareMDWorkspaces(Workspace1="wsMD",Workspace2=Reference,Tolerance=1.e-5,CheckEvents=False,IgnoreBoxID=False)
 
-        DeleteWorkspace("wsMD")
+        DeleteWorkspace("dummy_wsMD")
 
         return rez[0]
 
@@ -135,14 +135,14 @@ class LoadSQW_MemBasedTest(BuildSQWTest):
     """ The test checks loading MD workspace from SQW file when target file is file based"""
 
     def __init__(self):
-
+        super(LoadSQW_MemBasedTest, self).__init__()
         self._input_data = ["Test22meV2f.sqw","Test22meVMD.nxs"]
 
     def runTest(self):
 
         sqw_file = os.path.join(self._input_location,self._input_data[0])
 
-        wsMD=LoadSQW(Filename=sqw_file)
+        dummy_wsMD=LoadSQW(Filename=sqw_file)
 
         self._created_files=[]
 
@@ -153,6 +153,6 @@ class LoadSQW_MemBasedTest(BuildSQWTest):
         Reference=LoadMD(Filename=ref_file, FileBackEnd=True, Memory=100)
         rez = CompareMDWorkspaces(Workspace1="wsMD",Workspace2=Reference,Tolerance=1.e-5,CheckEvents=False,IgnoreBoxID=False)
 
-        DeleteWorkspace("wsMD")
+        DeleteWorkspace("dummy_wsMD")
 
         return rez[0]
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/CodeConventions.py b/Code/Mantid/Testing/SystemTests/tests/analysis/CodeConventions.py
index ed1ab76ceeced0da2f5ff3e59d13b415737c9ad0..ee72b67ef86ec7fbd4c947ea9cb0f7857fc398c2 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/CodeConventions.py
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/CodeConventions.py
@@ -8,7 +8,7 @@ MAX_ALG_LEN = 40 # TODO convention says 20 is the maximum
 
 SPECIAL = ["InputWorkspace", "OutputWorkspace", "Workspace",
            "ReductionProperties"]
-SPECIAL_UPPER = [name.upper for name in SPECIAL]
+SPECIAL_UPPER = [specialname.upper for specialname in SPECIAL]
 
 # TODO this list should be empty
 ALG_BAD_PARAMS = {
@@ -29,10 +29,10 @@ ALG_BAD_PARAMS = {
     "PoldiRemoveDeadWires(v1)":("nbExcludedWires", "nbAuteDeadWires"),
     "SaveIsawQvector(v1)":("Qx_vector", "Qy_vector", "Qz_vector"),
     "SCDCalibratePanels(v1)":("a", "b", "c", "alpha", "beta", "gamma",
-                          "useL0", "usetimeOffset", "usePanelWidth",
-                          "usePanelHeight", "usePanelPosition",
-                          "usePanelOrientation", "tolerance",
-                          "MaxPositionChange_meters"),
+                              "useL0", "usetimeOffset", "usePanelWidth",
+                              "usePanelHeight", "usePanelPosition",
+                              "usePanelOrientation", "tolerance",
+                              "MaxPositionChange_meters"),
     "SetSampleMaterial(v1)":("bAverage", "bSquaredAverage"),
     "SetUB(v1)":("a", "b", "c", "alpha", "beta", "gamma", "u", "v"),
     "ViewBOA(v1)":("CD-Distance"),
@@ -58,9 +58,18 @@ FUNC_BAD_PARAMS = {
     "StretchedExpFT":("height", "tau", "beta"),
     "PawleyParameterFunction":("a","b","c"),
     "PawleyFunction":("f0.a","f0.b","f0.c", "f0.Alpha", "f0.Beta", "f0.Gamma", "f0.ZeroShift"),
+    "LatticeFunction":("a","b","c")
     }
 
 class Algorithms(stresstesting.MantidStressTest):
+
+    def __init__(self):
+        super(Algorithms, self).__init__()
+        self.__ranOk = 0
+        self.algRegExp = re.compile(r'^[A-Z][a-zA-Z0-9]+$')
+        self.paramRegExp = re.compile(r'^[A-Z][a-zA-Z0-9]*$')
+        self.categoryRegExp = re.compile(r'^([A-Z][a-zA-Z]+\\?)+$')
+
     def verifyAlgName(self, name):
         if not self.algRegExp.match(name):
             print "Algorithm " + name + " has a name that violates conventions"
@@ -108,11 +117,6 @@ class Algorithms(stresstesting.MantidStressTest):
         return True
 
     def runTest(self):
-        self.__ranOk = 0
-        self.algRegExp = re.compile(r'^[A-Z][a-zA-Z0-9]+$')
-        self.paramRegExp = re.compile(r'^[A-Z][a-zA-Z0-9]*$')
-        self.categoryRegExp = re.compile(r'^([A-Z][a-zA-Z]+\\?)+$')
-
         algs = AlgorithmFactory.getRegisteredAlgorithms(True)
 
         for (name, versions) in algs.iteritems():
@@ -144,6 +148,13 @@ class Algorithms(stresstesting.MantidStressTest):
         return True
 
 class FitFunctions(stresstesting.MantidStressTest):
+    def __init__(self):
+        super(FitFunctions, self).__init__()
+        self.__ranOk = 0
+        self.funcRegExp = re.compile(r'^[A-Z][a-zA-Z0-9]+$')
+        self.paramRegExp = re.compile(r'^[A-Z][a-zA-Z0-9]*$')
+        self.categoryRegExp = re.compile(r'^([A-Z][a-zA-Z]+\\?)+$')
+
     def verifyFuncName(self, name):
         if name in FUNC_BAD_NAME:
             return True
@@ -192,11 +203,6 @@ class FitFunctions(stresstesting.MantidStressTest):
         return True
 
     def runTest(self):
-        self.__ranOk = 0
-        self.funcRegExp = re.compile(r'^[A-Z][a-zA-Z0-9]+$')
-        self.paramRegExp = re.compile(r'^[A-Z][a-zA-Z0-9]*$')
-        self.categoryRegExp = re.compile(r'^([A-Z][a-zA-Z]+\\?)+$')
-
         functions = mantid.api.FunctionFactory.getFunctionNames()
         for name in functions:
             if not self.verifyFuncName(name):
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/DOSTest.py b/Code/Mantid/Testing/SystemTests/tests/analysis/DOSTest.py
index ebaa9487eda46b9b61212d8f16084c67c3b1ebff..efbdc3bdb6510e66997c5a3e20ea96467098f6d1 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/DOSTest.py
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/DOSTest.py
@@ -123,7 +123,7 @@ class DOSPartialCrossSectionScaleTest(stresstesting.MantidStressTest):
         self.ref_result = 'II.DOSPartialCrossSectionScaleTest.nxs'
 
         DensityOfStates(File=file_name, SpectrumType=spec_type, Ions="H,C,O", ScaleByCrossSection='Incoherent',
-                      OutputWorkspace=self.ouput_ws_name)
+                        OutputWorkspace=self.ouput_ws_name)
 
     def validate(self):
         return self.ouput_ws_name, self.ref_result
@@ -146,7 +146,7 @@ class DOSPartialSummedContributionsCrossSectionScaleTest(stresstesting.MantidStr
         self.tolerance = 1e-10
 
         DensityOfStates(File=file_name, SpectrumType=spec_type, Ions="H,C,O", SumContributions=True,
-                      ScaleByCrossSection='Incoherent', OutputWorkspace=self.ouput_ws_name)
+                        ScaleByCrossSection='Incoherent', OutputWorkspace=self.ouput_ws_name)
 
     def validate(self):
         return self.ouput_ws_name, self.ref_result
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/ISISIndirectInelastic.py b/Code/Mantid/Testing/SystemTests/tests/analysis/ISISIndirectInelastic.py
index 38db816a22fb361f39ccdbf52fb9d3fbd645cc87..f920400b261a3a95578cc714c5ba5f9358dc1537 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/ISISIndirectInelastic.py
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/ISISIndirectInelastic.py
@@ -10,7 +10,6 @@ from mantid.simpleapi import *
 from mantid.api import FileFinder
 
 # Import our workflows.
-from inelastic_indirect_reducer import IndirectReducer
 from IndirectDataAnalysis import furyfitSeq, furyfitMult, confitSeq, abscorFeeder
 
 '''
@@ -18,11 +17,10 @@ from IndirectDataAnalysis import furyfitSeq, furyfitMult, confitSeq, abscorFeede
 - OSIRIS/IRIS supported by all tabs / interfaces.
 - VESUVIO is not supported by any interface as of yet.
 
-For diagrams on the intended work flow of the IDA and Indirect parts of the
-C2E interface, please see:
+For diagrams on the intended work flow of the IDR and IDA interfaces see:
 
-- http://www.mantidproject.org/IDA
-- http://www.mantidproject.org/Indirect
+- Indirect_DataReduction.rst
+- Indirect_DataAnalysis.rst
 
 System test class hierarchy as shown below:
 
@@ -80,7 +78,8 @@ stresstesting.MantidStressTest
 
 
 class ISISIndirectInelasticBase(stresstesting.MantidStressTest):
-    '''A common base class for the ISISIndirectInelastic* base classes.
+    '''
+    A common base class for the ISISIndirectInelastic* base classes.
     '''
 
     __metaclass__ = ABCMeta  # Mark as an abstract class
@@ -96,15 +95,18 @@ class ISISIndirectInelasticBase(stresstesting.MantidStressTest):
         raise NotImplementedError("Implement _run.")
 
     def validate_results_and_references(self):
+        num_ref_files = len(self.get_reference_files())
+        num_results = len(self.result_names)
+
         if type(self.get_reference_files()) != list:
             raise RuntimeError("The reference file(s) should be in a list")
         if type(self.result_names) != list:
             raise RuntimeError("The result workspace(s) should be in a list")
-        if len(self.get_reference_files()) !=\
-           len(self.result_names):
-            raise RuntimeError("The number of result workspaces does not match"
-                               " the number of reference files.")
-        if len(self.get_reference_files()) < 1:
+        if num_ref_files != num_results:
+            raise RuntimeError("The number of result workspaces (%d) does not match"
+                               " the number of reference files (%d)." % (
+                               num_ref_files, num_results))
+        if num_ref_files < 1 or num_results < 1:
             raise RuntimeError("There needs to be a least one result and "
                                "reference.")
 
@@ -147,8 +149,8 @@ class ISISIndirectInelasticBase(stresstesting.MantidStressTest):
         and returns the full path.'''
         return os.path.join(config['defaultsave.directory'], filename)
 
-
 #==============================================================================
+
 class ISISIndirectInelasticReduction(ISISIndirectInelasticBase):
     '''A base class for the ISIS indirect inelastic reduction tests
 
@@ -171,23 +173,20 @@ class ISISIndirectInelasticReduction(ISISIndirectInelasticBase):
         '''Defines the workflow for the test'''
         self.tolerance = 1e-7
 
-        reducer = IndirectReducer()
-        reducer.set_instrument_name(self.instr_name)
-        reducer.set_detector_range(self.detector_range[0],
-                                   self.detector_range[1])
-        reducer.set_sum_files(self.sum_files)
-        self.parameter_file = self.instr_name + '_graphite_002_Parameters.xml'
-        reducer.set_parameter_file(self.parameter_file)
-
-        for name in self.data_files:
-            reducer.append_data_file(name)
+        kwargs = {}
 
         if self.rebin_string is not None:
-            reducer.set_rebin_string(self.rebin_string)
+            kwargs['RebinString'] = self.rebin_string
 
-        # Do the reduction and rename the result.
-        reducer.reduce()
-        self.result_names = sorted(reducer.get_result_workspaces())
+        reductions = ISISIndirectEnergyTransfer(Instrument=self.instr_name,
+                                                Analyser='graphite',
+                                                Reflection='002',
+                                                InputFiles=self.data_files,
+                                                SumFiles=self.sum_files,
+                                                SpectraRange=self.detector_range,
+                                                **kwargs)
+
+        self.result_names = sorted(reductions.getNames())
 
     def _validate_properties(self):
         '''Check the object properties are in an expected state to continue'''
@@ -205,13 +204,12 @@ class ISISIndirectInelasticReduction(ISISIndirectInelasticBase):
 
 #------------------------- TOSCA tests ----------------------------------------
 
-
 class TOSCAReduction(ISISIndirectInelasticReduction):
 
     def __init__(self):
         ISISIndirectInelasticReduction.__init__(self)
         self.instr_name = 'TOSCA'
-        self.detector_range = [0, 139]
+        self.detector_range = [1, 140]
         self.data_files = ['TSC15352.raw']
         self.rebin_string = '-2.5,0.015,3,-0.005,1000'
 
@@ -223,8 +221,8 @@ class TOSCAMultiFileReduction(ISISIndirectInelasticReduction):
     def __init__(self):
         ISISIndirectInelasticReduction.__init__(self)
         self.instr_name = 'TOSCA'
-        self.detector_range = [0, 139]
-        self.data_files = ['TSC15352.raw', 'TSC15353.raw','TSC15354.raw']
+        self.detector_range = [1, 140]
+        self.data_files = ['TSC15352.raw', 'TSC15353.raw', 'TSC15354.raw']
         self.rebin_string = '-2.5,0.015,3,-0.005,1000'
 
     def get_reference_files(self):
@@ -237,7 +235,7 @@ class TOSCAMultiFileSummedReduction(ISISIndirectInelasticReduction):
     def __init__(self):
         ISISIndirectInelasticReduction.__init__(self)
         self.instr_name = 'TOSCA'
-        self.detector_range = [0, 139]
+        self.detector_range = [1, 140]
         self.data_files = ['TSC15352.raw', 'TSC15353.raw','TSC15354.raw']
         self.rebin_string = '-2.5,0.015,3,-0.005,1000'
         self.sum_files = True
@@ -245,16 +243,14 @@ class TOSCAMultiFileSummedReduction(ISISIndirectInelasticReduction):
     def get_reference_files(self):
         return ['II.TOSCAMultiFileSummedReduction.nxs']
 
-
 #------------------------- OSIRIS tests ---------------------------------------
 
-
 class OSIRISReduction(ISISIndirectInelasticReduction):
 
     def __init__(self):
         ISISIndirectInelasticReduction.__init__(self)
         self.instr_name = 'OSIRIS'
-        self.detector_range = [962, 1003]
+        self.detector_range = [963, 1004]
         self.data_files = ['OSIRIS00106550.raw']
         self.rebin_string = None
 
@@ -266,7 +262,7 @@ class OSIRISMultiFileReduction(ISISIndirectInelasticReduction):
     def __init__(self):
         ISISIndirectInelasticReduction.__init__(self)
         self.instr_name = 'OSIRIS'
-        self.detector_range = [962, 1003]
+        self.detector_range = [963, 1004]
         self.data_files = ['OSIRIS00106550.raw',' OSIRIS00106551.raw']
         self.rebin_string = None
 
@@ -280,7 +276,7 @@ class OSIRISMultiFileSummedReduction(ISISIndirectInelasticReduction):
     def __init__(self):
         ISISIndirectInelasticReduction.__init__(self)
         self.instr_name = 'OSIRIS'
-        self.detector_range = [962, 1003]
+        self.detector_range = [963, 1004]
         self.data_files = ['OSIRIS00106550.raw', 'OSIRIS00106551.raw']
         self.rebin_string = None
         self.sum_files = True
@@ -295,7 +291,7 @@ class IRISReduction(ISISIndirectInelasticReduction):
     def __init__(self):
         ISISIndirectInelasticReduction.__init__(self)
         self.instr_name = 'IRIS'
-        self.detector_range = [2, 52]
+        self.detector_range = [3, 53]
         self.data_files = ['IRS21360.raw']
         self.rebin_string = None
 
@@ -308,7 +304,7 @@ class IRISMultiFileReduction(ISISIndirectInelasticReduction):
     def __init__(self):
         ISISIndirectInelasticReduction.__init__(self)
         self.instr_name = 'IRIS'
-        self.detector_range = [2, 52]
+        self.detector_range = [3, 53]
         self.data_files = ['IRS21360.raw', 'IRS53664.raw']
         self.rebin_string = None
 
@@ -321,7 +317,7 @@ class IRISMultiFileSummedReduction(ISISIndirectInelasticReduction):
     def __init__(self):
         ISISIndirectInelasticReduction.__init__(self)
         self.instr_name = 'IRIS'
-        self.detector_range = [2, 52]
+        self.detector_range = [3, 53]
         self.data_files = ['IRS21360.raw', 'IRS53664.raw']
         self.sum_files = True
         self.rebin_string = None
@@ -331,19 +327,30 @@ class IRISMultiFileSummedReduction(ISISIndirectInelasticReduction):
         #as they should be the same
         return ['II.IRISMultiFileSummedReduction.nxs']
 
-#--------------------- Generic Reduction tests -----------------------------
+#==============================================================================
 
 class ISISIndirectInelasticReductionOutput(stresstesting.MantidStressTest):
 
     def runTest(self):
-        reducer = self._setup_reducer()
-        reducer.reduce()
-        self.result_names = sorted(reducer.get_result_workspaces())
+        self.file_formats = ['nxs', 'spe', 'nxspe', 'ascii', 'aclimax']
+        self.file_extensions = ['.nxs', '.spe', '.nxspe', '.dat', '_aclimax.dat']
 
-    def validate(self):
-        self.assertEqual(len(self.result_names), 1)
-        self.result_name = self.result_names[0]
+        self.instr_name = 'TOSCA'
+        self.detector_range = [1, 140]
+        self.data_files = ['TSC15352.raw']
+        self.rebin_string = '-2.5,0.015,3,-0.005,1000'
+
+        reductions = ISISIndirectEnergyTransfer(Instrument=self.instr_name,
+                                                Analyser='graphite',
+                                                Reflection='002',
+                                                InputFiles=self.data_files,
+                                                SpectraRange=self.detector_range,
+                                                RebinString=self.rebin_string,
+                                                SaveFormats=self.file_formats)
+
+        self.result_name = reductions[0].getName()
 
+    def validate(self):
         self.output_file_names = self._get_file_names()
         self.assert_reduction_output_exists(self.output_file_names)
         self.assert_ascii_file_matches()
@@ -404,31 +411,6 @@ class ISISIndirectInelasticReductionOutput(stresstesting.MantidStressTest):
         actual_result = self._read_ascii_file(file_path, num_lines)
         self.assertTrue(actual_result == expected_result, msg + " (%s != %s)" % (actual_result, expected_result))
 
-    def _setup_reducer(self):
-        self.file_formats = ['nxs', 'spe', 'nxspe', 'ascii', 'aclimax']
-        self.file_extensions = ['.nxs', '.spe', '.nxspe', '.dat', '_aclimax.dat']
-        self.instr_name = 'TOSCA'
-        self.detector_range = [0, 139]
-        self.data_files = ['TSC15352.raw']
-        self.rebin_string = '-2.5,0.015,3,-0.005,1000'
-        self.parameter_file = self.instr_name + '_graphite_002_Parameters.xml'
-
-        reducer = IndirectReducer()
-        reducer.set_instrument_name(self.instr_name)
-        reducer.set_detector_range(self.detector_range[0],
-                                   self.detector_range[1])
-        reducer.set_sum_files(False)
-        reducer.set_parameter_file(self.parameter_file)
-        reducer.set_save_formats(self.file_formats)
-
-        for name in self.data_files:
-            reducer.append_data_file(name)
-
-        if self.rebin_string is not None:
-            reducer.set_rebin_string(self.rebin_string)
-
-        return reducer
-
     def _read_ascii_file(self, path, num_lines):
         with open(path,'rb') as file_handle:
             lines = [file_handle.readline().rstrip() for _ in xrange(num_lines)]
@@ -446,6 +428,7 @@ class ISISIndirectInelasticReductionOutput(stresstesting.MantidStressTest):
         return output_names
 
 #==============================================================================
+
 class ISISIndirectInelasticCalibration(ISISIndirectInelasticBase):
     '''A base class for the ISIS indirect inelastic calibration tests
 
@@ -488,7 +471,6 @@ class ISISIndirectInelasticCalibration(ISISIndirectInelasticBase):
 
 #------------------------- OSIRIS tests ---------------------------------------
 
-
 class OSIRISCalibration(ISISIndirectInelasticCalibration):
 
     def __init__(self):
@@ -503,7 +485,6 @@ class OSIRISCalibration(ISISIndirectInelasticCalibration):
 
 #------------------------- IRIS tests ---------------------------------------
 
-
 class IRISCalibration(ISISIndirectInelasticCalibration):
 
     def __init__(self):
@@ -516,8 +497,8 @@ class IRISCalibration(ISISIndirectInelasticCalibration):
     def get_reference_files(self):
         return ["II.IRISCalibration.nxs"]
 
-
 #==============================================================================
+
 class ISISIndirectInelasticResolution(ISISIndirectInelasticBase):
     '''A base class for the ISIS indirect inelastic resolution tests
 
@@ -572,7 +553,6 @@ class ISISIndirectInelasticResolution(ISISIndirectInelasticBase):
 
 #------------------------- OSIRIS tests ---------------------------------------
 
-
 class OSIRISResolution(ISISIndirectInelasticResolution):
 
     def __init__(self):
@@ -590,7 +570,6 @@ class OSIRISResolution(ISISIndirectInelasticResolution):
 
 #------------------------- IRIS tests -----------------------------------------
 
-
 class IRISResolution(ISISIndirectInelasticResolution):
 
     def __init__(self):
@@ -606,8 +585,8 @@ class IRISResolution(ISISIndirectInelasticResolution):
     def get_reference_files(self):
         return ["II.IRISResolution.nxs"]
 
-
 #==============================================================================
+
 class ISISIndirectInelasticDiagnostics(ISISIndirectInelasticBase):
     '''A base class for the ISIS indirect inelastic diagnostic tests
 
@@ -646,10 +625,8 @@ class ISISIndirectInelasticDiagnostics(ISISIndirectInelasticBase):
         if type(self.suffix) != str:
             raise RuntimeError("suffix property should be a string")
 
-
 #------------------------- IRIS tests -----------------------------------------
 
-
 class IRISDiagnostics(ISISIndirectInelasticDiagnostics):
 
     def __init__(self):
@@ -663,10 +640,8 @@ class IRISDiagnostics(ISISIndirectInelasticDiagnostics):
     def get_reference_files(self):
         return ["II.IRISDiagnostics.nxs"]
 
-
 #------------------------- OSIRIS tests ---------------------------------------
 
-
 class OSIRISDiagnostics(ISISIndirectInelasticDiagnostics):
 
     def __init__(self):
@@ -680,8 +655,8 @@ class OSIRISDiagnostics(ISISIndirectInelasticDiagnostics):
     def get_reference_files(self):
         return ["II.OSIRISDiagnostics.nxs"]
 
-
 #==============================================================================
+
 class ISISIndirectInelasticMoments(ISISIndirectInelasticBase):
     '''A base class for the ISIS indirect inelastic TransformToIqt/TransformToIqtFit tests
 
@@ -715,8 +690,8 @@ class ISISIndirectInelasticMoments(ISISIndirectInelasticBase):
         if type(self.scale) != float:
             raise RuntimeError("Scale should be a float")
 
-
 #------------------------- OSIRIS tests ---------------------------------------
+
 class OSIRISMoments(ISISIndirectInelasticMoments):
 
     def __init__(self):
@@ -729,8 +704,8 @@ class OSIRISMoments(ISISIndirectInelasticMoments):
     def get_reference_files(self):
         return ['II.OSIRISMoments.nxs']
 
-
 #------------------------- IRIS tests -----------------------------------------
+
 class IRISMoments(ISISIndirectInelasticMoments):
 
     def __init__(self):
@@ -743,8 +718,8 @@ class IRISMoments(ISISIndirectInelasticMoments):
     def get_reference_files(self):
         return ['II.IRISMoments.nxs']
 
-
 #==============================================================================
+
 class ISISIndirectInelasticElwinAndMSDFit(ISISIndirectInelasticBase):
     '''A base class for the ISIS indirect inelastic Elwin/MSD Fit tests
 
@@ -810,7 +785,6 @@ class ISISIndirectInelasticElwinAndMSDFit(ISISIndirectInelasticBase):
 
 #------------------------- OSIRIS tests ---------------------------------------
 
-
 class OSIRISElwinAndMSDFit(ISISIndirectInelasticElwinAndMSDFit):
 
     def __init__(self):
@@ -828,7 +802,6 @@ class OSIRISElwinAndMSDFit(ISISIndirectInelasticElwinAndMSDFit):
 
 #------------------------- IRIS tests -----------------------------------------
 
-
 class IRISElwinAndMSDFit(ISISIndirectInelasticElwinAndMSDFit):
 
     def __init__(self):
@@ -844,8 +817,8 @@ class IRISElwinAndMSDFit(ISISIndirectInelasticElwinAndMSDFit):
                 'II.IRISElwinEQ2.nxs',
                 'II.IRISMSDFit.nxs']
 
-
 #==============================================================================
+
 class ISISIndirectInelasticFuryAndFuryFit(ISISIndirectInelasticBase):
     '''
     A base class for the ISIS indirect inelastic Fury/FuryFit tests
@@ -917,7 +890,6 @@ class ISISIndirectInelasticFuryAndFuryFit(ISISIndirectInelasticBase):
 
 #------------------------- OSIRIS tests ---------------------------------------
 
-
 class OSIRISFuryAndFuryFit(ISISIndirectInelasticFuryAndFuryFit):
 
     def __init__(self):
@@ -943,7 +915,6 @@ class OSIRISFuryAndFuryFit(ISISIndirectInelasticFuryAndFuryFit):
 
 #------------------------- IRIS tests -----------------------------------------
 
-
 class IRISFuryAndFuryFit(ISISIndirectInelasticFuryAndFuryFit):
 
     def __init__(self):
@@ -969,7 +940,6 @@ class IRISFuryAndFuryFit(ISISIndirectInelasticFuryAndFuryFit):
 
 #==============================================================================
 
-
 class ISISIndirectInelasticFuryAndFuryFitMulti(ISISIndirectInelasticBase):
     '''A base class for the ISIS indirect inelastic Fury/FuryFit tests
 
@@ -1039,7 +1009,6 @@ class ISISIndirectInelasticFuryAndFuryFitMulti(ISISIndirectInelasticBase):
 
 #------------------------- OSIRIS tests ---------------------------------------
 
-
 class OSIRISFuryAndFuryFitMulti(ISISIndirectInelasticFuryAndFuryFitMulti):
 
     def skipTests(self):
@@ -1068,7 +1037,6 @@ class OSIRISFuryAndFuryFitMulti(ISISIndirectInelasticFuryAndFuryFitMulti):
 
 #------------------------- IRIS tests -----------------------------------------
 
-
 class IRISFuryAndFuryFitMulti(ISISIndirectInelasticFuryAndFuryFitMulti):
 
     def __init__(self):
@@ -1094,7 +1062,6 @@ class IRISFuryAndFuryFitMulti(ISISIndirectInelasticFuryAndFuryFitMulti):
 
 #==============================================================================
 
-
 class ISISIndirectInelasticConvFit(ISISIndirectInelasticBase):
     '''A base class for the ISIS indirect inelastic ConvFit tests
 
@@ -1149,7 +1116,6 @@ class ISISIndirectInelasticConvFit(ISISIndirectInelasticBase):
 
 #------------------------- OSIRIS tests ---------------------------------------
 
-
 class OSIRISConvFit(ISISIndirectInelasticConvFit):
 
     def __init__(self):
@@ -1172,8 +1138,8 @@ class OSIRISConvFit(ISISIndirectInelasticConvFit):
     def get_reference_files(self):
         return ['II.OSIRISConvFitSeq.nxs']
 
-
 #------------------------- IRIS tests -----------------------------------------
+
 class IRISConvFit(ISISIndirectInelasticConvFit):
 
     def __init__(self):
@@ -1199,7 +1165,6 @@ class IRISConvFit(ISISIndirectInelasticConvFit):
 
 #==============================================================================
 
-
 class ISISIndirectInelasticApplyCorrections(ISISIndirectInelasticBase):
     '''A base class for the ISIS indirect inelastic Apply Corrections tests
 
@@ -1282,7 +1247,6 @@ class IRISApplyCorrectionsWithCan(ISISIndirectInelasticApplyCorrections):
     def get_reference_files(self):
         return ['II.IRISApplyCorrectionsWithCan.nxs']
 
-
 class IRISApplyCorrectionsWithCorrectionsWS(ISISIndirectInelasticApplyCorrections):
     """ Test applying corrections with a corrections workspace """
 
@@ -1323,9 +1287,6 @@ class IRISApplyCorrectionsWithBoth(ISISIndirectInelasticApplyCorrections):
 # Transmission Monitor Test
 
 class ISISIndirectInelasticTransmissionMonitor(ISISIndirectInelasticBase):
-    '''
-    '''
-
     # Mark as an abstract class
     __metaclass__ = ABCMeta
 
@@ -1347,8 +1308,8 @@ class ISISIndirectInelasticTransmissionMonitor(ISISIndirectInelasticBase):
         if type(self.can) != str:
             raise RuntimeError("Can should be a string.")
 
-
 #------------------------- IRIS tests -----------------------------------------
+
 class IRISTransmissionMonitor(ISISIndirectInelasticTransmissionMonitor):
 
     def __init__(self):
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/ISIS_LETReduction.py b/Code/Mantid/Testing/SystemTests/tests/analysis/ISIS_LETReduction.py
index 89d572b3894d289b78255ec4fd196e7bd9796379..a62dd1c28ee351050279198cf4b87e7c3bd937a3 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/ISIS_LETReduction.py
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/ISIS_LETReduction.py
@@ -31,7 +31,7 @@ def find_binning_range(energy,ebin):
         mult=2.8868
         dt_DAE = 1
     else:
-       raise RuntimeError("Find_binning_range: unsupported/unknown instrument found")
+        raise RuntimeError("Find_binning_range: unsupported/unknown instrument found")
 
     energy=float(energy)
 
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/IndirectEnergyConversionTest.py b/Code/Mantid/Testing/SystemTests/tests/analysis/IndirectEnergyConversionTest.py
index b213a4662eae77cb5874619666aeb94c3e552642..b683bf46ee8c927ee7ddf8c6df63380d9c88ca77 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/IndirectEnergyConversionTest.py
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/IndirectEnergyConversionTest.py
@@ -12,16 +12,16 @@ class IndirectEnergyConversionTest(stresstesting.MantidStressTest):
         files = 'irs21360.raw'
         rebin_string = '-0.5,0.005,0.5'
 
-        InelasticIndirectReduction(InputFiles=files,
-                                   RebiNString=rebin_string,
-                                   DetectorRange=detector_range,
+        ISISIndirectEnergyTransfer(InputFiles=files,
+                                   RebinString=rebin_string,
+                                   SpectraRange=detector_range,
                                    Instrument=instrument,
                                    Analyser=analyser,
                                    Reflection=reflection,
-                                   OutputWorkspace='__IndirectEnergyCOnversionTest_out_group')
+                                   OutputWorkspace='__IndirectEnergyConversionTest_out_group')
 
 
     def validate(self):
         self.disableChecking.append('Instrument')
         self.disableChecking.append('SpectraMap')
-        return 'irs21360_graphite002_red', 'IndirectEnergyConversionTest.nxs'
+        return 'IRS21360_graphite002_red', 'IndirectEnergyConversionTest.nxs'
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/LRScalingFactorsTest.py b/Code/Mantid/Testing/SystemTests/tests/analysis/LRScalingFactorsTest.py
new file mode 100644
index 0000000000000000000000000000000000000000..afdf17e061eddf25049f34bb30598695e5b9f161
--- /dev/null
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/LRScalingFactorsTest.py
@@ -0,0 +1,60 @@
+#pylint: disable=no-init,attribute-defined-outside-init
+import stresstesting
+import os
+from mantid import *
+from mantid.simpleapi import *
+
+class LRPrimaryFractionTest(stresstesting.MantidStressTest):
+    """
+    #y=a+bx
+    #
+    #lambdaRequested[Angstroms] S1H[mm] (S2/Si)H[mm] S1W[mm] (S2/Si)W[mm] a b error_a error_b
+    #
+    IncidentMedium=Air LambdaRequested=5.0 S1H=0.202 S2iH=0.196767 S1W=9.002 S2iW=9.004654 a=7.79202718645 b=3.39894488089e-05 error_a=0.0936282133631 error_b=5.79945870854e-06
+    IncidentMedium=Air LambdaRequested=5.0 S1H=0.202 S2iH=0.196767 S1W=20.0 S2iW=20.007348 a=24.4210636894 b=0.00010609255313 error_a=0.390001391338 error_b=2.51447482677e-05
+
+    """
+    def runTest(self):
+        self.cfg_file = os.path.join(config.getString('defaultsave.directory'),'scaling_factors.cfg')
+        LRScalingFactors(DirectBeamRuns=[124168, 124169, 124170, 124171, 124172],
+                         Attenuators = [0, 1, 1, 2, 2, 2],
+                         TOFRange=[10008, 35000], TOFSteps=200,
+                         SignalPeakPixelRange=[150, 160], 
+                         SignalBackgroundPixelRange=[147, 163],
+                         ScalingFactorFile=self.cfg_file)
+
+    def validate(self):
+        if not os.path.isfile(self.cfg_file):
+            raise RuntimeError, "Output file was not created"
+
+        reference = [[7.82, 3.20e-05, 0.054, 3.3e-06],
+                     [24.42, 0.000105, 0.225, 1.45e-05]]
+        tolerances = [[0.1, 5e-6, 0.1, 3e-6], [0.1, 1e-5, 0.2, 2e-5]]
+        fd = open(self.cfg_file, 'r')
+        item_number = 0
+        for line in fd.readlines():
+            if line.startswith("#"):
+                continue
+            toks = line.split()
+            for token in toks:
+                pair = token.split('=')
+                if pair[0].strip() == 'a':
+                    a = float(pair[1])
+                elif pair[0].strip() == 'b':
+                    b = float(pair[1])
+                elif pair[0].strip() == 'error_a':
+                    error_a = float(pair[1])
+                elif pair[0].strip() == 'error_b':
+                    error_b = float(pair[1])
+            if not (abs(reference[item_number][0]- a ) < tolerances[item_number][0] \
+                and abs(reference[item_number][1] - b) < tolerances[item_number][1] \
+                and abs(reference[item_number][2]-error_a) < tolerances[item_number][2] \
+                and abs(reference[item_number][3] - error_b) < tolerances[item_number][3]):
+                logger.error("Found    %5.3g %5.3g %5.3g %5.3g" % (a, b, error_a, error_b))
+                logger.error("Expected %5.3g %5.3g %5.3g %5.3g" % (reference[item_number][0], reference[item_number][1],
+                                                                   reference[item_number][2], reference[item_number][3]))
+                return False
+            item_number += 1
+        fd.close()
+        os.remove(self.cfg_file)
+        return True
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/LiquidsReflectometryReductionTest.py b/Code/Mantid/Testing/SystemTests/tests/analysis/LiquidsReflectometryReductionTest.py
index bd2825b42efecbca079cd5b2040b855f4249de94..8014c8bdcacb270b5a1857a77d251029d2c5c1a4 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/LiquidsReflectometryReductionTest.py
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/LiquidsReflectometryReductionTest.py
@@ -35,15 +35,8 @@ class LiquidsReflectometryReductionTest(stresstesting.MantidStressTest):
                                       OutputWorkspace='reflectivity_119814')
 
     def validate(self):
-        # Be more tolerant with the output.
-        self.tolerance = 0.01
-
-        # Skip the first point so we don't have to have a big tolerance
-        data_y = mtd["reflectivity_119814"].dataY(0)
-        data_y[1] = 0.631281639115562
-
         self.disableChecking.append('Instrument')
         self.disableChecking.append('Sample')
         self.disableChecking.append('SpectraMap')
         self.disableChecking.append('Axes')
-        return "reflectivity_119814", 'REFL_119814_combined_data.nxs'
+        return "reflectivity_119814", 'REFL_119814_combined_data_v2.nxs'
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/LiquidsReflectometryReductionWithBackgroundTest.py b/Code/Mantid/Testing/SystemTests/tests/analysis/LiquidsReflectometryReductionWithBackgroundTest.py
index 4b0359ff96c912bdea2fca4414bf099f91fede20..07fa5084cc3e5b63009abc15bea555eb56fc7539 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/LiquidsReflectometryReductionWithBackgroundTest.py
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/LiquidsReflectometryReductionWithBackgroundTest.py
@@ -4,54 +4,6 @@ from mantid import *
 from mantid.simpleapi import *
 import sys
 
-class LiquidsReflectometryReductionWithBackgroundTest(stresstesting.MantidStressTest):
-    """
-        This test checks that the new liquids reflectometer reduction produces
-        the same results as the old code. It's more tolerant than the test below.
-    """
-    def runTest(self):
-        #TODO: The reduction algorithm should not require an absolute path
-        scaling_factor_file = FileFinder.getFullPath("directBeamDatabaseFall2014_IPTS_11601_2.cfg")
-
-        LiquidsReflectometryReduction(RunNumbers=[119816],
-                                      NormalizationRunNumber=119692,
-                                      SignalPeakPixelRange=[155, 165],
-                                      SubtractSignalBackground=True,
-                                      SignalBackgroundPixelRange=[146, 165],
-                                      NormFlag=True,
-                                      NormPeakPixelRange=[154, 162],
-                                      NormBackgroundPixelRange=[151, 165],
-                                      SubtractNormBackground=True,
-                                      LowResDataAxisPixelRangeFlag=True,
-                                      LowResDataAxisPixelRange=[99, 158],
-                                      LowResNormAxisPixelRangeFlag=True,
-                                      LowResNormAxisPixelRange=[118, 137],
-                                      TOFRange=[9610, 22425],
-                                      IncidentMediumSelected='2InDiamSi',
-                                      GeometryCorrectionFlag=False,
-                                      QMin=0.005,
-                                      QStep=0.01,
-                                      AngleOffset=0.009,
-                                      AngleOffsetError=0.001,
-                                      ScalingFactorFile=scaling_factor_file,
-                                      SlitsWidthFlag=True,
-                                      CropFirstAndLastPoints=False,
-                                      OutputWorkspace='reflectivity_119816')
-
-    def validate(self):
-        # Be more tolerant with the output.
-        self.tolerance = 0.0002
-
-        # Skip the first point so we don't have to have a big tolerance
-        data_y = mtd["reflectivity_119816"].dataY(0)
-        data_y[1] = 0.00499601750282373
-
-        self.disableChecking.append('Instrument')
-        self.disableChecking.append('Sample')
-        self.disableChecking.append('SpectraMap')
-        self.disableChecking.append('Axes')
-        return "reflectivity_119816", 'REFL_119816.nxs'
-
 
 class LiquidsReflectometryReductionWithBackgroundPreciseTest(stresstesting.MantidStressTest):
     """
@@ -150,7 +102,7 @@ class TOFRangeOFFTest(stresstesting.MantidStressTest):
                                       LowResNormAxisPixelRangeFlag=True,
                                       LowResNormAxisPixelRange=[118, 137],
                                       TOFRange=[9610, 22425],
-                                      TofRangeFlag=False,
+                                      TOFRangeFlag=False,
                                       IncidentMediumSelected='2InDiamSi',
                                       GeometryCorrectionFlag=False,
                                       QMin=0.005,
@@ -189,7 +141,7 @@ class NoBackgroundTest(stresstesting.MantidStressTest):
                                       LowResNormAxisPixelRangeFlag=True,
                                       LowResNormAxisPixelRange=[118, 137],
                                       TOFRange=[9610, 22425],
-                                      TofRangeFlag=True,
+                                      TOFRangeFlag=True,
                                       IncidentMediumSelected='2InDiamSi',
                                       GeometryCorrectionFlag=False,
                                       QMin=0.005,
@@ -229,7 +181,7 @@ class TOFMismatchTest(stresstesting.MantidStressTest):
                                           LowResNormAxisPixelRangeFlag=True,
                                           LowResNormAxisPixelRange=[118, 137],
                                           TOFRange=[9610, 22425],
-                                          TofRangeFlag=True,
+                                          TOFRangeFlag=True,
                                           IncidentMediumSelected='2InDiamSi',
                                           GeometryCorrectionFlag=False,
                                           QMin=0.005,
@@ -268,7 +220,7 @@ class BadDataTOFRangeTest(stresstesting.MantidStressTest):
                                           LowResNormAxisPixelRangeFlag=True,
                                           LowResNormAxisPixelRange=[118, 137],
                                           TOFRange=[29623.0, 42438.0],
-                                          TofRangeFlag=True,
+                                          TOFRangeFlag=True,
                                           IncidentMediumSelected='2InDiamSi',
                                           GeometryCorrectionFlag=False,
                                           QMin=0.005,
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/LoadLotsOfFiles.py b/Code/Mantid/Testing/SystemTests/tests/analysis/LoadLotsOfFiles.py
index 253085eb8971a12c7346cd6fa455170b8931d639..96cb9cd0c7a08112193f9db6326e0afd9ad57777 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/LoadLotsOfFiles.py
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/LoadLotsOfFiles.py
@@ -68,7 +68,8 @@ BANNED_FILES = ['992 Descriptions.txt',
                 'poldi2013n006903.hdf',
                 'poldi2013n006904.hdf',
                 'poldi2014n019874.hdf',
-                'poldi2014n019881.hdf'
+                'poldi2014n019881.hdf',
+                'poldi2015n000977.hdf'
                 ]
 
 EXPECTED_EXT = '.expected'
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/POLDIAnalyseResidualsTest.py b/Code/Mantid/Testing/SystemTests/tests/analysis/POLDIAnalyseResidualsTest.py
index 53011cea6922691f85c60eeeb555b9522a97f73f..ca747f13f2e814e419b4feaba44386cd43706f71 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/POLDIAnalyseResidualsTest.py
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/POLDIAnalyseResidualsTest.py
@@ -33,9 +33,8 @@ class POLDIAnalyseResidualsTest(stresstesting.MantidStressTest):
             referenceData = mtd["%s_fortran_residuals" % (dataFile)].dataY(0)
             calculatedData = mtd["%sResiduals" % (dataFile)].dataY(0)
 
-            self.assertEqual(calculatedData.shape[0], referenceData.shape[0],
-                             "Number of d-values does not match for %s (is: %i, should: %i)" % (
-                             dataFile, calculatedData.shape[0], referenceData.shape[0]))
+            self.assertEqual(calculatedData.shape[0], referenceData.shape[0],"Number of d-values does not match for %s \
+                             (is: %i, should: %i)" % (dataFile, calculatedData.shape[0], referenceData.shape[0]))
 
             CreateWorkspace(referenceData, calculatedData, OutputWorkspace=workspaceNameTemplate)
 
@@ -49,13 +48,13 @@ class POLDIAnalyseResidualsTest(stresstesting.MantidStressTest):
             self.assertDelta(slope, 1.0, 1e-2, "Slope is larger than 1.0 for %s (is: %d)" % (dataFile, slope))
 
             relativeSlopeError = fitResult.cell(1, 2) / slope
-            self.assertLessThan(relativeSlopeError, 5e-3, "Relative error of slope is too large for %s (is: %d)" % (
-                                                          dataFile, relativeSlopeError))
+            self.assertLessThan(relativeSlopeError, 5e-3,
+                                "Relative error of slope is too large for %s (is: %d)" % (dataFile, relativeSlopeError))
 
             intercept = fitResult.cell(0, 1)
             self.assertDelta(intercept, 0.0, 1e-3, "Intercept deviates too far from 0 %s (is: %d)" % (dataFile, intercept))
 
             residuals = mtd[fitNameTemplate + "_Workspace"].dataY(2)
             maxAbsoluteResidual = np.max(np.abs(residuals))
-            self.assertLessThan(maxAbsoluteResidual, 1.0, "Maximum absolute residual is too large for %s (is: %d)" % (
-                                                          dataFile, maxAbsoluteResidual))
+            self.assertLessThan(maxAbsoluteResidual, 1.0,
+                                "Maximum absolute residual is too large for %s (is: %d)" % (dataFile, maxAbsoluteResidual))
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/POLDIDataAnalysisTest.py b/Code/Mantid/Testing/SystemTests/tests/analysis/POLDIDataAnalysisTest.py
new file mode 100644
index 0000000000000000000000000000000000000000..1221efbb6ce527d23c2e88dd36a3d6ed184e022b
--- /dev/null
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/POLDIDataAnalysisTest.py
@@ -0,0 +1,88 @@
+# pylint: disable=no-init,invalid-name,too-many-locals
+import stresstesting
+from mantid.simpleapi import *
+from mantid.api import *
+import numpy as np
+
+
+class POLDIDataAnalysisTestSi(stresstesting.MantidStressTest):
+    """Base class that loads/generates data for the tests, which is identical.
+    """
+
+    def runTest(self):
+        pass
+
+    def prepareTest(self):
+        self._loadData()
+        self._createSi()
+
+        return 'poldi_data_6904', 'Si'
+
+    def _loadData(self):
+        PoldiLoadRuns(2013, 6903, 6904, 2, OutputWorkspace='poldi', MaskBadDetectors=False)
+
+    def _createSi(self):
+        PoldiCreatePeaksFromCell(SpaceGroup='F d -3 m',
+                                 a=5.431, LatticeSpacingMin=0.7,
+                                 Atoms='Si 0 0 0 1.0 0.01',
+                                 OutputWorkspace='Si')
+
+
+class POLDIDataAnalysisTestSiIndividual(POLDIDataAnalysisTestSi):
+    """This test runs PoldiDataAnalysis with Si data, using."""
+
+    def runTest(self):
+        data, expectedPeaks = self.prepareTest()
+
+        output = PoldiDataAnalysis(InputWorkspace=data,
+                                   MaximumPeakNumber=11,
+                                   ExpectedPeaks=expectedPeaks,
+                                   PlotResult=False)
+
+        # Make sure that it's a workspace group
+        self.assertTrue(isinstance(output, WorkspaceGroup))
+
+        # check the refined peaks.
+        refinedPeaks = AnalysisDataService.retrieve('poldi_data_6904_peaks_refined_2d')
+        self.assertEquals(refinedPeaks.rowCount(), 11)
+
+        # make sure there are no unindexed peaks
+        self.assertFalse(AnalysisDataService.doesExist('poldi_data_6904_peaks_refined_1d_unindexed'))
+
+        # get total spectrum
+        totalSpectrum = AnalysisDataService.retrieve('poldi_data_6904_sum')
+        # get residuals
+        residuals = AnalysisDataService.retrieve('poldi_data_6904_residuals')
+
+        sumData = totalSpectrum.dataY(0)
+        residualData = residuals.dataY(0)
+
+        maxSum = np.max(sumData)
+        maxResidual = np.max(residualData)
+
+        # Maximum residual should not be too large
+        self.assertLessThan(maxResidual / maxSum, 0.075)
+
+class POLDIDataAnalysisTestSiPawley(POLDIDataAnalysisTestSi):
+    """This test runs PoldiDataAnalysis with Si data, using."""
+
+    def runTest(self):
+        data, expectedPeaks = self.prepareTest()
+
+        PoldiDataAnalysis(InputWorkspace=data,
+                                   MaximumPeakNumber=11,
+                                   ExpectedPeaks=expectedPeaks,
+                                   PawleyFit=True,
+                                   PlotResult=False, OutputWorkspace='output')
+
+        # inspect the cell
+        cell = AnalysisDataService.retrieve('poldi_data_6904_cell_refined')
+
+        # 2 rows for cubic cell
+        self.assertTrue(cell.rowCount(), 2)
+
+        a_val = cell.cell(0, 1)
+        a_err = cell.cell(0, 2)
+
+        self.assertLessThan(np.abs(a_err), 5.0e-5)
+        self.assertLessThan(np.abs(a_val - 5.4311946) / a_err, 1.5)
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/POLDIFitPeaks2DTest.py b/Code/Mantid/Testing/SystemTests/tests/analysis/POLDIFitPeaks2DTest.py
index 3d127c8a9938a0d968744d9b75f6a6b7457afc26..6e796ef58e5862d7ba9361b5b593fa09ac437204 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/POLDIFitPeaks2DTest.py
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/POLDIFitPeaks2DTest.py
@@ -93,14 +93,15 @@ class POLDIFitPeaks2DPawleyTest(stresstesting.MantidStressTest):
         si_refs = PoldiCreatePeaksFromCell("F d -3 m", "Si 0 0 0", a=5.431, LatticeSpacingMin=0.7)
         indexed = PoldiIndexKnownCompounds(peaks_ref, "si_refs")
 
-        DeleteTableRows("indexed_si_refs", "10-30")
+        DeleteTableRows("peaks_ref_indexed_si_refs", "8-30")
 
-        fit2d, fit1d, peaks_ref_2d, cell = PoldiFitPeaks2D('si_data_6904', 'indexed_si_refs',
+        fit2d, fit1d, peaks_ref_2d, cell = PoldiFitPeaks2D('si_data_6904', 'peaks_ref_indexed_si_refs',
                                                            PawleyFit=True,
-                                                           InitialCell="5.431 5.431 5.431 90 90 90",
-                                                           CrystalSystem="Cubic",
                                                            MaximumIterations=100)
 
+        # parameters a and ZeroShift
+        self.assertEquals(cell.rowCount(), 2)
+
         cell_a = cell.cell(0, 1)
         cell_a_err = cell.cell(0, 2)
 
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/POLDILoadRunsTest.py b/Code/Mantid/Testing/SystemTests/tests/analysis/POLDILoadRunsTest.py
index c542ffbd765ad0d98821ebbace53269ed322edfc..8fd73d1cea6871bd89b10c6e480d563045cf9ba1 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/POLDILoadRunsTest.py
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/POLDILoadRunsTest.py
@@ -4,6 +4,7 @@ from mantid.simpleapi import *
 from mantid.api import *
 import numpy as np
 
+
 class POLDILoadRunsTest(stresstesting.MantidStressTest):
     """This assembly of test cases checks that the behavior of PoldiLoadRuns is correct."""
 
@@ -19,6 +20,9 @@ class POLDILoadRunsTest(stresstesting.MantidStressTest):
         self.loadWorkspacesDontOverwriteOther()
         self.loadWorkspacesOverwriteOther()
 
+        self.checkRemoveBadDetectors()
+        self.check2015PoldiData()
+
     def loadSingleWorkspace(self):
         singleWs = PoldiLoadRuns(2013, 6904)
 
@@ -128,6 +132,51 @@ class POLDILoadRunsTest(stresstesting.MantidStressTest):
 
         self.assertTrue(issubclass(type(otherWs), Workspace))
 
+    def checkRemoveBadDetectors(self):
+        # Determine bad detectors automatically
+        PoldiLoadRuns(2013, 6903, 6904, 2, MaskBadDetectors=True,
+                                            BadDetectorThreshold=2.5,
+                                            OutputWorkspace='twoWorkspacesMerged')
+
+        wsMerged = AnalysisDataService.retrieve("twoWorkspacesMerged_data_6904")
+        self.assertEquals(len([True for x in range(wsMerged.getNumberHistograms()) if wsMerged.getDetector(
+            x).isMasked()]), 36)
+
+        self.clearAnalysisDataService()
+
+        # Lower threshold, more excluded detectors
+        PoldiLoadRuns(2013, 6903, 6904, 2, MaskBadDetectors=True,
+                                            BadDetectorThreshold=2.0,
+                                            OutputWorkspace='twoWorkspacesMerged')
+
+        wsMerged = AnalysisDataService.retrieve("twoWorkspacesMerged_data_6904")
+        self.assertEquals(len([True for x in range(wsMerged.getNumberHistograms()) if wsMerged.getDetector(
+            x).isMasked()]), 49)
+
+        self.clearAnalysisDataService()
+
+        # Only use those from the IDF
+        PoldiLoadRuns(2013, 6903, 6904, 2, MaskBadDetectors=False,
+                                            OutputWorkspace='twoWorkspacesMerged')
+
+        wsMerged = AnalysisDataService.retrieve("twoWorkspacesMerged_data_6904")
+        self.assertEquals(len([True for x in range(wsMerged.getNumberHistograms()) if wsMerged.getDetector(
+            x).isMasked()]), 12)
+
+        self.clearAnalysisDataService()
+
+    def check2015PoldiData(self):
+        PoldiLoadRuns(2015, 977, OutputWorkspace='ws')
+
+        ws2015 = AnalysisDataService.retrieve('ws_data_977')
+        self.assertEquals(ws2015.getNumberHistograms(), 400)
+        self.assertEquals(len(ws2015.readX(0)), 125)
+        self.assertTrue(ws2015.run().hasProperty('chopperspeed'))
+
+        self.clearAnalysisDataService()
+
+
+
     def compareWorkspaces(self, left, right):
         for i in range(left.getNumberHistograms()):
             self.assertTrue(np.array_equal(left.dataY(i), right.dataY(i)))
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/REFMReduction.py b/Code/Mantid/Testing/SystemTests/tests/analysis/REFMReduction.py
index 9028c273df3661460d918baed6886105f692e40f..80bd80cc4b45366cf6a7d201ab94b00a7ca21655 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/REFMReduction.py
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/REFMReduction.py
@@ -7,22 +7,22 @@ from mantid.simpleapi import *
 class REFMReduction(stresstesting.MantidStressTest):
     def runTest(self):
         RefReduction(DataRun=str(9709),
-              NormalizationRun=str(9684),
-              SignalPeakPixelRange=[216, 224],
-              SubtractSignalBackground=True,
-              SignalBackgroundPixelRange=[172, 197],
-              PerformNormalization=True,
-              NormPeakPixelRange=[226, 238],
-              NormBackgroundPixelRange=[130, 183],
-              SubtractNormBackground=False,
-              CropLowResDataAxis=True,
-              CropLowResNormAxis=False,
-              LowResDataAxisPixelRange = [86, 159],
-              NBins=40,
-              Theta=0.086,
-              PolarizedData=True,
-              Instrument="REF_M",
-              OutputWorkspacePrefix='reflectivity')
+                     NormalizationRun=str(9684),
+                     SignalPeakPixelRange=[216, 224],
+                     SubtractSignalBackground=True,
+                     SignalBackgroundPixelRange=[172, 197],
+                     PerformNormalization=True,
+                     NormPeakPixelRange=[226, 238],
+                     NormBackgroundPixelRange=[130, 183],
+                     SubtractNormBackground=False,
+                     CropLowResDataAxis=True,
+                     CropLowResNormAxis=False,
+                     LowResDataAxisPixelRange = [86, 159],
+                     NBins=40,
+                     Theta=0.086,
+                     PolarizedData=True,
+                     Instrument="REF_M",
+                     OutputWorkspacePrefix='reflectivity')
 
     def validate(self):
         # Be more tolerant with the output, mainly because of the errors.
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/ReduceOneSCD_Run.py b/Code/Mantid/Testing/SystemTests/tests/analysis/ReduceOneSCD_Run.py
index f1e5a6fbf4e2a55c49f145023294321ef2664612..ff3ba022855d540064741a7995ecb905195ca132 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/ReduceOneSCD_Run.py
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/ReduceOneSCD_Run.py
@@ -19,7 +19,6 @@ import stresstesting
 
 
 from mantid.api import *
-#sys.path.append("/home/ruth/GIT_MantidBuild/bin/")
 from mantid.simpleapi import *
 
 class ReduceOneSCD_Run( stresstesting.MantidStressTest):
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/SANSLoadersTest.py b/Code/Mantid/Testing/SystemTests/tests/analysis/SANSLoadersTest.py
index a427fcd3fe5e6ef086fa39cef10322e355d38a65..36a1f284ab1343f671c6c2374451fbcbe480a336 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/SANSLoadersTest.py
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/SANSLoadersTest.py
@@ -142,6 +142,7 @@ class LoadSampleTest(unittest.TestCase):
             self.assertAlmostEqual(cur_pos[1], -0.002)
 
 
+
 class LoadSampleTestStressTest(stresstesting.MantidStressTest):
     def runTest(self):
         self._success = False
@@ -159,6 +160,88 @@ class LoadSampleTestStressTest(stresstesting.MantidStressTest):
     def validate(self):
         return self._success
 
+class LoadAddedEventDataSampleTestStressTest(stresstesting.MantidStressTest):
+    def __init__(self):
+        stresstesting.MantidStressTest.__init__(self)
+        self._success = False
+
+    def runTest(self):
+        self._success = False
+        config["default.instrument"] = "SANS2D"
+        ici.SANS2D()
+        ici.MaskFile('MaskSANS2DReductionGUI.txt')
+        ici.SetDetectorOffsets('REAR', -16.0, 58.0, 0.0, 0.0, 0.0, 0.0)
+        ici.SetDetectorOffsets('FRONT', -44.0, -20.0, 47.0, 0.0, 1.0, 1.0)
+        ici.Gravity(False)
+        ici.Set1D()
+
+        ici.add_runs(('22048', '22023') ,'SANS2D', 'nxs', saveAsEvent=True)
+
+        ici.AssignSample('22023-add.nxs')
+
+        ici.WavRangeReduction(4.6, 12.85, False)
+
+        # Need to do validation ourselves since we have to compare to sets of workspace-file pairs
+        if self._validateWorkspaceToNeXusCustom():
+            self._success = True
+
+
+    def _validateWorkspaceToNeXusCustom(self):
+        '''
+        Since we need to compare two have two comparisons, we need to redefine the validateWorkspaceToNexus method here.
+        Assumes that the items from self.validate() are many tuples  where the first item is a nexus file and loads it,
+        to compare to the supplied workspace which is the second item.
+        '''
+        value_pairs = list(self._validateCustom())
+
+        # Make sure we have pairs of two
+        if len(value_pairs )%2 != 0:
+            return False
+
+        # For all pairs create a list and run the normal comparison
+        validationResult = []
+
+        for index in range(0, len(value_pairs), 2):
+            valNames = value_pairs[index : index + 2]
+
+            numRezToCheck=len(valNames)
+            mismatchName=None
+
+            validationResult.extend([True])
+            for ik in range(0,numRezToCheck,2): # check All results
+                workspace2 = valNames[ik+1]
+                if workspace2.endswith('.nxs'):
+                    Load(Filename=workspace2,OutputWorkspace="RefFile")
+                    workspace2 = "RefFile"
+                else:
+                    raise RuntimeError("Should supply a NeXus file: %s" % workspace2)
+                valPair=(valNames[ik],"RefFile")
+                if numRezToCheck>2:
+                    mismatchName = valNames[ik]
+
+                if not self.validateWorkspaces(valPair,mismatchName):
+                    validationResult[index/2] = False
+                    print 'Workspace {0} not equal to its reference file'.format(valNames[ik])
+            #end check All results
+
+        # Check if a comparison went wrong
+        return all(item is True for item in validationResult)
+
+    def _validateCustom(self):
+        return ('22023rear_1D_4.6_12.85', 'SANS2DLoadingAddedEventData.nxs',
+                '22023rear_1D_4.6_12.85_incident_monitor', 'SANS2DLoadingAddedEventDataMonitor.nxs')
+
+    def requiredMemoryMB(self):
+        return 2000
+
+    def validateMethod(self):
+        return "WorkspaceToNexus"
+
+    def cleanup(self):
+        os.remove(os.path.join(config['defaultsave.directory'],'SANS2D00022023-add.nxs'))
+
+    def validate(self):
+        return self._success
 
 
 if __name__ == '__main__':
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/SNSPowderRedux.py b/Code/Mantid/Testing/SystemTests/tests/analysis/SNSPowderRedux.py
index 26f0aab056e6c8096ca533e489f2f09f52537eec..7db8091f619f1dcf2c0250cc97f6dbacadb17943 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/SNSPowderRedux.py
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/SNSPowderRedux.py
@@ -10,25 +10,24 @@ def _skip_test():
     import platform
 
     # Only runs on RHEL6 at the moment
-    return ("Linux" not in platform.platform())
+    return "Linux" not in platform.platform()
 
 def getSaveDir():
     """determine where to save - the current working directory"""
-    import os
     return os.path.abspath(os.path.curdir)
 
 def do_cleanup():
     Files = ["PG3_9829.gsa",
-    "PG3_9829.py",
-    "PG3_9830.gsa",
-    "PG3_9830.py",
-    "PG3_4844-1.dat",
-    "PG3_4844.getn",
-    "PG3_4844.gsa",
-    "PG3_4844.py",
-    "PG3_4866.gsa"]
-    for file in Files:
-        absfile = FileFinder.getFullPath(file)
+             "PG3_9829.py",
+             "PG3_9830.gsa",
+             "PG3_9830.py",
+             "PG3_4844-1.dat",
+             "PG3_4844.getn",
+             "PG3_4844.gsa",
+             "PG3_4844.py",
+             "PG3_4866.gsa"]
+    for filename in Files:
+        absfile = FileFinder.getFullPath(filename)
         if os.path.exists(absfile):
             os.remove(absfile)
     return True
@@ -96,7 +95,6 @@ class PG3StripPeaks(stresstesting.MantidStressTest):
 
     def runTest(self):
         # determine where to save
-        import os
         savedir = os.path.abspath(os.path.curdir)
 
         LoadEventNexus(Filename="PG3_4866_event.nxs",
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/SphinxWarnings.py b/Code/Mantid/Testing/SystemTests/tests/analysis/SphinxWarnings.py
index 4d4b02f15b9f61b9a9d3aa1d28a2c9a7808dc809..179af12b8d021fa757c80a8b1c7667e56448ac27 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/SphinxWarnings.py
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/SphinxWarnings.py
@@ -12,30 +12,30 @@ class SphinxWarnings(stresstesting.MantidStressTest):
     def __init__(self):
         stresstesting.MantidStressTest.__init__(self)
         self.allowedCategories=['Arithmetic',
-                        'CorrectionFunctions',
-                        'Crystal',
-                        'DataHandling',
-                        'Diagnostics',
-                        'Diffraction',
-                        'Events',
-                        'Examples',
-                        'ISIS',
-                        'Inelastic',
-                        'MDAlgorithms',
-                        'MPI',
-                        'Muon',
-                        'Optimization',
-                        'PythonAlgorithms',
-                        'Quantification',
-                        'Reflectometry',
-                        'Remote',
-                        'SANS',
-                        'Simulation',
-                        'SINQ',
-                        'Sample',
-                        'Transforms',
-                        'Utility',
-                        'Workflow']
+                                'CorrectionFunctions',
+                                'Crystal',
+                                'DataHandling',
+                                'Diagnostics',
+                                'Diffraction',
+                                'Events',
+                                'Examples',
+                                'ISIS',
+                                'Inelastic',
+                                'MDAlgorithms',
+                                'MPI',
+                                'Muon',
+                                'Optimization',
+                                'PythonAlgorithms',
+                                'Quantification',
+                                'Reflectometry',
+                                'Remote',
+                                'SANS',
+                                'Simulation',
+                                'SINQ',
+                                'Sample',
+                                'Transforms',
+                                'Utility',
+                                'Workflow']
         self.errorMessage=""
 
     def checkString(self,s):
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/TobyFitResolutionSimulationTest.py b/Code/Mantid/Testing/SystemTests/tests/analysis/TobyFitResolutionSimulationTest.py
index 0c24b3cc234db0e4eb1f0490efc91fa1a10220b3..94778c8ef5a3bcf3031c2b25c68b52ee1903beb6 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/TobyFitResolutionSimulationTest.py
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/TobyFitResolutionSimulationTest.py
@@ -71,7 +71,8 @@ class TobyFitResolutionSimulationTest(MantidStressTest):
         CreateModeratorModel(Workspace=fake_data,ModelType='IkedaCarpenterModerator',
                              Parameters="TiltAngle=32,TauF=2.7,TauS=0,R=0")
         CreateChopperModel(Workspace=fake_data,ModelType='FermiChopperModel',
-                           Parameters="AngularVelocity=chopper_speed_log,ChopperRadius=0.049,SlitThickness=0.0023,SlitRadius=1.3,Ei=Ei,JitterSigma=0.0")
+                           Parameters="AngularVelocity=chopper_speed_log,ChopperRadius=0.049,\
+                           SlitThickness=0.0023,SlitRadius=1.3,Ei=Ei,JitterSigma=0.0")
 
         ##
         ## UB matrix
@@ -88,9 +89,9 @@ class TobyFitResolutionSimulationTest(MantidStressTest):
 
         # Create the MD workspace
         qscale = 'Q in A^-1'
-        fake_md = ConvertToMD(  InputWorkspace=fake_data, QDimensions="Q3D", QConversionScales=qscale,
-                                SplitInto=[3], SplitThreshold=100,
-        		                MinValues="-15,-15,-15,-30", MaxValues="25,25,25,279",OverwriteExisting=True)
+        fake_md = ConvertToMD(InputWorkspace=fake_data, QDimensions="Q3D", QConversionScales=qscale,
+                              SplitInto=[3], SplitThreshold=100,MinValues="-15,-15,-15,-30",
+                              MaxValues="25,25,25,279",OverwriteExisting=True)
 
         # Run the simulation.
         resol_model = "TobyFitResolutionModel"
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/UnweightedLeastSquaresTest.py b/Code/Mantid/Testing/SystemTests/tests/analysis/UnweightedLeastSquaresTest.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1d819298fa396304adcc1e78ce752bab3f578f8
--- /dev/null
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/UnweightedLeastSquaresTest.py
@@ -0,0 +1,136 @@
+# pylint: disable=no-init,invalid-name,too-few-public-methods
+#
+# These system test perform some of the fits provided by NIST for non-linear
+# least square systems that can be found here:
+# http://www.itl.nist.gov/div898/strd/nls/nls_main.shtml
+import stresstesting
+from mantid.simpleapi import *
+
+
+def runFit(x, y, fn):
+    ws = CreateWorkspace(x, y)
+
+    Fit(fn, ws, Output='ws',
+        Minimizer='Levenberg-Marquardt',
+        CostFunction="Unweighted least squares")
+
+    param_table = mtd['ws_Parameters']
+
+    params = param_table.column(1)[:-1]
+    errors = param_table.column(2)[:-1]
+
+    return params, errors
+
+
+class LeastSquaresNISTRat43Test(stresstesting.MantidStressTest):
+    def runTest(self):
+        x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
+        y = [16.08, 33.83, 65.8, 97.2, 191.55, 326.2, 386.87, 520.53, 590.03, 651.92, 724.93, 699.56, 689.96, 637.56,
+             717.41]
+
+        function = 'name=UserFunction,Formula=b1/((1+exp(b2-b3*x))^(1/b4)),b1=700,b2=5,b3=0.75,b4=1.3'
+
+        params, errors = runFit(x, y, function)
+
+        expected_params = [6.9964151270E+02, 5.2771253025E+00, 7.5962938329E-01, 1.2792483859E+00]
+        expected_errors = [1.6302297817E+01, 2.0828735829E+00, 1.9566123451E-01, 6.8761936385E-01]
+
+        for err, expected in zip(errors, expected_errors):
+            self.assertDelta(err / expected - 1.0, 0.0, 3e-2)
+
+        for val, expected in zip(params, expected_params):
+            self.assertDelta(val / expected - 1.0, 0.0, 3e-3)
+
+
+class LeastSquaresNISTGauss3Test(stresstesting.MantidStressTest):
+    def runTest(self):
+        x = [1.000000, 2.000000, 3.000000, 4.000000, 5.000000, 6.000000, 7.000000, 8.000000, 9.000000, 10.000000,
+             11.00000, 12.00000, 13.00000, 14.00000, 15.00000, 16.00000, 17.00000, 18.00000, 19.00000, 20.00000,
+             21.00000, 22.00000, 23.00000, 24.00000, 25.00000, 26.00000, 27.00000, 28.00000, 29.00000, 30.00000,
+             31.00000, 32.00000, 33.00000, 34.00000, 35.00000, 36.00000, 37.00000, 38.00000, 39.00000, 40.00000,
+             41.00000, 42.00000, 43.00000, 44.00000, 45.00000, 46.00000, 47.00000, 48.00000, 49.00000, 50.00000,
+             51.00000, 52.00000, 53.00000, 54.00000, 55.00000, 56.00000, 57.00000, 58.00000, 59.00000, 60.00000,
+             61.00000, 62.00000, 63.00000, 64.00000, 65.00000, 66.00000, 67.00000, 68.00000, 69.00000, 70.00000,
+             71.00000, 72.00000, 73.00000, 74.00000, 75.00000, 76.00000, 77.00000, 78.00000, 79.00000, 80.00000,
+             81.00000, 82.00000, 83.00000, 84.00000, 85.00000, 86.00000, 87.00000, 88.00000, 89.00000, 90.00000,
+             91.00000, 92.00000, 93.00000, 94.00000, 95.00000, 96.00000, 97.00000, 98.00000, 99.00000, 100.00000,
+             101.00000, 102.00000, 103.00000, 104.00000, 105.00000, 106.0000, 107.0000, 108.0000, 109.0000, 110.0000,
+             111.0000, 112.0000, 113.0000, 114.0000, 115.0000, 116.0000, 117.0000, 118.0000, 119.0000, 120.0000,
+             121.0000, 122.0000, 123.0000, 124.0000, 125.0000, 126.0000, 127.0000, 128.0000, 129.0000, 130.0000,
+             131.0000, 132.0000, 133.0000, 134.0000, 135.0000, 136.0000, 137.0000, 138.0000, 139.0000, 140.0000,
+             141.0000, 142.0000, 143.0000, 144.0000, 145.0000, 146.0000, 147.0000, 148.0000, 149.0000, 150.0000,
+             151.0000, 152.0000, 153.0000, 154.0000, 155.0000, 156.0000, 157.0000, 158.0000, 159.0000, 160.0000,
+             161.0000, 162.0000, 163.0000, 164.0000, 165.0000, 166.0000, 167.0000, 168.0000, 169.0000, 170.0000,
+             171.0000, 172.0000, 173.0000, 174.0000, 175.0000, 176.0000, 177.0000, 178.0000, 179.0000, 180.0000,
+             181.0000, 182.0000, 183.0000, 184.0000, 185.0000, 186.0000, 187.0000, 188.0000, 189.0000, 190.0000,
+             191.0000, 192.0000, 193.0000, 194.0000, 195.0000, 196.0000, 197.0000, 198.0000, 199.0000, 200.0000,
+             201.0000, 202.0000, 203.0000, 204.0000, 205.0000, 206.0000, 207.0000, 208.0000, 209.0000, 210.0000,
+             211.0000, 212.0000, 213.0000, 214.0000, 215.0000, 216.0000, 217.0000, 218.0000, 219.0000, 220.0000,
+             221.0000, 222.0000, 223.0000, 224.0000, 225.0000, 226.0000, 227.0000, 228.0000, 229.0000, 230.0000,
+             231.0000, 232.0000, 233.0000, 234.0000, 235.0000, 236.0000, 237.0000, 238.0000, 239.0000, 240.0000,
+             241.0000, 242.0000, 243.0000, 244.0000, 245.0000, 246.0000, 247.0000, 248.0000, 249.0000, 250.0000]
+        y = [97.58776, 97.76344, 96.56705, 92.52037, 91.15097, 95.21728, 90.21355, 89.29235, 91.51479, 89.60965,
+             86.56187, 85.55315, 87.13053, 85.67938, 80.04849, 82.18922, 87.24078, 80.79401, 81.28564, 81.56932,
+             79.22703, 79.43259, 77.90174, 76.75438, 77.17338, 74.27296, 73.11830, 73.84732, 72.47746, 71.92128,
+             66.91962, 67.93554, 69.55841, 69.06592, 66.53371, 63.87094, 69.70526, 63.59295, 63.35509, 59.99747,
+             62.64843, 65.77345, 59.10141, 56.57750, 61.15313, 54.30767, 62.83535, 56.52957, 56.98427, 58.11459,
+             58.69576, 58.23322, 54.90490, 57.91442, 56.96629, 51.13831, 49.27123, 52.92668, 54.47693, 51.81710,
+             51.05401, 52.51731, 51.83710, 54.48196, 49.05859, 50.52315, 50.32755, 46.44419, 50.89281, 52.13203,
+             49.78741, 49.01637, 54.18198, 53.17456, 53.20827, 57.43459, 51.95282, 54.20282, 57.46687, 53.60268,
+             58.86728, 57.66652, 63.71034, 65.24244, 65.10878, 69.96313, 68.85475, 73.32574, 76.21241, 78.06311,
+             75.37701, 87.54449, 89.50588, 95.82098, 97.48390, 100.86070, 102.48510, 105.7311, 111.3489, 111.0305,
+             110.1920, 118.3581, 118.8086, 122.4249, 124.0953, 125.9337, 127.8533, 131.0361, 133.3343, 135.1278,
+             131.7113, 131.9151, 132.1107, 127.6898, 133.2148, 128.2296, 133.5902, 127.2539, 128.3482, 124.8694,
+             124.6031, 117.0648, 118.1966, 119.5408, 114.7946, 114.2780, 120.3484, 114.8647, 111.6514, 110.1826,
+             108.4461, 109.0571, 106.5308, 109.4691, 106.8709, 107.3192, 106.9000, 109.6526, 107.1602, 108.2509,
+             104.96310, 109.3601, 107.6696, 99.77286, 104.96440, 106.1376, 106.5816, 100.12860, 101.66910, 96.44254,
+             97.34169, 96.97412, 90.73460, 93.37949, 82.12331, 83.01657, 78.87360, 74.86971, 72.79341, 65.14744,
+             67.02127, 60.16136, 57.13996, 54.05769, 50.42265, 47.82430, 42.85748, 42.45495, 38.30808, 36.95794,
+             33.94543, 34.19017, 31.66097, 23.56172, 29.61143, 23.88765, 22.49812, 24.86901, 17.29481, 18.09291,
+             15.34813, 14.77997, 13.87832, 12.88891, 16.20763, 16.29024, 15.29712, 14.97839, 12.11330, 14.24168,
+             12.53824, 15.19818, 11.70478, 15.83745, 10.035850, 9.307574, 12.86800, 8.571671, 11.60415, 12.42772,
+             11.23627, 11.13198, 7.761117, 6.758250, 14.23375, 10.63876, 8.893581, 11.55398, 11.57221, 11.58347,
+             9.724857, 11.43854, 11.22636, 10.170150, 12.50765, 6.200494, 9.018902, 10.80557, 13.09591, 3.914033,
+             9.567723, 8.038338, 10.230960, 9.367358, 7.695937, 6.118552, 8.793192, 7.796682, 12.45064, 10.61601,
+             6.001000, 6.765096, 8.764652, 4.586417, 8.390782, 7.209201, 10.012090, 7.327461, 6.525136, 2.840065,
+             10.323710, 4.790035, 8.376431, 6.263980, 2.705892, 8.362109, 8.983507, 3.362469, 1.182678, 4.875312]
+
+        function = ("name=UserFunction,Formula=b1*exp(-b2*x) + b3*exp( -(x-b4)^2 / b5^2 ) + b6*exp( -(x-b7)^2 / b8^2 ),"
+                    "b1=94.9,b2=0.009,b3=90.1,b4=113.0,b5=20.0,b6=73.8,b7=140.0,b8=20.0")
+
+        expected_params = [9.8940368970E+01, 1.0945879335E-02, 1.0069553078E+02, 1.1163619459E+02, 2.3300500029E+01,
+                           7.3705031418E+01, 1.4776164251E+02, 1.9668221230E+01]
+
+        expected_errors = [5.3005192833E-01, 1.2554058911E-04, 8.1256587317E-01, 3.5317859757E-01, 3.6584783023E-01,
+                           1.2091239082E+00, 4.0488183351E-01, 3.7806634336E-01]
+
+        params, errors = runFit(x, y, function)
+
+        for err, expected in zip(errors, expected_errors):
+            self.assertDelta(err / expected - 1.0, 0.0, 1e-2)
+
+        for val, expected in zip(params, expected_params):
+            self.assertDelta(val / expected - 1.0, 0.0, 2e-5)
+
+
+class LeastSquaresNISTMGH09Test(stresstesting.MantidStressTest):
+    def runTest(self):
+        x = [4.000000E+00, 2.000000E+00, 1.000000E+00, 5.000000E-01, 2.500000E-01, 1.670000E-01, 1.250000E-01,
+             1.000000E-01, 8.330000E-02, 7.140000E-02, 6.250000E-02]
+
+        y = [1.957000E-01, 1.947000E-01, 1.735000E-01, 1.600000E-01, 8.440000E-02, 6.270000E-02, 4.560000E-02,
+             3.420000E-02, 3.230000E-02, 2.350000E-02, 2.460000E-02]
+
+        # Second set of starting parameters.
+        function = 'name=UserFunction,Formula=b1*(x^2+x*b2) / (x^2+x*b3+b4),b1=0.25,b2=0.39,b3=0.415,b4=0.39'
+
+        params, errors = runFit(x, y, function)
+
+        expected_params = [1.9280693458E-01,1.9128232873E-01,1.2305650693E-01,1.3606233068E-01]
+        expected_errors = [1.1435312227E-02,1.9633220911E-01,8.0842031232E-02,9.0025542308E-02]
+
+        for err, expected in zip(errors, expected_errors):
+            self.assertDelta(err / expected - 1.0, 0.0, 1e-3)
+
+        for val, expected in zip(params, expected_params):
+            self.assertDelta(val / expected - 1.0, 0.0, 3e-4)
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/reference/II.TOSCAMultiFileReduction2.nxs.md5 b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/II.TOSCAMultiFileReduction2.nxs.md5
index e1bc4905088eab0399d2e77978e0d0e8fd44da2b..44c6c182cc2ce4dad9e05be1deefd9a15c64eccb 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/reference/II.TOSCAMultiFileReduction2.nxs.md5
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/II.TOSCAMultiFileReduction2.nxs.md5
@@ -1 +1 @@
-ed6aea923444b6d1c6e5dfd810cb329f
\ No newline at end of file
+b7c86ee67f2e306c7fffd85403cba548
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/reference/LiquidsReflectometryReductionTestWithBackground.nxs.md5 b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/LiquidsReflectometryReductionTestWithBackground.nxs.md5
index 940997695321557922c5ad265728675c64dcd8a2..e4dd2d4bdeee3ae4c87f1c061128b3c8ae641a9a 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/reference/LiquidsReflectometryReductionTestWithBackground.nxs.md5
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/LiquidsReflectometryReductionTestWithBackground.nxs.md5
@@ -1 +1 @@
-791a2b2fe751b8af599a5b97aa2ce3a4
+32043ffb3ff3964d1b6c332b670afd7c
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/reference/REFL_119814_combined_data_v2.nxs.md5 b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/REFL_119814_combined_data_v2.nxs.md5
new file mode 100644
index 0000000000000000000000000000000000000000..f80ec2d3a5e2eaf91d10720e64840bc24a48acc2
--- /dev/null
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/REFL_119814_combined_data_v2.nxs.md5
@@ -0,0 +1 @@
+b4185bb9f084032982784e50ededebf7
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/reference/REFL_NoBackgroundTest.nxs.md5 b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/REFL_NoBackgroundTest.nxs.md5
index 50c84eda0f98cb1be5690c3fee5a7e2bcae7e70f..1272da5d4a62406e60f899e90838622cccda4b06 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/reference/REFL_NoBackgroundTest.nxs.md5
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/REFL_NoBackgroundTest.nxs.md5
@@ -1 +1 @@
-20bed05c1d84537f743afbb10dfad067
+329a3f2503d9cb3bee302efcf68af181
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/reference/REFL_NoNormalizationTest.nxs.md5 b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/REFL_NoNormalizationTest.nxs.md5
index 5b0dc67f9ef22bfb0fe1cd481af777850643cbf4..d8ae6307ab73eba2dd855326c9cbe8e4d2da2746 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/reference/REFL_NoNormalizationTest.nxs.md5
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/REFL_NoNormalizationTest.nxs.md5
@@ -1 +1 @@
-713537859017897277e049c17d7f3fe4
+88ffaa8d49e827ad3456599fd7320c7c
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/reference/SANS2DLoadingAddedEventData.nxs.md5 b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/SANS2DLoadingAddedEventData.nxs.md5
new file mode 100644
index 0000000000000000000000000000000000000000..010396cbf6e4a735744fa7d2c5d611f09990a8bc
--- /dev/null
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/SANS2DLoadingAddedEventData.nxs.md5
@@ -0,0 +1 @@
+c6363d39533b410090d0b3f754c3f73e
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/reference/SANS2DLoadingAddedEventDataMonitor.nxs.md5 b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/SANS2DLoadingAddedEventDataMonitor.nxs.md5
new file mode 100644
index 0000000000000000000000000000000000000000..aa692778df2755f5f73d937845a1458ad9d7e22f
--- /dev/null
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/SANS2DLoadingAddedEventDataMonitor.nxs.md5
@@ -0,0 +1 @@
+3ddae20b3ce716c46cda62467f904b90
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/reference/TOFRangeOFFTest.nxs.md5 b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/TOFRangeOFFTest.nxs.md5
index c1ad112e814e252a1587bc2cefe4db2383e6bf57..52dda1c0e2b8e6a976d97d2db33dfe7fc18b062d 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/reference/TOFRangeOFFTest.nxs.md5
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/TOFRangeOFFTest.nxs.md5
@@ -1 +1 @@
-2460ea1adf15e55f788c0b7def73dc58
+b85f69361aab0d026ed007e4b79a85a8
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/PeaksFilter/CMakeLists.txt b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/PeaksFilter/CMakeLists.txt
index a9f5477cb67e0e7ec322aa736f0b5dfc34fe0aeb..d799dc4e668c3b21c1af04be7183f5e45b6913ac 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/PeaksFilter/CMakeLists.txt
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/PeaksFilter/CMakeLists.txt
@@ -2,13 +2,15 @@ PROJECT(PeaksFilter)
 include_directories( SYSTEM ${PARAVIEW_INCLUDE_DIRS} )
 ADD_PARAVIEW_PLUGIN(MantidParaViewPeaksFilterSMPlugin "1.0"
 SERVER_MANAGER_XML PeaksFilter.xml
-SERVER_MANAGER_SOURCES vtkPeaksFilter.cxx
-GUI_RESOURCE_FILES PeaksFilterGUI.xml)
+SERVER_MANAGER_SOURCES vtkPeaksFilter.cxx)
 # Add to the 'VatesParaViewPlugins' group in VS
 set_property( TARGET MantidParaViewPeaksFilterSMPlugin PROPERTY FOLDER "MantidVatesParaViewPlugins")
 
-target_link_libraries( MantidParaViewPeaksFilterSMPlugin
-${MANTID_SUBPROJECT_LIBS} )
+target_link_libraries( MantidParaViewPeaksFilterSMPlugin LINK_PUBLIC ${MANTID_SUBPROJECT_LIBS} )
+
+if (OSX_VERSION VERSION_GREATER 10.8)
+  set_target_properties ( MantidParaViewPeaksFilterSMPlugin PROPERTIES INSTALL_RPATH "@loader_path/../../Contents/Libraries;@loader_path/../../Contents/MacOS")
+endif ()
 
 # Put library into subfolder.
 SET_TARGET_OUTPUT_DIRECTORY(MantidParaViewPeaksFilterSMPlugin  ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${CMAKE_CFG_INTDIR}/${PVPLUGINS_DIR}/${PVPLUGINS_SUBDIR})
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/PeaksFilter/PeaksFilter.xml b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/PeaksFilter/PeaksFilter.xml
index 1467d2c912c6d2a89b5989623140b1432bb75abf..c185ee066b4036b6d3d69e55bace9ae56e8a57e4 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/PeaksFilter/PeaksFilter.xml
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/PeaksFilter/PeaksFilter.xml
@@ -2,6 +2,9 @@
   <!-- Begin ScaleWorkspace -->
   <ProxyGroup name="filters">
     <SourceProxy name="MantidParaViewPeaksFilter" class="vtkPeaksFilter" label="MD Peaks Filter" >
+      <Hints>
+        <ShowInMenu category="Mantid"/>
+      </Hints>
       <InputProperty
         name="Input"
         command="SetInputConnection">
@@ -37,4 +40,4 @@
     </SourceProxy>
   </ProxyGroup>
   <!-- End ScaleWorkspace -->
-</ServerManagerConfiguration>
\ No newline at end of file
+</ServerManagerConfiguration>
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/PeaksFilter/vtkPeaksFilter.h b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/PeaksFilter/vtkPeaksFilter.h
index 272795e238061dca43cbf1c8fe56192df84a3401..96e23567bdeafa0ddddc6ca18fc357e76d3b45aa 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/PeaksFilter/vtkPeaksFilter.h
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/PeaksFilter/vtkPeaksFilter.h
@@ -11,7 +11,7 @@ class VTK_EXPORT vtkPeaksFilter : public vtkUnstructuredGridAlgorithm
 {
 public:
   static vtkPeaksFilter *New();
-  vtkTypeMacro(vtkPeaksFilter, vtkUnstructuredGridAlgorithm);
+  vtkTypeMacro(vtkPeaksFilter, vtkUnstructuredGridAlgorithm)
   void PrintSelf(ostream& os, vtkIndent indent);
   void SetPeaksWorkspace(std::string peaksWorkspaceName);
   void SetRadiusNoShape(double radius);
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/CMakeLists.txt b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/CMakeLists.txt
index 056b2b05e3ab0277365d923b6b417f4ec79bce8d..46b81b52aef870634bcc8e9674e8fed302b1026a 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/CMakeLists.txt
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/CMakeLists.txt
@@ -2,14 +2,17 @@ PROJECT(ScaleWorkspace)
 include_directories( SYSTEM ${PARAVIEW_INCLUDE_DIRS} )
 ADD_PARAVIEW_PLUGIN(MantidParaViewScaleWorkspaceSMPlugin "1.0"
 SERVER_MANAGER_XML ScaleWorkspace.xml
-SERVER_MANAGER_SOURCES vtkScaleWorkspace.cxx
-GUI_RESOURCE_FILES ScaleWorkspaceGUI.xml)
+SERVER_MANAGER_SOURCES vtkScaleWorkspace.cxx)
 # Add to the 'VatesParaViewPlugins' group in VS
 set_property( TARGET MantidParaViewScaleWorkspaceSMPlugin PROPERTY FOLDER "MantidVatesParaViewPlugins")
 
-target_link_libraries( MantidParaViewScaleWorkspaceSMPlugin
+target_link_libraries( MantidParaViewScaleWorkspaceSMPlugin LINK_PUBLIC
 ${MANTID_SUBPROJECT_LIBS} )
 
+if (OSX_VERSION VERSION_GREATER 10.8)
+  set_target_properties ( MantidParaViewScaleWorkspaceSMPlugin PROPERTIES INSTALL_RPATH "@loader_path/../../Contents/Libraries;@loader_path/../../Contents/MacOS")
+endif ()
+
 # Put library into subfolder.
 SET_TARGET_OUTPUT_DIRECTORY(MantidParaViewScaleWorkspaceSMPlugin  ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${CMAKE_CFG_INTDIR}/${PVPLUGINS_DIR}/${PVPLUGINS_SUBDIR})
 
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/ScaleWorkspace.xml b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/ScaleWorkspace.xml
index 380139ad7805a395a349457586995a4469fa1b5d..83774514ed8c37c3038c4f3a6a07817c2ed2f100 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/ScaleWorkspace.xml
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/ScaleWorkspace.xml
@@ -2,6 +2,9 @@
   <!-- Begin ScaleWorkspace -->
   <ProxyGroup name="filters">
     <SourceProxy name="MantidParaViewScaleWorkspace" class="vtkScaleWorkspace" label="MD Scale Workspace" >
+      <Hints>
+        <ShowInMenu category="Mantid"/>
+      </Hints>
       <InputProperty
         name="Input"
         command="SetInputConnection">
@@ -25,4 +28,4 @@
     </SourceProxy>
   </ProxyGroup>
   <!-- End ScaleWorkspace -->
-</ServerManagerConfiguration>
\ No newline at end of file
+</ServerManagerConfiguration>
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/vtkScaleWorkspace.cxx b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/vtkScaleWorkspace.cxx
index e9b15021d609133cb6f51eed9b88836e0b8f1f2e..cb73097af1a5fd6acf1c30ef7db50a9c97f5cd6e 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/vtkScaleWorkspace.cxx
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/vtkScaleWorkspace.cxx
@@ -19,6 +19,8 @@ vtkScaleWorkspace::vtkScaleWorkspace() :
   m_xScaling(1),
   m_yScaling(1),
   m_zScaling(1),
+  m_minValue(0.1),
+  m_maxValue(0.1),
   m_specialCoordinates(-1),
   m_metadataJsonManager(new MetadataJsonManager()),
   m_vatesConfigurations(new VatesConfigurations())
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/vtkScaleWorkspace.h b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/vtkScaleWorkspace.h
index 1a0065a478f40816f1f19d9b90cc409470d57eff..de4d54991d0e47166611445d15e7d0a7ce8e749a 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/vtkScaleWorkspace.h
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/vtkScaleWorkspace.h
@@ -10,7 +10,7 @@ class VTK_EXPORT vtkScaleWorkspace : public vtkUnstructuredGridAlgorithm
 {
 public:
   static vtkScaleWorkspace *New();
-  vtkTypeMacro(vtkScaleWorkspace, vtkUnstructuredGridAlgorithm);
+  vtkTypeMacro(vtkScaleWorkspace, vtkUnstructuredGridAlgorithm)
   void PrintSelf(ostream& os, vtkIndent indent);
   void SetXScaling(double xScaling);
   void SetYScaling(double yScaling);
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/SplatterPlot/CMakeLists.txt b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/SplatterPlot/CMakeLists.txt
index 3d3208936b160accd33e8118ba8f07e952fc1774..bb006eb7f9355b6aff6b72d3cfcbbdab7ab82556 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/SplatterPlot/CMakeLists.txt
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/SplatterPlot/CMakeLists.txt
@@ -3,17 +3,20 @@ include_directories( SYSTEM ${PARAVIEW_INCLUDE_DIRS} )
 ADD_PARAVIEW_PLUGIN(MantidParaViewSplatterPlotSMPlugin "1.0"
 	SERVER_MANAGER_XML SplatterPlot.xml
 	SERVER_MANAGER_SOURCES vtkSplatterPlot.cxx
-	GUI_RESOURCES SplatterPlot.qrc
-	GUI_RESOURCE_FILES SplatterPlotGUI.xml)
+	GUI_RESOURCES SplatterPlot.qrc)
 	
 # Add to the 'VatesParaViewPlugins' group in VS
 set_property( TARGET MantidParaViewSplatterPlotSMPlugin PROPERTY FOLDER "MantidVatesParaViewPlugins" )
 
 include_directories ( SYSTEM ${QWT_INCLUDE_DIR} )
 
-target_link_libraries( MantidParaViewSplatterPlotSMPlugin 
+target_link_libraries( MantidParaViewSplatterPlotSMPlugin LINK_PUBLIC 
 ${MANTID_SUBPROJECT_LIBS} ${QWT_LIBRARIES})
 
+if (OSX_VERSION VERSION_GREATER 10.8)
+  set_target_properties ( MantidParaViewSplatterPlotSMPlugin PROPERTIES INSTALL_RPATH "@loader_path/../../Contents/Libraries;@loader_path/../../Contents/MacOS")
+endif ()
+
 # Put library into subfolder.
 SET_TARGET_OUTPUT_DIRECTORY(MantidParaViewSplatterPlotSMPlugin ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${CMAKE_CFG_INTDIR}/${PVPLUGINS_DIR}/${PVPLUGINS_SUBDIR})
 
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/SplatterPlot/SplatterPlot.xml b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/SplatterPlot/SplatterPlot.xml
index 7c4dd419679452d87510376d9dd9602b56e94393..93b9eaca57eb2caa0776aff48548300dc4312820 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/SplatterPlot/SplatterPlot.xml
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/SplatterPlot/SplatterPlot.xml
@@ -2,6 +2,9 @@
   <!-- Begin SplatterPlot -->
   <ProxyGroup name="filters">
     <SourceProxy name="MantidParaViewSplatterPlot" class="vtkSplatterPlot" label="MD Scatter Plot">
+      <Hints>
+        <ShowInMenu category="Mantid" icon=":/Splatter.png"/>
+      </Hints>
       <InputProperty
         name="Input"
         command="SetInputConnection">
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/SplatterPlot/vtkSplatterPlot.h b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/SplatterPlot/vtkSplatterPlot.h
index ff3c7117e90ee9137ce2e77dfa1e5c2507a5678f..f44ef1e8f50c427e07569f932631a1cddd0c8860 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/SplatterPlot/vtkSplatterPlot.h
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/SplatterPlot/vtkSplatterPlot.h
@@ -17,7 +17,7 @@ class VTK_EXPORT vtkSplatterPlot : public vtkUnstructuredGridAlgorithm
 {
 public:
   static vtkSplatterPlot *New();
-  vtkTypeMacro(vtkSplatterPlot, vtkUnstructuredGridAlgorithm);
+  vtkTypeMacro(vtkSplatterPlot, vtkUnstructuredGridAlgorithm)
   double getTime() const;
   void PrintSelf(ostream& os, vtkIndent indent);
   void SetNumberOfPoints(int nPoints);
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/CMakeLists.txt b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/CMakeLists.txt
index 5537e38b62060127c5fb4d58d948d546be8762f2..5e98df4ff82639cf2dd9c74cffa72813cee690c8 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/CMakeLists.txt
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/CMakeLists.txt
@@ -3,7 +3,6 @@ include_directories( SYSTEM ${PARAVIEW_INCLUDE_DIRS} )
 add_paraview_plugin( MantidParaViewEventNexusReaderSMPlugin "1.0"
 	SERVER_MANAGER_XML EventNexusReader.xml
 	SERVER_MANAGER_SOURCES vtkEventNexusReader.cxx
-	GUI_RESOURCE_FILES EventNexusReaderGUI.xml
 )
 
 # Add to the 'VatesParaViewPlugins' group in VS
@@ -11,8 +10,11 @@ set_property( TARGET MantidParaViewEventNexusReaderSMPlugin PROPERTY FOLDER "Man
 
 include_directories ( SYSTEM ${QWT_INCLUDE_DIR} )
 
-target_link_libraries( MantidParaViewEventNexusReaderSMPlugin 
-${MANTID_SUBPROJECT_LIBS} ${QWT_LIBRARIES})
+target_link_libraries( MantidParaViewEventNexusReaderSMPlugin LINK_PUBLIC ${MANTID_SUBPROJECT_LIBS} ${QWT_LIBRARIES})
+
+if (OSX_VERSION VERSION_GREATER 10.8)
+  set_target_properties ( MantidParaViewEventNexusReaderSMPlugin PROPERTIES INSTALL_RPATH "@loader_path/../../Contents/Libraries;@loader_path/../../Contents/MacOS")
+endif ()
 
 # Put library into subfolder.
 SET_TARGET_OUTPUT_DIRECTORY(MantidParaViewEventNexusReaderSMPlugin ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${CMAKE_CFG_INTDIR}/${PVPLUGINS_DIR}/${PVPLUGINS_SUBDIR})
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/EventNexusReader.xml b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/EventNexusReader.xml
index 1002f17e9fdb533bac581381dae9f7b8bad9ca84..1aa53472280d2bc921847362747ecb1a8269fb11 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/EventNexusReader.xml
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/EventNexusReader.xml
@@ -43,7 +43,12 @@
           Available timestep values.
         </Documentation>
       </DoubleVectorProperty>
+      <Hints>
+        <ReaderFactory
+          extensions="nxs"
+          file_description="Event Nexus File" />
+      </Hints>
     </SourceProxy>
   </ProxyGroup>
   <!-- End EventNexusReader -->
-</ServerManagerConfiguration>
\ No newline at end of file
+</ServerManagerConfiguration>
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/vtkEventNexusReader.cxx b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/vtkEventNexusReader.cxx
index 6edd4d02dad28f5390c1fa7bae58800858712a37..c48089d1f5af1a256f6921b654b25f8a9d62cd0d 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/vtkEventNexusReader.cxx
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/vtkEventNexusReader.cxx
@@ -9,6 +9,7 @@
 #include "vtkFloatArray.h"
 #include "vtkStreamingDemandDrivenPipeline.h"
 #include "vtkPVClipDataSet.h"
+#include "vtkPVInformationKeys.h"
 #include "vtkBox.h"
 #include "vtkUnstructuredGrid.h"
 #include "MantidVatesAPI/vtkMDHexFactory.h"
@@ -199,7 +200,7 @@ void vtkEventNexusReader::setTimeRange(vtkInformationVector* outputVector)
   if(m_presenter->hasTDimensionAvailable())
   {
     vtkInformation *outInfo = outputVector->GetInformationObject(0);
-    outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_LABEL_ANNOTATION(),
+    outInfo->Set(vtkPVInformationKeys::TIME_LABEL_ANNOTATION(),
                  m_presenter->getTimeStepLabel().c_str());
     std::vector<double> timeStepValues = m_presenter->getTimeStepValues();
     outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(), &timeStepValues[0],
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/vtkEventNexusReader.h b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/vtkEventNexusReader.h
index e65894cca868a2749679196fe7c1246c3ea8415b..a2dfe17e027145ca5f5ec27a91bc1d143e355d1a 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/vtkEventNexusReader.h
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/vtkEventNexusReader.h
@@ -17,7 +17,7 @@ public:
   //----------------------------------------------
 
   static vtkEventNexusReader *New();
-  vtkTypeMacro(vtkEventNexusReader, vtkUnstructuredGridAlgorithm);
+  vtkTypeMacro(vtkEventNexusReader, vtkUnstructuredGridAlgorithm)
   void PrintSelf(ostream& os, vtkIndent indent);
   vtkSetStringMacro(FileName);
   vtkGetStringMacro(FileName);
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/CMakeLists.txt b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/CMakeLists.txt
index c7b74fc70f15a434c697c3d51ff59cb360cd2352..cd89b857ab9d4c5644f27dc0859bcb1e13851b74 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/CMakeLists.txt
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/CMakeLists.txt
@@ -3,7 +3,6 @@ include_directories( SYSTEM ${PARAVIEW_INCLUDE_DIRS} )
 add_paraview_plugin( MantidParaViewMDEWNexusReaderSMPlugin "1.0"
 	SERVER_MANAGER_XML MDEWNexusReader.xml
 	SERVER_MANAGER_SOURCES vtkMDEWNexusReader.cxx
-	GUI_RESOURCE_FILES MDEWNexusReaderGUI.xml
 )
 
 # Add to the 'VatesParaViewPlugins' group in VS
@@ -11,8 +10,11 @@ set_property( TARGET MantidParaViewMDEWNexusReaderSMPlugin PROPERTY FOLDER "Mant
 
 include_directories ( SYSTEM ${QWT_INCLUDE_DIR} )
 
-target_link_libraries( MantidParaViewMDEWNexusReaderSMPlugin 
-${MANTID_SUBPROJECT_LIBS} ${QWT_LIBRARIES})
+target_link_libraries( MantidParaViewMDEWNexusReaderSMPlugin LINK_PUBLIC ${MANTID_SUBPROJECT_LIBS} ${QWT_LIBRARIES})
+
+if (OSX_VERSION VERSION_GREATER 10.8)
+  set_target_properties ( MantidParaViewMDEWNexusReaderSMPlugin PROPERTIES INSTALL_RPATH "@loader_path/../../Contents/Libraries;@loader_path/../../Contents/MacOS")
+endif ()
 
 # Put library into subfolder.
 SET_TARGET_OUTPUT_DIRECTORY(MantidParaViewMDEWNexusReaderSMPlugin ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${CMAKE_CFG_INTDIR}/${PVPLUGINS_DIR}/${PVPLUGINS_SUBDIR})
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/MDEWNexusReader.xml b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/MDEWNexusReader.xml
index 2d40df60f38d6f1798331703801d6c61cd1c7344..13657926b55e551b8e790dcd2311eb27b5936381 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/MDEWNexusReader.xml
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/MDEWNexusReader.xml
@@ -48,6 +48,11 @@
         information_only="1"
         si_class="vtkSITimeLabelProperty">
       </StringVectorProperty>
+      <Hints>
+        <ReaderFactory
+          extensions="nxs"
+          file_description="MDEW Nexus File" />
+      </Hints>
     </SourceProxy>
   </ProxyGroup>
   <!-- End MDEWNexusReader -->
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.cxx b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.cxx
index 880b277761c1022eef60995f53879fa5a5713ca4..4eeb30cca8c852f57cab81afd317b0897077ae09 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.cxx
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.cxx
@@ -9,6 +9,7 @@
 #include "vtkFloatArray.h"
 #include "vtkStreamingDemandDrivenPipeline.h"
 #include "vtkPVClipDataSet.h"
+#include "vtkPVInformationKeys.h"
 #include "vtkBox.h"
 #include "vtkUnstructuredGrid.h"
 
@@ -205,7 +206,7 @@ void vtkMDEWNexusReader::setTimeRange(vtkInformationVector* outputVector)
   if(m_presenter->hasTDimensionAvailable())
   {
     vtkInformation *outInfo = outputVector->GetInformationObject(0);
-    outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_LABEL_ANNOTATION(),
+    outInfo->Set(vtkPVInformationKeys::TIME_LABEL_ANNOTATION(),
                  m_presenter->getTimeStepLabel().c_str());
     std::vector<double> timeStepValues = m_presenter->getTimeStepValues();
     outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(), &timeStepValues[0],
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.h b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.h
index 0d7533f64f4bb90ac5d9bc99d3dfc1721d683217..1b1431072eae37834bcfc75abf55de3c750975f6 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.h
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.h
@@ -11,10 +11,10 @@ class VTK_EXPORT vtkMDEWNexusReader : public vtkUnstructuredGridAlgorithm
 public:
 
   static vtkMDEWNexusReader *New();
-  vtkTypeMacro(vtkMDEWNexusReader, vtkUnstructuredGridAlgorithm);
+  vtkTypeMacro(vtkMDEWNexusReader, vtkUnstructuredGridAlgorithm)
   void PrintSelf(ostream& os, vtkIndent indent);
-  vtkSetStringMacro(FileName);
-  vtkGetStringMacro(FileName);
+  vtkSetStringMacro(FileName)
+  vtkGetStringMacro(FileName)
   int CanReadFile(const char* fname);
   void SetInMemory(bool inMemory);
   void SetDepth(int depth);
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/CMakeLists.txt b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/CMakeLists.txt
index 5607de2b63ea14c474d48f8e3e37633e3639cf5d..511ff2bc512d1968b7ffd8d5b4ba90c549fb11e5 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/CMakeLists.txt
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/CMakeLists.txt
@@ -3,7 +3,6 @@ include_directories( SYSTEM ${PARAVIEW_INCLUDE_DIRS} )
 add_paraview_plugin( MantidParaViewMDHWNexusReaderSMPlugin "1.0"
 	SERVER_MANAGER_XML MDHWNexusReader.xml
 	SERVER_MANAGER_SOURCES vtkMDHWNexusReader.cxx
-	GUI_RESOURCE_FILES MDHWNexusReaderGUI.xml
 )
 
 # Add to the 'VatesParaViewPlugins' group in VS
@@ -11,8 +10,11 @@ set_property( TARGET MantidParaViewMDHWNexusReaderSMPlugin PROPERTY FOLDER "Mant
 
 include_directories ( SYSTEM ${QWT_INCLUDE_DIR} )
 
-target_link_libraries( MantidParaViewMDHWNexusReaderSMPlugin 
-${MANTID_SUBPROJECT_LIBS} ${QWT_LIBRARIES})
+target_link_libraries( MantidParaViewMDHWNexusReaderSMPlugin LINK_PUBLIC ${MANTID_SUBPROJECT_LIBS} ${QWT_LIBRARIES})
+
+if (OSX_VERSION VERSION_GREATER 10.8)
+  set_target_properties ( MantidParaViewMDHWNexusReaderSMPlugin PROPERTIES INSTALL_RPATH "@loader_path/../../Contents/Libraries;@loader_path/../../Contents/MacOS")
+endif ()
 
 # Put library into subfolder.
 SET_TARGET_OUTPUT_DIRECTORY(MantidParaViewMDHWNexusReaderSMPlugin ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${CMAKE_CFG_INTDIR}/${PVPLUGINS_DIR}/${PVPLUGINS_SUBDIR})
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/MDHWNexusReader.xml b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/MDHWNexusReader.xml
index 692c863b9100f9c385ba5d81eb7eab38cb5acc51..48fe5946222adfe365cbf0d224caa492f34dace5 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/MDHWNexusReader.xml
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/MDHWNexusReader.xml
@@ -42,6 +42,11 @@
         information_only="1"
         si_class="vtkSITimeLabelProperty">
       </StringVectorProperty>
+      <Hints>
+        <ReaderFactory
+          extensions="nxs"
+          file_description="MDHW Nexus File" />
+      </Hints>
     </SourceProxy>
   </ProxyGroup>
   <!-- End MDHWNexusReader -->
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/vtkMDHWNexusReader.cxx b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/vtkMDHWNexusReader.cxx
index 834965eb2c5cff7b5ce314d5c66311dabffc5e7a..d97840f52aa3f225e87bafc6c7956a308436a35d 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/vtkMDHWNexusReader.cxx
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/vtkMDHWNexusReader.cxx
@@ -9,6 +9,7 @@
 #include "vtkFloatArray.h"
 #include "vtkStreamingDemandDrivenPipeline.h"
 #include "vtkPVClipDataSet.h"
+#include "vtkPVInformationKeys.h"
 #include "vtkBox.h"
 #include "vtkUnstructuredGrid.h"
 
@@ -208,7 +209,7 @@ void vtkMDHWNexusReader::setTimeRange(vtkInformationVector* outputVector)
   if(m_presenter->hasTDimensionAvailable())
   {
     vtkInformation *outInfo = outputVector->GetInformationObject(0);
-    outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_LABEL_ANNOTATION(),
+    outInfo->Set(vtkPVInformationKeys::TIME_LABEL_ANNOTATION(),
                  m_presenter->getTimeStepLabel().c_str());
     std::vector<double> timeStepValues = m_presenter->getTimeStepValues();
     outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(), &timeStepValues[0],
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/vtkMDHWNexusReader.h b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/vtkMDHWNexusReader.h
index b7b0d66f32bb88bc349a961113bd8be4bc65b0b3..986c9d3bc0d7e4d0ca71c62c9e64afdac3d73b9d 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/vtkMDHWNexusReader.h
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/vtkMDHWNexusReader.h
@@ -11,10 +11,10 @@ class VTK_EXPORT vtkMDHWNexusReader : public vtkUnstructuredGridAlgorithm
 public:
 
   static vtkMDHWNexusReader *New();
-  vtkTypeMacro(vtkMDHWNexusReader, vtkUnstructuredGridAlgorithm);
+  vtkTypeMacro(vtkMDHWNexusReader, vtkUnstructuredGridAlgorithm)
   void PrintSelf(ostream& os, vtkIndent indent);
-  vtkSetStringMacro(FileName);
-  vtkGetStringMacro(FileName);
+  vtkSetStringMacro(FileName)
+  vtkGetStringMacro(FileName)
   int CanReadFile(const char* fname);
   void SetInMemory(bool inMemory);
   void SetDepth(int depth);
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/NexusPeaksReader/CMakeLists.txt b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/NexusPeaksReader/CMakeLists.txt
index 9a1c7182a7630e7700bc088b25d8a8931d6bf545..4cd710a5c2fa19b9721920216a0084f99460fca7 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/NexusPeaksReader/CMakeLists.txt
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/NexusPeaksReader/CMakeLists.txt
@@ -3,15 +3,18 @@ include_directories( SYSTEM ${PARAVIEW_INCLUDE_DIRS} )
 add_paraview_plugin( MantidParaViewNexusPeaksReaderSMPlugin "1.0"
 	SERVER_MANAGER_XML NexusPeaksReader.xml
 	SERVER_MANAGER_SOURCES vtkNexusPeaksReader.cxx
-	GUI_RESOURCE_FILES NexusPeaksReaderGUI.xml
 )
 
 # Add to the 'VatesParaViewPlugins' group in VS
 set_property( TARGET MantidParaViewNexusPeaksReaderSMPlugin PROPERTY FOLDER "MantidVatesParaViewPlugins" )
 
-target_link_libraries( MantidParaViewNexusPeaksReaderSMPlugin 
+target_link_libraries( MantidParaViewNexusPeaksReaderSMPlugin LINK_PUBLIC
 ${MANTID_SUBPROJECT_LIBS} ${NEXUS_C_LIBRARIES})
 
+if (OSX_VERSION VERSION_GREATER 10.8)
+  set_target_properties ( MantidParaViewNexusPeaksReaderSMPlugin PROPERTIES INSTALL_RPATH "@loader_path/../../Contents/Libraries;@loader_path/../../Contents/MacOS")
+endif ()
+
 # Put library into subfolder.
 SET_TARGET_OUTPUT_DIRECTORY(MantidParaViewNexusPeaksReaderSMPlugin ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${CMAKE_CFG_INTDIR}/${PVPLUGINS_DIR}/${PVPLUGINS_SUBDIR})
 
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/NexusPeaksReader/NexusPeaksReader.xml b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/NexusPeaksReader/NexusPeaksReader.xml
index 9ce6cebfaece9479da9c31dbf7b7817d7e210e94..fa1be34eaac9296e0c0ef8440399b251436d14aa 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/NexusPeaksReader/NexusPeaksReader.xml
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/NexusPeaksReader/NexusPeaksReader.xml
@@ -39,6 +39,11 @@
              Set the size of the unintegrated peak markers.
            </Documentation>
          </DoubleVectorProperty>
+         <Hints>
+           <ReaderFactory
+             extensions="nxs"
+             file_description="Mantid Nexus Peaks File" />
+         </Hints>
     </SourceProxy>
   </ProxyGroup>
   <!-- End NexusPeaksReader -->
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/NexusPeaksReader/vtkNexusPeaksReader.h b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/NexusPeaksReader/vtkNexusPeaksReader.h
index 0ea3ca0d83e3e7581b8e6a807575599f56928811..d4de3978c7f5513709114c065fd008b4fe911fc4 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/NexusPeaksReader/vtkNexusPeaksReader.h
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/NexusPeaksReader/vtkNexusPeaksReader.h
@@ -1,6 +1,6 @@
 #ifndef _vtkEventNexusReader_h
 #define _vtkEventNexusReader_h
-#include "vtkPolyDataAlgorithm.h"
+#include "MantidVatesAPI/vtkPolyDataAlgorithm_Silent.h"
 #include "MantidAPI/IPeaksWorkspace.h"
 
 class vtkImplicitFunction;
@@ -9,7 +9,7 @@ class VTK_EXPORT vtkNexusPeaksReader : public vtkPolyDataAlgorithm
 {
 public:
   static vtkNexusPeaksReader *New();
-  vtkTypeMacro(vtkNexusPeaksReader, vtkPolyDataAlgorithm);
+  vtkTypeMacro(vtkNexusPeaksReader, vtkPolyDataAlgorithm)
   void PrintSelf(ostream& os, vtkIndent indent);
   vtkSetStringMacro(FileName);
   vtkGetStringMacro(FileName);
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/PeaksReader/CMakeLists.txt b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/PeaksReader/CMakeLists.txt
index 3b2407ae805533e0fb505617a7278376b6c32144..d1b587e3146ccc6991345319d29ed1062e266cfa 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/PeaksReader/CMakeLists.txt
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/PeaksReader/CMakeLists.txt
@@ -3,15 +3,18 @@ include_directories( SYSTEM ${PARAVIEW_INCLUDE_DIRS} )
 add_paraview_plugin( MantidParaViewPeaksReaderSMPlugin "1.0"
 	SERVER_MANAGER_XML PeaksReader.xml
 	SERVER_MANAGER_SOURCES vtkPeaksReader.cxx
-	GUI_RESOURCE_FILES PeaksReaderGUI.xml
 )
 
 # Add to the 'VatesParaViewPlugins' group in VS
 set_property( TARGET MantidParaViewPeaksReaderSMPlugin PROPERTY FOLDER "MantidVatesParaViewPlugins" )
 
-target_link_libraries( MantidParaViewPeaksReaderSMPlugin 
+target_link_libraries( MantidParaViewPeaksReaderSMPlugin LINK_PUBLIC
 ${MANTID_SUBPROJECT_LIBS} )
 
+if (OSX_VERSION VERSION_GREATER 10.8)
+  set_target_properties ( MantidParaViewPeaksReaderSMPlugin PROPERTIES INSTALL_RPATH "@loader_path/../../Contents/Libraries;@loader_path/../../Contents/MacOS")
+endif ()
+
 # Put library into subfolder.
 SET_TARGET_OUTPUT_DIRECTORY(MantidParaViewPeaksReaderSMPlugin ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${CMAKE_CFG_INTDIR}/${PVPLUGINS_DIR}/${PVPLUGINS_SUBDIR})
 
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/PeaksReader/PeaksReader.xml b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/PeaksReader/PeaksReader.xml
index 45b882e11d321e00b04e87ec67a1ec6bd2a8b42d..3c403f56e440d8e93855c72cfa2ebdb8ef74835d 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/PeaksReader/PeaksReader.xml
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/PeaksReader/PeaksReader.xml
@@ -39,6 +39,11 @@
              Set the size of the unintegrated peak markers.
            </Documentation>
          </DoubleVectorProperty>
+         <Hints>
+           <ReaderFactory
+             extensions="peaks"
+             file_description="ISAW Peaks File" />
+         </Hints>
     </SourceProxy>
   </ProxyGroup>
   <!-- End PeaksReader -->
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/PeaksReader/vtkPeaksReader.h b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/PeaksReader/vtkPeaksReader.h
index 14eed7f0d72ec4e412b6c85e3f6bc6c28cd97893..a2ccc5786dc092aa44c7992a9d64efb87f380c71 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/PeaksReader/vtkPeaksReader.h
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/PeaksReader/vtkPeaksReader.h
@@ -1,6 +1,6 @@
 #ifndef _vtkEventNexusReader_h
 #define _vtkEventNexusReader_h
-#include "vtkPolyDataAlgorithm.h"
+#include "MantidVatesAPI/vtkPolyDataAlgorithm_Silent.h"
 #include "MantidAPI/IPeaksWorkspace.h"
 
 class vtkImplicitFunction;
@@ -9,10 +9,10 @@ class VTK_EXPORT vtkPeaksReader : public vtkPolyDataAlgorithm
 {
 public:
   static vtkPeaksReader *New();
-  vtkTypeMacro(vtkPeaksReader, vtkPolyDataAlgorithm);
+  vtkTypeMacro(vtkPeaksReader, vtkPolyDataAlgorithm)
   void PrintSelf(ostream& os, vtkIndent indent);
-  vtkSetStringMacro(FileName);
-  vtkGetStringMacro(FileName);
+  vtkSetStringMacro(FileName)
+  vtkGetStringMacro(FileName)
   int CanReadFile(const char* fname);
   void SetDimensions(int dimensions);
   /// Setter for the unitegrated peak marker size
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/CMakeLists.txt b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/CMakeLists.txt
index d8d8525c52cfdb3205ce7c7e1c0f3bbbfb1ceb33..8ade1e4798e3c6c555c0578d84a412482b4542f4 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/CMakeLists.txt
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/CMakeLists.txt
@@ -3,7 +3,6 @@ include_directories( SYSTEM ${PARAVIEW_INCLUDE_DIRS} )
 add_paraview_plugin( MantidParaViewSQWEventReaderSMPlugin "1.0"
 	SERVER_MANAGER_XML SQWEventReader.xml
 	SERVER_MANAGER_SOURCES vtkSQWEventReader.cxx
-	GUI_RESOURCE_FILES SQWEventReaderGUI.xml
 )
 
 # Add to the 'VatesParaViewPlugins' group in VS
@@ -11,8 +10,11 @@ set_property( TARGET MantidParaViewSQWEventReaderSMPlugin PROPERTY FOLDER "Manti
 
 include_directories ( SYSTEM ${QWT_INCLUDE_DIR} )
 
-target_link_libraries( MantidParaViewSQWEventReaderSMPlugin 
-${MANTID_SUBPROJECT_LIBS} ${QWT_LIBRARIES})
+target_link_libraries( MantidParaViewSQWEventReaderSMPlugin LINK_PUBLIC ${MANTID_SUBPROJECT_LIBS} ${QWT_LIBRARIES})
+
+if (OSX_VERSION VERSION_GREATER 10.8)
+  set_target_properties ( MantidParaViewSQWEventReaderSMPlugin PROPERTIES INSTALL_RPATH "@loader_path/../../Contents/Libraries;@loader_path/../../Contents/MacOS")
+endif ()
 
 # Put library into subfolder.
 SET_TARGET_OUTPUT_DIRECTORY(MantidParaViewSQWEventReaderSMPlugin ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${CMAKE_CFG_INTDIR}/${PVPLUGINS_DIR}/${PVPLUGINS_SUBDIR})
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/SQWEventReader.xml b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/SQWEventReader.xml
index ce0b8e3d869bc839e53d62c265848c539291c9bc..e22d5ca7d0322da05285ef678a23b665da45e54d 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/SQWEventReader.xml
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/SQWEventReader.xml
@@ -48,6 +48,11 @@
         information_only="1"
         si_class="vtkSITimeLabelProperty">
       </StringVectorProperty>
+      <Hints>
+        <ReaderFactory
+          extensions="sqw"
+          file_description="MD *.sqw format" />
+      </Hints>
     </SourceProxy>
   </ProxyGroup>
   <!-- End SQWEventReader -->
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/vtkSQWEventReader.cxx b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/vtkSQWEventReader.cxx
index ef61e72c3cc659df3fb6115e1038ea11706e8c30..a009a7a71cfc2c519815aac3e19fdd0966a9b387 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/vtkSQWEventReader.cxx
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/vtkSQWEventReader.cxx
@@ -10,6 +10,7 @@
 #include "vtkUnstructuredGrid.h"
 #include "vtkStreamingDemandDrivenPipeline.h"
 #include "vtkPVClipDataSet.h"
+#include "vtkPVInformationKeys.h"
 #include "vtkBox.h"
 
 #include "MantidVatesAPI/vtkMDHexFactory.h"
@@ -202,7 +203,7 @@ void vtkSQWEventReader::setTimeRange(vtkInformationVector* outputVector)
   if(m_presenter->hasTDimensionAvailable())
   {
     vtkInformation *outInfo = outputVector->GetInformationObject(0);
-    outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_LABEL_ANNOTATION(),
+    outInfo->Set(vtkPVInformationKeys::TIME_LABEL_ANNOTATION(),
                  m_presenter->getTimeStepLabel().c_str());
     std::vector<double> timeStepValues = m_presenter->getTimeStepValues();
     outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(), &timeStepValues[0],
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/vtkSQWEventReader.h b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/vtkSQWEventReader.h
index 502de502e23c72545343b929bac3d22a3be9e07f..89e67fc083db881e800621ff9b1950bff030a631 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/vtkSQWEventReader.h
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/vtkSQWEventReader.h
@@ -17,7 +17,7 @@ public:
   //----------------------------------------------
 
   static vtkSQWEventReader *New();
-  vtkTypeMacro(vtkSQWEventReader, vtkUnstructuredGridAlgorithm);
+  vtkTypeMacro(vtkSQWEventReader, vtkUnstructuredGridAlgorithm)
   void PrintSelf(ostream& os, vtkIndent indent);
   vtkSetStringMacro(FileName);
   vtkGetStringMacro(FileName);
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWReader/CMakeLists.txt b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWReader/CMakeLists.txt
index f061505754421f1dca0feb8e1ce7c90521963636..689f53b054120133a355490a1406db72b39f80f5 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWReader/CMakeLists.txt
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWReader/CMakeLists.txt
@@ -12,6 +12,10 @@ set_property( TARGET MantidParaViewSQWReaderSMPlugin PROPERTY FOLDER "MantidVate
 target_link_libraries( MantidParaViewSQWReaderSMPlugin 
 ${MANTID_SUBPROJECT_LIBS} )
 
+if (OSX_VERSION VERSION_GREATER 10.8)
+  set_target_properties ( MantidParaViewSQWReaderSMPlugin PROPERTIES INSTALL_RPATH "@loader_path/../../Contents/Libraries;@loader_path/../../Contents/MacOS")
+endif ()
+
 # Put library into subfolder.
 SET_TARGET_OUTPUT_DIRECTORY( MantidParaViewSQWReaderSMPlugin ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${CMAKE_CFG_INTDIR}/${PVPLUGINS_DIR}/${PVPLUGINS_SUBDIR})
 
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/CMakeLists.txt b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/CMakeLists.txt
index a40f403de2a1e94f1ea15d0c303023f40dab8c75..7068c0f5ccf13a4c0a7f9e3dc07a44546275956e 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/CMakeLists.txt
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/CMakeLists.txt
@@ -6,9 +6,13 @@ ADD_PARAVIEW_PLUGIN(MantidParaViewMDEWSourceSMPlugin "1.0"
 
 # Add to the 'VatesParaViewPlugins' group in VS
 set_property( TARGET MantidParaViewMDEWSourceSMPlugin PROPERTY FOLDER "MantidVatesParaViewPlugins" )
+
 include_directories ( SYSTEM ${QWT_INCLUDE_DIR} )
-target_link_libraries( MantidParaViewMDEWSourceSMPlugin 
-${MANTID_SUBPROJECT_LIBS} ${QWT_LIBRARIES})
+target_link_libraries( MantidParaViewMDEWSourceSMPlugin LINK_PUBLIC ${MANTID_SUBPROJECT_LIBS} ${QWT_LIBRARIES})
+
+if (OSX_VERSION VERSION_GREATER 10.8)
+  set_target_properties ( MantidParaViewMDEWSourceSMPlugin PROPERTIES INSTALL_RPATH "@loader_path/../../Contents/Libraries;@loader_path/../../Contents/MacOS")
+endif ()
 
 # Put library into subfolder.
 SET_TARGET_OUTPUT_DIRECTORY(MantidParaViewMDEWSourceSMPlugin ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${CMAKE_CFG_INTDIR}/${PVPLUGINS_DIR}/${PVPLUGINS_SUBDIR})
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.cxx b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.cxx
index 196dd73e69c89ad37b7fcd5e524f70af033017e5..72b9d1da914e1ee426951e5b3ba7509d0770eed6 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.cxx
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.cxx
@@ -4,6 +4,7 @@
 #include "vtkInformationVector.h"
 #include "vtkObjectFactory.h"
 #include "vtkPVClipDataSet.h"
+#include "vtkPVInformationKeys.h"
 #include "vtkUnstructuredGridAlgorithm.h"
 #include "vtkUnstructuredGrid.h"
 #include "vtkStreamingDemandDrivenPipeline.h"
@@ -14,6 +15,7 @@
 #include "MantidVatesAPI/vtkMDHexFactory.h"
 #include "MantidVatesAPI/vtkMDQuadFactory.h"
 #include "MantidVatesAPI/vtkMDLineFactory.h"
+#include "MantidVatesAPI/vtkMD0DFactory.h"
 #include "MantidVatesAPI/FilteringUpdateProgressAction.h"
 #include "MantidVatesAPI/IgnoreZerosThresholdRange.h"
 
@@ -22,7 +24,7 @@ using namespace Mantid::VATES;
 vtkStandardNewMacro(vtkMDEWSource)
 
 /// Constructor
-vtkMDEWSource::vtkMDEWSource() :  m_wsName(""), m_depth(1000), m_time(0), m_presenter(NULL), m_isStartup(true), m_startupTimeValue(0)
+vtkMDEWSource::vtkMDEWSource() :  m_wsName(""), m_depth(1000), m_time(0), m_presenter(NULL)
 {
   this->SetNumberOfInputPorts(0);
   this->SetNumberOfOutputPorts(1);
@@ -173,17 +175,7 @@ int vtkMDEWSource::RequestData(vtkInformation *, vtkInformationVector **, vtkInf
     //get the info objects
     vtkInformation *outInfo = outputVector->GetInformationObject(0);
 
-    if (m_isStartup)
-    {
-      // This is part of a workaround for ParaView time steps. The time we get
-      // is the first time point for all sources, and not necessarily of this source.
-      // This causes problems when getting the time slice and we end up with an empty 
-      // data set. We therefore feed m_time the first time step of this source at 
-      // start up.
-      m_time = m_startupTimeValue;
-      m_isStartup = false;
-    }
-    else if (outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()))
+    if (outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()))
     {
       // usually only one actual step requested
       m_time =outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP());
@@ -193,12 +185,14 @@ int vtkMDEWSource::RequestData(vtkInformation *, vtkInformationVector **, vtkInf
     FilterUpdateProgressAction<vtkMDEWSource> drawingProgressUpdate(this, "Drawing...");
 
     ThresholdRange_scptr thresholdRange(new IgnoreZerosThresholdRange());
+    vtkMD0DFactory* zeroDFactory = new vtkMD0DFactory(thresholdRange, "signal");
     vtkMDHexFactory* hexahedronFactory = new vtkMDHexFactory(thresholdRange, "signal");
     vtkMDQuadFactory* quadFactory = new vtkMDQuadFactory(thresholdRange, "signal");
     vtkMDLineFactory* lineFactory = new vtkMDLineFactory(thresholdRange, "signal");
 
     hexahedronFactory->SetSuccessor(quadFactory);
     quadFactory->SetSuccessor(lineFactory);
+    lineFactory->SetSuccessor(zeroDFactory);
 
     hexahedronFactory->setTime(m_time);
     vtkDataSet* product = m_presenter->execute(hexahedronFactory, loadingProgressUpdate, drawingProgressUpdate);
@@ -256,7 +250,7 @@ void vtkMDEWSource::setTimeRange(vtkInformationVector* outputVector)
   if(m_presenter->hasTDimensionAvailable())
   {
     vtkInformation *outInfo = outputVector->GetInformationObject(0);
-    outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_LABEL_ANNOTATION(),
+    outInfo->Set(vtkPVInformationKeys::TIME_LABEL_ANNOTATION(),
                  m_presenter->getTimeStepLabel().c_str());
     std::vector<double> timeStepValues = m_presenter->getTimeStepValues();
     outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(), &timeStepValues[0],
@@ -265,9 +259,6 @@ void vtkMDEWSource::setTimeRange(vtkInformationVector* outputVector)
     timeRange[0] = timeStepValues.front();
     timeRange[1] = timeStepValues.back();
 
-    // This is part of a workaround to get the first time value of the current source.
-    m_startupTimeValue = timeRange[0];
-
     outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(), timeRange, 2);
   }
 }
@@ -316,7 +307,7 @@ char* vtkMDEWSource::GetWorkspaceTypeName()
 {
   if(m_presenter == NULL)
   {
-    return "";
+    return const_cast<char*>("");
   }
   try
   {
@@ -326,7 +317,7 @@ char* vtkMDEWSource::GetWorkspaceTypeName()
   }
   catch(std::runtime_error&)
   {
-    return "";
+    return const_cast<char*>("");
   }
 }
 
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.h b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.h
index f2f7a3e1b19a7f18b745d13e0ad602e782116fc2..7ad2525cf4cbe5878ed00c37ac366060eadbf7f5 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.h
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.h
@@ -45,7 +45,7 @@ class VTK_EXPORT vtkMDEWSource : public vtkUnstructuredGridAlgorithm
 {
 public:
   static vtkMDEWSource *New();
-  vtkTypeMacro(vtkMDEWSource, vtkUnstructuredGridAlgorithm);
+  vtkTypeMacro(vtkMDEWSource, vtkUnstructuredGridAlgorithm)
   void PrintSelf(ostream& os, vtkIndent indent);
   
   void SetWsName(std::string wsName);
@@ -97,17 +97,6 @@ private:
   /// Cached typename.
   std::string typeName;
 
-
-  // This is part of a workaround for a ParaView providing not the start time of 
-  // of current data set. 
-  ///Startup flag
-  bool m_isStartup;
-
-  // This is part of a workaround for a ParaView providing not the start time of 
-  // of current data set. 
-  /// Startup time value
-  double m_startupTimeValue;
-
   vtkMDEWSource(const vtkMDEWSource&);
   void operator = (const vtkMDEWSource&);
   void setTimeRange(vtkInformationVector* outputVector);
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/CMakeLists.txt b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/CMakeLists.txt
index e3fa0dd9580eb5df2b4847d05680e77f8d7139f0..e6df317df17aec0abc200a41403274472c01aea7 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/CMakeLists.txt
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/CMakeLists.txt
@@ -9,8 +9,11 @@ set_property( TARGET MantidParaViewMDHWSourceSMPlugin PROPERTY FOLDER "MantidVat
 
 include_directories ( SYSTEM ${QWT_INCLUDE_DIR} )
 
-target_link_libraries( MantidParaViewMDHWSourceSMPlugin 
-${MANTID_SUBPROJECT_LIBS} ${QWT_LIBRARIES})
+target_link_libraries( MantidParaViewMDHWSourceSMPlugin LINK_PUBLIC ${MANTID_SUBPROJECT_LIBS} ${QWT_LIBRARIES})
+
+if (OSX_VERSION VERSION_GREATER 10.8)
+  set_target_properties ( MantidParaViewMDHWSourceSMPlugin PROPERTIES INSTALL_RPATH "@loader_path/../../Contents/Libraries;@loader_path/../../Contents/MacOS")
+endif ()
 
 # Put library into subfolder.
 SET_TARGET_OUTPUT_DIRECTORY(MantidParaViewMDHWSourceSMPlugin ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${CMAKE_CFG_INTDIR}/${PVPLUGINS_DIR}/${PVPLUGINS_SUBDIR})
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.cxx b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.cxx
index e2757e29cacbdf39746273ce58366e5dac853dd3..59539b18372925cb0cbdd08c02e27a2f8a251e8f 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.cxx
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.cxx
@@ -4,6 +4,7 @@
 #include "vtkInformationVector.h"
 #include "vtkObjectFactory.h"
 #include "vtkPVClipDataSet.h"
+#include "vtkPVInformationKeys.h"
 #include "vtkUnstructuredGridAlgorithm.h"
 #include "vtkUnstructuredGrid.h"
 #include "vtkStreamingDemandDrivenPipeline.h"
@@ -14,6 +15,9 @@
 #include "MantidVatesAPI/TimeToTimeStep.h"
 #include "MantidVatesAPI/vtkMDHistoHex4DFactory.h"
 #include "MantidVatesAPI/vtkMDHistoHexFactory.h"
+#include "MantidVatesAPI/vtkMDHistoQuadFactory.h"
+#include "MantidVatesAPI/vtkMDHistoLineFactory.h"
+#include "MantidVatesAPI/vtkMD0DFactory.h"
 #include "MantidVatesAPI/FilteringUpdateProgressAction.h"
 #include "MantidVatesAPI/IgnoreZerosThresholdRange.h"
 
@@ -170,14 +174,21 @@ int vtkMDHWSource::RequestData(vtkInformation *, vtkInformationVector **, vtkInf
     ThresholdRange_scptr thresholdRange(new IgnoreZerosThresholdRange());
 
     /*
-    Will attempt to handle drawing in 4D case and then in 3D case if that fails.
+    Will attempt to handle drawing in 4D case and then in 3D case if that fails, and so on down to 1D
     */
-    vtkMDHistoHexFactory* successor = new vtkMDHistoHexFactory(thresholdRange, "signal");
+    vtkMD0DFactory* zeroDFactory = new vtkMD0DFactory(thresholdRange, "signal");
+    vtkMDHistoLineFactory* lineFactory = new vtkMDHistoLineFactory(thresholdRange, "signal");
+    vtkMDHistoQuadFactory* quadFactory = new vtkMDHistoQuadFactory(thresholdRange, "signal");
+    vtkMDHistoHexFactory* hexFactory = new vtkMDHistoHexFactory(thresholdRange, "signal");
     vtkMDHistoHex4DFactory<TimeToTimeStep> *factory = new vtkMDHistoHex4DFactory<TimeToTimeStep>(thresholdRange, "signal", m_time);
-    factory->SetSuccessor(successor);
+
+    factory->SetSuccessor(hexFactory);
+    hexFactory->SetSuccessor(quadFactory);
+    quadFactory->SetSuccessor(lineFactory);
+    lineFactory->SetSuccessor(zeroDFactory);
 
     vtkDataSet* product = m_presenter->execute(factory, loadingProgressUpdate, drawingProgressUpdate);
-    
+
     //-------------------------------------------------------- Corrects problem whereby boundaries not set propertly in PV.
     vtkBox* box = vtkBox::New();
     box->SetBounds(product->GetBounds());
@@ -192,7 +203,6 @@ int vtkMDHWSource::RequestData(vtkInformation *, vtkInformationVector **, vtkInf
     vtkUnstructuredGrid *output = vtkUnstructuredGrid::SafeDownCast(
       outInfo->Get(vtkDataObject::DATA_OBJECT()));
     output->ShallowCopy(clipperOutput);
-
     try
     {
       m_presenter->makeNonOrthogonal(output);
@@ -243,7 +253,7 @@ void vtkMDHWSource::setTimeRange(vtkInformationVector* outputVector)
   if(m_presenter->hasTDimensionAvailable())
   {
     vtkInformation *outInfo = outputVector->GetInformationObject(0);
-    outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_LABEL_ANNOTATION(),
+    outInfo->Set(vtkPVInformationKeys::TIME_LABEL_ANNOTATION(),
                  m_presenter->getTimeStepLabel().c_str());
     std::vector<double> timeStepValues = m_presenter->getTimeStepValues();
     outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(), &timeStepValues[0],
@@ -300,7 +310,7 @@ char* vtkMDHWSource::GetWorkspaceTypeName()
 {
   if(m_presenter == NULL)
   {
-    return "";
+    return const_cast<char*>("");
   }
   try
   {
@@ -310,7 +320,7 @@ char* vtkMDHWSource::GetWorkspaceTypeName()
   }
   catch(std::runtime_error&)
   {
-    return "";
+    return const_cast<char*>("");
   }
 }
 
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.h b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.h
index e5e2c5c366ae0374714e2418d96bae85bd86b6c4..195fa4a0077d29cec11ed834fedbde069931cd91 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.h
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.h
@@ -44,7 +44,7 @@ class VTK_EXPORT vtkMDHWSource : public vtkUnstructuredGridAlgorithm
 {
 public:
   static vtkMDHWSource *New();
-  vtkTypeMacro(vtkMDHWSource, vtkUnstructuredGridAlgorithm);
+  vtkTypeMacro(vtkMDHWSource, vtkUnstructuredGridAlgorithm)
   void PrintSelf(ostream& os, vtkIndent indent);
   
   void SetWsName(std::string wsName);
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/PeaksSource/CMakeLists.txt b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/PeaksSource/CMakeLists.txt
index 188fe0c7fafd56fd6fc564e474a51c551912f43f..119d7bf24232dc66ccf02b55d76de1108195551a 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/PeaksSource/CMakeLists.txt
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/PeaksSource/CMakeLists.txt
@@ -7,9 +7,13 @@ ADD_PARAVIEW_PLUGIN(MantidParaViewPeaksSourceSMPlugin "1.0"
 # Add to the 'VatesParaViewPlugins' group in VS
 set_property( TARGET MantidParaViewPeaksSourceSMPlugin PROPERTY FOLDER "MantidVatesParaViewPlugins" )
 
-target_link_libraries( MantidParaViewPeaksSourceSMPlugin 
+target_link_libraries( MantidParaViewPeaksSourceSMPlugin LINK_PUBLIC
 ${MANTID_SUBPROJECT_LIBS} )
 
+if (OSX_VERSION VERSION_GREATER 10.8)
+  set_target_properties ( MantidParaViewPeaksSourceSMPlugin PROPERTIES INSTALL_RPATH "@loader_path/../../Contents/Libraries;@loader_path/../../Contents/MacOS")
+endif ()
+
 # Put library into subfolder.
 SET_TARGET_OUTPUT_DIRECTORY(MantidParaViewPeaksSourceSMPlugin ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${CMAKE_CFG_INTDIR}/${PVPLUGINS_DIR}/${PVPLUGINS_SUBDIR})
 
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/PeaksSource/vtkPeaksSource.h b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/PeaksSource/vtkPeaksSource.h
index 88023cc0e2dfee9dd679c03e038518d7c96eaa05..cc1d092b73bbadfe78b753a441709b6df131fd55 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/PeaksSource/vtkPeaksSource.h
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/PeaksSource/vtkPeaksSource.h
@@ -3,7 +3,7 @@
 
 #include "MantidAPI/IPeaksWorkspace.h"
 #include "MantidVatesAPI/vtkPeakMarkerFactory.h"
-#include "vtkPolyDataAlgorithm.h"
+#include "MantidVatesAPI/vtkPolyDataAlgorithm_Silent.h"
 #include <string>
 
 /**
@@ -39,7 +39,7 @@ class VTK_EXPORT vtkPeaksSource : public vtkPolyDataAlgorithm
 {
 public:
   static vtkPeaksSource *New();
-  vtkTypeMacro(vtkPeaksSource,vtkPolyDataAlgorithm);
+  vtkTypeMacro(vtkPeaksSource,vtkPolyDataAlgorithm)
   void PrintSelf(ostream& os, vtkIndent indent);
   
   void SetWsName(std::string wsName);
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/SinglePeakMarkerSource/CMakeLists.txt b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/SinglePeakMarkerSource/CMakeLists.txt
index b713178fd46d2911ff18e3f270e4ca7cca838a7b..e0f879e1377b82df7a0cd29d2454497b8023ac98 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/SinglePeakMarkerSource/CMakeLists.txt
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/SinglePeakMarkerSource/CMakeLists.txt
@@ -7,8 +7,11 @@ ADD_PARAVIEW_PLUGIN(MantidParaViewSinglePeakMarkerSourceSMPlugin "1.0"
 # Add to the 'VatesParaViewPlugins' group in VS
 set_property( TARGET MantidParaViewSinglePeakMarkerSourceSMPlugin  PROPERTY FOLDER "MantidVatesParaViewPlugins" )
 
-target_link_libraries( MantidParaViewSinglePeakMarkerSourceSMPlugin  
-${MANTID_SUBPROJECT_LIBS} )
+target_link_libraries( MantidParaViewSinglePeakMarkerSourceSMPlugin LINK_PUBLIC ${MANTID_SUBPROJECT_LIBS} )
+
+if (OSX_VERSION VERSION_GREATER 10.8)
+  set_target_properties ( MantidParaViewSinglePeakMarkerSourceSMPlugin PROPERTIES INSTALL_RPATH "@loader_path/../../Contents/Libraries;@loader_path/../../Contents/MacOS")
+endif ()
 
 # Put library into subfolder.
 SET_TARGET_OUTPUT_DIRECTORY(MantidParaViewSinglePeakMarkerSourceSMPlugin  ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${CMAKE_CFG_INTDIR}/${PVPLUGINS_DIR}/${PVPLUGINS_SUBDIR})
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/SinglePeakMarkerSource/vtkSinglePeakMarkerSource.h b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/SinglePeakMarkerSource/vtkSinglePeakMarkerSource.h
index dccef350679450a1368911c25cc0b0ed97c20dbe..6a3f8c53a099f83b5e5de55c2143df11eea50e84 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/SinglePeakMarkerSource/vtkSinglePeakMarkerSource.h
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/SinglePeakMarkerSource/vtkSinglePeakMarkerSource.h
@@ -34,7 +34,7 @@ class VTK_EXPORT vtkSinglePeakMarkerSource : public vtkPolyDataAlgorithm
 {
 public:
   static vtkSinglePeakMarkerSource*New();
-  vtkTypeMacro(vtkSinglePeakMarkerSource,vtkPolyDataAlgorithm);
+  vtkTypeMacro(vtkSinglePeakMarkerSource,vtkPolyDataAlgorithm)
   void PrintSelf(ostream& os, vtkIndent indent);
   void SetRadiusMarker(double radius);
   void SetPosition1(double position1);
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/CMakeLists.txt b/Code/Mantid/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/CMakeLists.txt
index 613bfa22bab3375dee7e3e850680a1ad3684b33d..33a02ddce5fd9c921e915fdeb15083db93d100eb 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/CMakeLists.txt
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/CMakeLists.txt
@@ -37,9 +37,16 @@ project( MantidParaViewQtWidgets )
 add_library( MantidParaViewQtWidgets ${SRC_FILES} ${MOCCED_FILES} ${INC_FILES} ) 
 # Add to the 'Vates' group in VS
 set_property( TARGET MantidParaViewQtWidgets PROPERTY FOLDER "MantidVates" )
-target_link_libraries( MantidParaViewQtWidgets ${QT_LIBRARIES} 
+target_link_libraries( MantidParaViewQtWidgets 
+vtkRenderingFreeType
+vtkRenderingFreeTypeOpenGL
+${QT_LIBRARIES} 
 ${MANTID_SUBPROJECT_LIBS} )
 
+if (OSX_VERSION VERSION_GREATER 10.8)
+  set_target_properties ( MantidParaViewQtWidgets PROPERTIES INSTALL_RPATH "@loader_path/../Libraries;@loader_path/../MacOS")
+endif ()
+
 add_definitions( -DIN_MANTIDPARAVIEWQT_MANTIDPARAVIEWWIDGETS )
 
 # Put library into subfolder.
@@ -47,4 +54,3 @@ add_definitions( -DIN_MANTIDPARAVIEWQT_MANTIDPARAVIEWWIDGETS )
 
 install( TARGETS MantidParaViewQtWidgets ${SYSTEM_PACKAGE_TARGET} DESTINATION ${LIB_DIR} )
 
-
diff --git a/Code/Mantid/Vates/VatesAPI/CMakeLists.txt b/Code/Mantid/Vates/VatesAPI/CMakeLists.txt
index 927bc9468ec3127a1602d702c044bfccffe90267..00db31c94ed467accbe6cafd47f624d09b8012e8 100644
--- a/Code/Mantid/Vates/VatesAPI/CMakeLists.txt
+++ b/Code/Mantid/Vates/VatesAPI/CMakeLists.txt
@@ -46,6 +46,7 @@ src/vtkDataSetToWsLocation.cpp
 src/vtkEllipsoidTransformer.cpp
 src/vtkMDLineFactory.cpp
 src/vtkMDQuadFactory.cpp
+src/vtkMD0DFactory.cpp
 src/vtkNullUnstructuredGrid.cpp
 src/vtkSplatterPlotFactory.cpp
 src/vtkMDHexFactory.cpp
@@ -113,6 +114,7 @@ inc/MantidVatesAPI/vtkEllipsoidTransformer.h
 inc/MantidVatesAPI/vtkMDLineFactory.h
 inc/MantidVatesAPI/vtkMDQuadFactory.h
 inc/MantidVatesAPI/vtkMDHexFactory.h
+inc/MantidVatesAPI/vtkMD0DFactory.h
 inc/MantidVatesAPI/vtkNullUnstructuredGrid.h
 inc/MantidVatesAPI/vtkSplatterPlotFactory.h
 inc/MantidVatesAPI/vtkPeakMarkerFactory.h
@@ -142,6 +144,7 @@ test/vtkMDHistoHex4DFactoryTest.h
 test/vtkMDHistoHexFactoryTest.h
 test/vtkMDHistoLineFactoryTest.h
 test/vtkMDHistoQuadFactoryTest.h
+test/vtkMD0DFactoryTest.h
 test/FieldDataToMetadataTest.h
 test/FilteringUpdateProgressActionTest.h
 test/LoadVTKTest.h
@@ -176,7 +179,7 @@ test/CompositePeaksPresenterVsiTest.h
 )
 
 include_directories( inc )
-include_directories ( SYSTEM ${QWT_INCLUDE_DIR} )
+include_directories ( SYSTEM ${QWT_INCLUDE_DIR} ${PARAVIEW_INCLUDE_DIRS})
 
 set( SRC_UNITY_IGNORE_FILES )
 if( UNITY_BUILD )
@@ -207,6 +210,10 @@ vtkPVVTKExtensionsDefault
 ${QWT_LIBRARIES}
 )
 
+if (OSX_VERSION VERSION_GREATER 10.8)
+  set_target_properties ( VatesAPI PROPERTIES INSTALL_RPATH "@loader_path/../MacOS;@loader_path/../Libraries")
+endif ()
+
 # Create test file projects
 if( CXXTEST_FOUND AND GMOCK_FOUND AND GTEST_FOUND )
   include_directories ( SYSTEM ${CXXTEST_INCLUDE_DIR} ${GMOCK_INCLUDE_DIR} ${GTEST_INCLUDE_DIR} )
diff --git a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/CompositePeaksPresenterVsi.h b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/CompositePeaksPresenterVsi.h
index e09ab823f093e074c2673f2d81f87efca2a72f7e..21bf69a640492aa98c745276b90eb062d87361fe 100644
--- a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/CompositePeaksPresenterVsi.h
+++ b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/CompositePeaksPresenterVsi.h
@@ -23,7 +23,7 @@ public:
   }
   std::vector<Mantid::API::IPeaksWorkspace_sptr> getPeaksWorkspaces() const;
   virtual std::vector<bool> getViewablePeaks() const;
-  virtual void updateViewFrustum(ViewFrustum frustum);
+  virtual void updateViewFrustum(ViewFrustum_const_sptr frustum);
   virtual std::string getFrame() const;
   virtual std::string getPeaksWorkspaceName() const{
     throw std::runtime_error(
diff --git a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/ConcretePeaksPresenterVsi.h b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/ConcretePeaksPresenterVsi.h
index e6b6a6cfa7c71e58138d7dc10052de9140e68ad5..a3d72ca061f994cb264b802f1cbfbfca50f48cb6 100644
--- a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/ConcretePeaksPresenterVsi.h
+++ b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/ConcretePeaksPresenterVsi.h
@@ -15,11 +15,11 @@ namespace VATES {
 class DLLExport ConcretePeaksPresenterVsi : public PeaksPresenterVsi {
 public:
   ConcretePeaksPresenterVsi(Mantid::API::IPeaksWorkspace_sptr peaksWorkspace,
-                            ViewFrustum frustum, std::string wsFrame);
+                            ViewFrustum_const_sptr frustum, std::string wsFrame);
   ~ConcretePeaksPresenterVsi();
   virtual Mantid::API::IPeaksWorkspace_sptr getPeaksWorkspace() const;
   virtual std::vector<bool> getViewablePeaks() const;
-  virtual void updateViewFrustum(ViewFrustum frustum);
+  virtual void updateViewFrustum(ViewFrustum_const_sptr frustum);
   virtual std::string getFrame() const;
   virtual std::string getPeaksWorkspaceName() const;
   virtual void
@@ -35,7 +35,7 @@ private:
   /// Viewable Peaks
   mutable std::vector<bool> m_viewablePeaks;
   /// The viewable region
-  ViewFrustum m_viewableRegion;
+  ViewFrustum_const_sptr m_viewableRegion;
   /// The peaks workspace
   Mantid::API::IPeaksWorkspace_sptr m_peaksWorkspace;
   /// The frame
diff --git a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/MDHWInMemoryLoadingPresenter.h b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/MDHWInMemoryLoadingPresenter.h
index 534d88220135bbb7513a285db1d3d496facb148f..ce76a4d229fed31b6e2527cb4ac350f4c92d4f8f 100644
--- a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/MDHWInMemoryLoadingPresenter.h
+++ b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/MDHWInMemoryLoadingPresenter.h
@@ -50,7 +50,6 @@ namespace Mantid
       virtual bool canReadFile() const;
       virtual std::string getWorkspaceTypeName();
       virtual int getSpecialCoordinates();
-
     private:
       /// Repository for accessing workspaces. At this level, does not specify how or where from.
       boost::scoped_ptr<WorkspaceProvider> m_repository;
diff --git a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/NullPeaksPresenterVsi.h b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/NullPeaksPresenterVsi.h
index c8c04fd18c79619c52cc87e6d4b09ef0d3c735a2..900dae7fd983792eaec7abfb57cdce4c4cbfb20a 100644
--- a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/NullPeaksPresenterVsi.h
+++ b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/NullPeaksPresenterVsi.h
@@ -23,7 +23,7 @@ public:
     throw std::runtime_error(
         "NullPeaksPresenterVsi does not implement this method. Misused");
   }
-  virtual void updateViewFrustum(ViewFrustum) {}
+  virtual void updateViewFrustum(ViewFrustum_const_sptr) {}
   virtual std::string getFrame() const {
     throw std::runtime_error(
         "NullPeaksPresenterVsi does not implement this method. Misused");
diff --git a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/PeaksPresenterVsi.h b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/PeaksPresenterVsi.h
index 3f891f3f236ce118d8eb87f61431d0b70da469fa..78eb1b79904582eebd4e61a0fea202927c9f3d87 100644
--- a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/PeaksPresenterVsi.h
+++ b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/PeaksPresenterVsi.h
@@ -5,19 +5,19 @@
 #include "MantidAPI/IPeaksWorkspace.h"
 #include "MantidKernel/V3D.h"
 #include "MantidKernel/SpecialCoordinateSystem.h"
+#include "MantidVatesAPI/ViewFrustum.h"
 #include <vector>
 #include <string>
 
 namespace Mantid {
 namespace VATES {
-class ViewFrustum;
 
 class DLLExport PeaksPresenterVsi {
 public:
   virtual ~PeaksPresenterVsi(){};
   virtual std::vector<bool> getViewablePeaks() const = 0;
   virtual Mantid::API::IPeaksWorkspace_sptr getPeaksWorkspace() const = 0;
-  virtual void updateViewFrustum(ViewFrustum frustum) = 0;
+  virtual void updateViewFrustum(ViewFrustum_const_sptr frustum) = 0;
   virtual std::string getFrame() const = 0;
   virtual std::string getPeaksWorkspaceName() const = 0;
   virtual void getPeaksInfo(Mantid::API::IPeaksWorkspace_sptr peaksWorkspace,
diff --git a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/VatesKnowledgeSerializer.h b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/VatesKnowledgeSerializer.h
index 9d8d4eb8e09fd6ad68d7f232e071c05b23a6e53a..d4e4ec4593907df33709ad5db8a59586f7b105cd 100644
--- a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/VatesKnowledgeSerializer.h
+++ b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/VatesKnowledgeSerializer.h
@@ -62,10 +62,9 @@ private:
   std::string m_wsNameXML;
   std::string m_wsName;
   std::string m_geomXML;
-  LocationPolicy m_locationPolicy;
 public:
 
-  VatesKnowledgeSerializer(LocationPolicy locationPolicy=LocationMandatory);
+  VatesKnowledgeSerializer();
 
   /// Set the implicit function to use called.
   void setImplicitFunction(boost::shared_ptr<const Mantid::Geometry::MDImplicitFunction> spFunction);
diff --git a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/ViewFrustum.h b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/ViewFrustum.h
index d6e6847ff2beca6d86f5c505fa32c976d8fcad8a..b145c50bf3c772d099a09541aec4a0cdfc716281 100644
--- a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/ViewFrustum.h
+++ b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/ViewFrustum.h
@@ -7,6 +7,7 @@
 #include <cmath>
 #include <cfloat>
 #include <vector>
+#include <boost/shared_ptr.hpp>
 
 namespace Mantid
 {
@@ -23,9 +24,9 @@ class DLLExport FrustumPlane
                                                                                                 m_paramB(paramB),
                                                                                                 m_paramC(paramC), 
                                                                                                 m_paramD(paramD){}
-    FrustumPlane(const FrustumPlane<I, T>& other) : m_paramA(other.m_paramA), 
+    FrustumPlane(const FrustumPlane<I, T>& other) : m_paramA(other.m_paramA),
                                                     m_paramB(other.m_paramB),
-                                                    m_paramC(other.m_paramC), 
+                                                    m_paramC(other.m_paramC),
                                                     m_paramD(other.m_paramD){}
     T A() {return m_paramA;}
     T B() {return m_paramB;}
@@ -170,6 +171,10 @@ class DLLExport ViewFrustum
     matrix.setColumn(1, vec1);
     matrix.setColumn(2, vec2);
   }
+
+/// shared pointer to the view frustum
+typedef boost::shared_ptr<Mantid::VATES::ViewFrustum> ViewFrustum_sptr;
+typedef boost::shared_ptr<const Mantid::VATES::ViewFrustum> ViewFrustum_const_sptr;
 }
 }
 #endif
\ No newline at end of file
diff --git a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToNonOrthogonalDataSet.h b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToNonOrthogonalDataSet.h
index ae7c45346faa0533f2166db6e26eb3a30c759042..831df55d738a0ffa2ca7ccc7c7efe5c94dc99574 100644
--- a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToNonOrthogonalDataSet.h
+++ b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToNonOrthogonalDataSet.h
@@ -64,8 +64,6 @@ namespace VATES
   private:
     vtkDataSetToNonOrthogonalDataSet& operator=(const vtkDataSetToNonOrthogonalDataSet& other);
     vtkDataSetToNonOrthogonalDataSet(const vtkDataSetToNonOrthogonalDataSet& other);
-    /// Copy a vector to an array
-    void copyToRaw(double *arr, MantidVec vec);
     /// Calculate the skew matrix and basis.
     void createSkewInformation(Geometry::OrientedLattice &ol,
                                Kernel::DblMatrix &w,
@@ -78,8 +76,6 @@ namespace VATES
     void updateMetaData(vtkUnstructuredGrid *ugrid);
     vtkDataSet *m_dataSet; ///< Pointer to VTK dataset to modify
     std::string m_wsName; ///< The name of the workspace to fetch
-    //FIXME: Temp var for getting hardcoded stuff back
-    unsigned int m_hc;
     std::size_t m_numDims; ///< Number of dimensions in workspace
     Kernel::DblMatrix m_skewMat; ///< The skew matrix for non-orthogonal representation
     MantidVec m_basisNorm; ///< Holder for the basis normalisation values
diff --git a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkGlyph3D_Silent.h b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkGlyph3D_Silent.h
new file mode 100644
index 0000000000000000000000000000000000000000..e784a3050ed76444c8401c74d8c5c181a3d64f5d
--- /dev/null
+++ b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkGlyph3D_Silent.h
@@ -0,0 +1,17 @@
+#ifndef VTKGLYPH3D_SILENT_H
+#define VTKGLYPH3D_SILENT_H
+
+#if defined(__GNUC__) && !(defined(__INTEL_COMPILER))
+  #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 8 )
+    #pragma GCC diagnostic push
+  #endif
+  #pragma GCC diagnostic ignored "-Wconversion"
+#endif
+#include <vtkGlyph3D.h>
+#if defined(__GNUC__) && !(defined(__INTEL_COMPILER))
+  #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 8 )
+    #pragma GCC diagnostic pop
+  #endif
+#endif
+
+#endif // VTKGLYPH3D_SILENT_H
diff --git a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMD0DFactory.h b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMD0DFactory.h
new file mode 100644
index 0000000000000000000000000000000000000000..5469d9fae87453ef79e9682a04398e92f173df05
--- /dev/null
+++ b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMD0DFactory.h
@@ -0,0 +1,73 @@
+#ifndef MANTID_VATES_VTK_MD_0D_FACTORY_H_
+#define MANTID_VATES_VTK_MD_0D_FACTORY_H_
+
+#include "MantidKernel/System.h"
+#include "MantidVatesAPI/vtkDataSetFactory.h"
+#include "MantidAPI/IMDWorkspace.h"
+#include "vtkUnstructuredGrid.h"
+#include "MantidVatesAPI/ThresholdRange.h"
+
+namespace Mantid
+{
+  namespace VATES
+  {
+
+/** 0D Factory. This type is responsible for rendering IMDWorkspaces with 0D.
+
+ Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+
+ This file is part of Mantid.
+
+ Mantid is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ Mantid 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 General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+ File change history is stored at: <https://github.com/mantidproject/mantid>
+ Code Documentation is available at: <http://doxygen.mantidproject.org>
+ */
+    class DLLExport vtkMD0DFactory : public vtkDataSetFactory
+    {
+    public:
+
+      /// Constructor
+      vtkMD0DFactory(ThresholdRange_scptr thresholdRange, const std::string& scalarName);
+
+      /// Assignment operator
+      vtkMD0DFactory& operator=(const vtkMD0DFactory& other);
+
+      /// Copy constructor.
+      vtkMD0DFactory(const vtkMD0DFactory& other);
+
+      /// Destructor
+      virtual ~vtkMD0DFactory();
+
+      /// Factory Method.
+      virtual vtkDataSet* create(ProgressAction& progressUpdating) const;
+
+      virtual void initialize(Mantid::API::Workspace_sptr);
+
+      virtual std::string getFactoryTypeName() const
+      {
+        return "vtkMD0DFactory";
+      }
+
+    protected:
+        virtual void validate() const;
+
+    private:
+      mutable ThresholdRange_scptr m_thresholdRange;
+      std::string m_scalarName;
+    };
+    
+  }
+}
+#endif
diff --git a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkPolyDataAlgorithm_Silent.h b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkPolyDataAlgorithm_Silent.h
new file mode 100644
index 0000000000000000000000000000000000000000..accda9816f3f304456f6446990a9338fbbcba086
--- /dev/null
+++ b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkPolyDataAlgorithm_Silent.h
@@ -0,0 +1,17 @@
+#ifndef VTKPOLYDATAALGORITHM_SILENT_H
+#define VTKPOLYDATAALGORITHM_SILENT_H
+
+#if defined(__GNUC__) && !(defined(__INTEL_COMPILER))
+  #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 8 )
+    #pragma GCC diagnostic push
+  #endif
+  #pragma GCC diagnostic ignored "-Wconversion"
+#endif
+#include <vtkPolyDataAlgorithm.h>
+#if defined(__GNUC__) && !(defined(__INTEL_COMPILER))
+  #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 8 )
+    #pragma GCC diagnostic pop
+  #endif
+#endif
+
+#endif // VTKPOLYDATAALGORITHM_SILENT_H
diff --git a/Code/Mantid/Vates/VatesAPI/src/Common.cpp b/Code/Mantid/Vates/VatesAPI/src/Common.cpp
index 5e02d039a6f743521c29f1d3497e077c1dff4166..e2e19d031e714e363d3a70444b707b3583babcde 100644
--- a/Code/Mantid/Vates/VatesAPI/src/Common.cpp
+++ b/Code/Mantid/Vates/VatesAPI/src/Common.cpp
@@ -6,15 +6,14 @@
 #include <vtkFieldData.h>
 #include <vtkStringArray.h>
 
+#include "vtkPVChangeOfBasisHelper.h"
+
 #include <boost/math/special_functions/fpclassify.hpp>
 
-//using namespace Mantid::Geometry;
-namespace Mantid
-{
-namespace VATES
-{
-std::string makeAxisTitle(Dimension_const_sptr dim)
-{
+// using namespace Mantid::Geometry;
+namespace Mantid {
+namespace VATES {
+std::string makeAxisTitle(Dimension_const_sptr dim) {
   std::string title = dim->getName();
   title += " (";
   title += dim->getUnits();
@@ -22,10 +21,8 @@ std::string makeAxisTitle(Dimension_const_sptr dim)
   return title;
 }
 
-void setAxisLabel(std::string metadataLabel,
-                  std::string labelString,
-                  vtkFieldData *fieldData)
-{
+void setAxisLabel(std::string metadataLabel, std::string labelString,
+                  vtkFieldData *fieldData) {
   vtkNew<vtkStringArray> axisTitle;
   axisTitle->SetName(metadataLabel.c_str());
   axisTitle->SetNumberOfComponents(1);
@@ -34,8 +31,7 @@ void setAxisLabel(std::string metadataLabel,
   fieldData->AddArray(axisTitle.GetPointer());
 }
 
-bool isSpecial(double value)
-{
+bool isSpecial(double value) {
   return boost::math::isnan(value) || boost::math::isinf(value);
 }
 
diff --git a/Code/Mantid/Vates/VatesAPI/src/CompositePeaksPresenterVsi.cpp b/Code/Mantid/Vates/VatesAPI/src/CompositePeaksPresenterVsi.cpp
index 65f3bdf799d4f2569b9ae597c5b33c5fa651c0ca..28fb29794111f5aa86ed69f22843e9857c65d356 100644
--- a/Code/Mantid/Vates/VatesAPI/src/CompositePeaksPresenterVsi.cpp
+++ b/Code/Mantid/Vates/VatesAPI/src/CompositePeaksPresenterVsi.cpp
@@ -17,7 +17,7 @@ CompositePeaksPresenterVsi::~CompositePeaksPresenterVsi() {}
  * Update the view frustum
  * @param frustum The view frustum
  */
-void CompositePeaksPresenterVsi::updateViewFrustum(ViewFrustum frustum) {
+void CompositePeaksPresenterVsi::updateViewFrustum(ViewFrustum_const_sptr frustum) {
   for (std::vector<PeaksPresenterVsi_sptr>::iterator it =
            m_peaksPresenters.begin();
        it != m_peaksPresenters.end(); ++it) {
diff --git a/Code/Mantid/Vates/VatesAPI/src/ConcretePeaksPresenterVsi.cpp b/Code/Mantid/Vates/VatesAPI/src/ConcretePeaksPresenterVsi.cpp
index 92b1c23384e2abc2dfd4a1d65ac8dc9b003397c0..c5a1a259e69ec446093a80e8d11b3f72f3f4318c 100644
--- a/Code/Mantid/Vates/VatesAPI/src/ConcretePeaksPresenterVsi.cpp
+++ b/Code/Mantid/Vates/VatesAPI/src/ConcretePeaksPresenterVsi.cpp
@@ -17,7 +17,7 @@ namespace VATES {
  * @param frame The coordinate frame
  */
 ConcretePeaksPresenterVsi::ConcretePeaksPresenterVsi(
-    Mantid::API::IPeaksWorkspace_sptr peaksWorkspace, ViewFrustum frustum,
+    Mantid::API::IPeaksWorkspace_sptr peaksWorkspace, ViewFrustum_const_sptr frustum,
     std::string frame)
     : m_viewableRegion(frustum), m_peaksWorkspace(peaksWorkspace),
       m_frame(frame) {}
@@ -29,7 +29,7 @@ ConcretePeaksPresenterVsi::~ConcretePeaksPresenterVsi() {}
  * Update the view frustum
  * @param frustum The view frustum.
  */
-void ConcretePeaksPresenterVsi::updateViewFrustum(ViewFrustum frustum) {
+void ConcretePeaksPresenterVsi::updateViewFrustum(ViewFrustum_const_sptr frustum) {
   m_viewableRegion = frustum;
 }
 
@@ -44,7 +44,7 @@ std::vector<bool> ConcretePeaksPresenterVsi::getViewablePeaks() const{
 
   if (this->m_peaksWorkspace->getNumberPeaks() >= 1) {
     double effectiveRadius = 1e-2;
-    std::string viewable = m_viewableRegion.toExtentsAsString();
+    std::string viewable = m_viewableRegion->toExtentsAsString();
     Mantid::API::IPeaksWorkspace_sptr peaksWS = m_peaksWorkspace;
 
     Mantid::API::IAlgorithm_sptr alg =
diff --git a/Code/Mantid/Vates/VatesAPI/src/MDEWLoadingPresenter.cpp b/Code/Mantid/Vates/VatesAPI/src/MDEWLoadingPresenter.cpp
index b0e7cb9bdd5c7444dbfeb41e15020ce4002bc68f..00feb6483209d71f2b8f9ff0e9c2b2af2c115b2d 100644
--- a/Code/Mantid/Vates/VatesAPI/src/MDEWLoadingPresenter.cpp
+++ b/Code/Mantid/Vates/VatesAPI/src/MDEWLoadingPresenter.cpp
@@ -155,7 +155,7 @@ namespace Mantid
       vtkFieldData* outputFD = vtkFieldData::New();
       
       //Serialize metadata
-      VatesKnowledgeSerializer serializer(LocationNotRequired);
+      VatesKnowledgeSerializer serializer;
       serializer.setWorkspaceName(wsName);
       serializer.setGeometryXML(xmlBuilder.create());
       serializer.setImplicitFunction( Mantid::Geometry::MDImplicitFunction_sptr(new Mantid::Geometry::NullImplicitFunction()));
diff --git a/Code/Mantid/Vates/VatesAPI/src/MDHWLoadingPresenter.cpp b/Code/Mantid/Vates/VatesAPI/src/MDHWLoadingPresenter.cpp
index eb113bb20a1d68b8c2841e7a78eb2819d6ab1838..bd98f1811f90f6e9d988a5e13dcda4ba03210f27 100644
--- a/Code/Mantid/Vates/VatesAPI/src/MDHWLoadingPresenter.cpp
+++ b/Code/Mantid/Vates/VatesAPI/src/MDHWLoadingPresenter.cpp
@@ -150,7 +150,7 @@ namespace Mantid
       vtkFieldData* outputFD = vtkFieldData::New();
       
       //Serialize metadata
-      VatesKnowledgeSerializer serializer(LocationNotRequired);
+      VatesKnowledgeSerializer serializer;
       serializer.setWorkspaceName(wsName);
       serializer.setGeometryXML(xmlBuilder.create());
       serializer.setImplicitFunction( Mantid::Geometry::MDImplicitFunction_sptr(new Mantid::Geometry::NullImplicitFunction()));
diff --git a/Code/Mantid/Vates/VatesAPI/src/MetaDataExtractorUtils.cpp b/Code/Mantid/Vates/VatesAPI/src/MetaDataExtractorUtils.cpp
index 84c1ee0ef93e149c0e951e3eccce242e4b85db58..58fd5a4f57ff692f4d1cf166ad46c20264e04696 100644
--- a/Code/Mantid/Vates/VatesAPI/src/MetaDataExtractorUtils.cpp
+++ b/Code/Mantid/Vates/VatesAPI/src/MetaDataExtractorUtils.cpp
@@ -49,7 +49,7 @@ namespace Mantid
           instrument = eventWorkspace->getExperimentInfo(0)->getInstrument()->getName();
         } else 
         {
-          g_log.warning() << "The event workspace does not have any instruments. \n";
+          g_log.notice() << "The event workspace does not have any instruments. \n";
 
           instrument = "";
         }
@@ -60,7 +60,7 @@ namespace Mantid
           instrument = histoWorkspace->getExperimentInfo(0)->getInstrument()->getName();
         } else
         {
-          g_log.warning() << "The histo workspace does not have any instruments. \n";
+          g_log.notice() << "The histo workspace does not have any instruments. \n";
 
           instrument = "";
         }
diff --git a/Code/Mantid/Vates/VatesAPI/src/VatesKnowledgeSerializer.cpp b/Code/Mantid/Vates/VatesAPI/src/VatesKnowledgeSerializer.cpp
index b9e9dcd600065b6c9d509a9a710ff933004e8ea5..8fe711d88bba447d96837fbe44c0265555b6da1f 100644
--- a/Code/Mantid/Vates/VatesAPI/src/VatesKnowledgeSerializer.cpp
+++ b/Code/Mantid/Vates/VatesAPI/src/VatesKnowledgeSerializer.cpp
@@ -13,12 +13,11 @@ namespace Mantid
 namespace VATES
 {
 
-VatesKnowledgeSerializer::VatesKnowledgeSerializer(LocationPolicy locationPolicy) : 
+VatesKnowledgeSerializer::VatesKnowledgeSerializer() : 
   m_wsLocationXML(""), 
   m_wsNameXML(""), 
   m_wsName(""), 
-  m_geomXML(""),
-  m_locationPolicy(locationPolicy)
+  m_geomXML("")
 {
 }
 
diff --git a/Code/Mantid/Vates/VatesAPI/src/vtkDataSetToNonOrthogonalDataSet.cpp b/Code/Mantid/Vates/VatesAPI/src/vtkDataSetToNonOrthogonalDataSet.cpp
index e75428c6a6c31f74a8d3c299b32c32c2cb92896c..22040df08d65b0cf245139904e4bef490e9ad193 100644
--- a/Code/Mantid/Vates/VatesAPI/src/vtkDataSetToNonOrthogonalDataSet.cpp
+++ b/Code/Mantid/Vates/VatesAPI/src/vtkDataSetToNonOrthogonalDataSet.cpp
@@ -11,26 +11,69 @@
 #include <vtkDataSet.h>
 #include <vtkFieldData.h>
 #include <vtkFloatArray.h>
+#include <vtkDoubleArray.h>
 #include <vtkMatrix3x3.h>
 #include <vtkNew.h>
 #include <vtkPoints.h>
 #include <vtkUnstructuredGrid.h>
+#include <vtkDataObject.h>
+#include <vtkMatrix4x4.h>
+#include <vtkSmartPointer.h>
 
 #include <boost/algorithm/string/find.hpp>
 #include <stdexcept>
 
-namespace Mantid
-{
-namespace VATES
-{
+using namespace Mantid;
+namespace {
+
+void addChangeOfBasisMatrixToFieldData(vtkDataObject *dataObject,
+                                       const MantidVec &u, const MantidVec &v,
+                                       const MantidVec &w) {
+
+  if (!dataObject) {
+    throw std::invalid_argument("Change of basis needs a vtkDataObject");
+  }
+  if (u.size() != 3) {
+    throw std::invalid_argument("Change of basis requires 3-element u");
+  }
+  if (v.size() != 3) {
+    throw std::invalid_argument("Change of basis requires 3-element v");
+  }
+  if (w.size() != 3) {
+    throw std::invalid_argument("Change of basis requires 3-element w");
+  }
+
+  vtkSmartPointer<vtkMatrix4x4> cobMatrix =
+      vtkSmartPointer<vtkMatrix4x4>::New();
+  cobMatrix->Identity();
+  std::copy(u.begin(), u.end(), cobMatrix->Element[0]);
+  std::copy(v.begin(), v.end(), cobMatrix->Element[1]);
+  std::copy(w.begin(), w.end(), cobMatrix->Element[2]);
+
+  cobMatrix->Transpose();
+
+  vtkNew<vtkDoubleArray> cobArray;
+  cobArray->SetName("ChangeOfBasisMatrix");
+  cobArray->SetNumberOfComponents(16);
+  cobArray->SetNumberOfTuples(1);
+  std::copy(&cobMatrix->Element[0][0], (&cobMatrix->Element[0][0]) + 16,
+            cobArray->GetPointer(0));
+  dataObject->GetFieldData()->AddArray(cobArray.GetPointer());
+}
+
+}
+
+namespace Mantid {
+namespace VATES {
 
 /**
  * This function constructs and executes the helper class.
  * @param dataset : The VTK data to modify
- * @param name : The MDWorkspace containing the information to construct modification
+ * @param name : The MDWorkspace containing the information to construct
+ * modification
  */
-void vtkDataSetToNonOrthogonalDataSet::exec(vtkDataSet *dataset, std::string name)
-{
+void vtkDataSetToNonOrthogonalDataSet::exec(vtkDataSet *dataset,
+                                            std::string name) {
   vtkDataSetToNonOrthogonalDataSet temp(dataset, name);
   temp.execute();
 }
@@ -38,40 +81,32 @@ void vtkDataSetToNonOrthogonalDataSet::exec(vtkDataSet *dataset, std::string nam
 /**
  * This is the private class constructor.
  * @param dataset : The VTK data to modify
- * @param name : The MDWorkspace containing the information to construct modification
+ * @param name : The MDWorkspace containing the information to construct
+ * modification
  */
-vtkDataSetToNonOrthogonalDataSet::vtkDataSetToNonOrthogonalDataSet(vtkDataSet *dataset,
-                                                                   std::string name) :
-  m_dataSet(dataset),
-  m_wsName(name),
-  m_hc(0),
-  m_numDims(3),
-  m_skewMat(),
-  m_basisNorm(),
-  m_basisX(1, 0, 0),
-  m_basisY(0, 1, 0),
-  m_basisZ(0, 0, 1),
-  m_coordType(Kernel::HKL)
-{
-  if (NULL == m_dataSet)
-  {
-    throw std::runtime_error("Cannot construct vtkDataSetToNonOrthogonalDataSet with null VTK dataset");
+vtkDataSetToNonOrthogonalDataSet::vtkDataSetToNonOrthogonalDataSet(
+    vtkDataSet *dataset, std::string name)
+    : m_dataSet(dataset), m_wsName(name), m_numDims(3), m_skewMat(),
+      m_basisNorm(), m_basisX(1, 0, 0), m_basisY(0, 1, 0), m_basisZ(0, 0, 1),
+      m_coordType(Kernel::HKL) {
+  if (NULL == m_dataSet) {
+    throw std::runtime_error("Cannot construct "
+                             "vtkDataSetToNonOrthogonalDataSet with null VTK "
+                             "dataset");
   }
-  if (name.empty())
-  {
-    throw std::runtime_error("Cannot construct vtkDataSetToNonOrthogonalDataSet without associated workspace name");
+  if (name.empty()) {
+    throw std::runtime_error("Cannot construct "
+                             "vtkDataSetToNonOrthogonalDataSet without "
+                             "associated workspace name");
   }
 }
 
 /**
  * Class destructor
  */
-vtkDataSetToNonOrthogonalDataSet::~vtkDataSetToNonOrthogonalDataSet()
-{
-}
+vtkDataSetToNonOrthogonalDataSet::~vtkDataSetToNonOrthogonalDataSet() {}
 
-void vtkDataSetToNonOrthogonalDataSet::execute()
-{
+void vtkDataSetToNonOrthogonalDataSet::execute() {
   // Downcast to a vtkUnstructuredGrid
   vtkUnstructuredGrid *data = vtkUnstructuredGrid::SafeDownCast(m_dataSet);
   if (NULL == data)
@@ -79,90 +114,79 @@ void vtkDataSetToNonOrthogonalDataSet::execute()
     throw std::runtime_error("VTK dataset does not inherit from vtkPointSet");
   }
 
-  if (0 == m_hc)
-  {
-    // Get the workspace from the ADS
-    ADSWorkspaceProvider<API::IMDWorkspace> workspaceProvider;
-    API::Workspace_sptr ws = workspaceProvider.fetchWorkspace(m_wsName);
-    std::string wsType = ws->id();
+  // Get the workspace from the ADS
+  ADSWorkspaceProvider<API::IMDWorkspace> workspaceProvider;
+  API::Workspace_sptr ws = workspaceProvider.fetchWorkspace(m_wsName);
+  std::string wsType = ws->id();
 
-    Geometry::OrientedLattice oLatt;
-    std::vector<double> wMatArr;
-    Kernel::Matrix<coord_t> affMat;
+  Geometry::OrientedLattice oLatt;
+  std::vector<double> wMatArr;
+  Kernel::Matrix<coord_t> affMat;
 
-    // Have to cast since inherited class doesn't provide access to all info
-    if (boost::algorithm::find_first(wsType, "MDHistoWorkspace"))
-    {
-      API::IMDHistoWorkspace_const_sptr infoWs = boost::dynamic_pointer_cast<const API::IMDHistoWorkspace>(ws);
-      m_numDims = infoWs->getNumDims();
-      m_coordType = infoWs->getSpecialCoordinateSystem();
-      if (Kernel::HKL != m_coordType)
-      {
-        throw std::invalid_argument("Cannot create non-orthogonal view for non-HKL coordinates");
-      }
-      const API::Sample sample = infoWs->getExperimentInfo(0)->sample();
-      if (!sample.hasOrientedLattice())
-      {
-        throw std::invalid_argument("OrientedLattice is not present on workspace");
-      }
-      oLatt = sample.getOrientedLattice();
-      const API::Run run = infoWs->getExperimentInfo(0)->run();
-      if (!run.hasProperty("W_MATRIX"))
-      {
-        throw std::invalid_argument("W_MATRIX is not present on workspace");
-      }
-      wMatArr = run.getPropertyValueAsType<std::vector<double > >("W_MATRIX");
-      try
-      {
-        API::CoordTransform const *transform = infoWs->getTransformToOriginal();
-        affMat = transform->makeAffineMatrix();
-      }
-      catch (std::runtime_error &)
-      {
-        // Create identity matrix of dimension+1
-        std::size_t nDims = infoWs->getNumDims() + 1;
-        Kernel::Matrix<coord_t> temp(nDims, nDims, true);
-        affMat = temp;
-      }
+  // Have to cast since inherited class doesn't provide access to all info
+  if (boost::algorithm::find_first(wsType, "MDHistoWorkspace")) {
+    API::IMDHistoWorkspace_const_sptr infoWs =
+        boost::dynamic_pointer_cast<const API::IMDHistoWorkspace>(ws);
+    m_numDims = infoWs->getNumDims();
+    m_coordType = infoWs->getSpecialCoordinateSystem();
+    if (Kernel::HKL != m_coordType) {
+      throw std::invalid_argument(
+          "Cannot create non-orthogonal view for non-HKL coordinates");
     }
-    // This is only here to make the unit test run.
-    if (boost::algorithm::find_first(wsType, "MDEventWorkspace"))
-    {
-      API::IMDEventWorkspace_const_sptr infoWs = boost::dynamic_pointer_cast<const API::IMDEventWorkspace>(ws);
-      m_numDims = infoWs->getNumDims();
-      m_coordType = infoWs->getSpecialCoordinateSystem();
-      if (Kernel::HKL != m_coordType)
-      {
-        throw std::invalid_argument("Cannot create non-orthogonal view for non-HKL coordinates");
-      }
-      const API::Sample sample = infoWs->getExperimentInfo(0)->sample();
-      if (!sample.hasOrientedLattice())
-      {
-        throw std::invalid_argument("OrientedLattice is not present on workspace");
-      }
-      oLatt = sample.getOrientedLattice();
-      const API::Run run = infoWs->getExperimentInfo(0)->run();
-      if (!run.hasProperty("W_MATRIX"))
-      {
-        throw std::invalid_argument("W_MATRIX is not present on workspace");
-      }
-      wMatArr = run.getPropertyValueAsType<std::vector<double > >("W_MATRIX");
-      try
-      {
-        API::CoordTransform const *transform = infoWs->getTransformToOriginal();
-        affMat = transform->makeAffineMatrix();
-      }
-      catch (std::runtime_error &)
-      {
-        // Create identity matrix of dimension+1
-        std::size_t nDims = infoWs->getNumDims() + 1;
-        Kernel::Matrix<coord_t> temp(nDims, nDims, true);
-        affMat = temp;
-      }
+    const API::Sample sample = infoWs->getExperimentInfo(0)->sample();
+    if (!sample.hasOrientedLattice()) {
+      throw std::invalid_argument(
+          "OrientedLattice is not present on workspace");
+    }
+    oLatt = sample.getOrientedLattice();
+    const API::Run run = infoWs->getExperimentInfo(0)->run();
+    if (!run.hasProperty("W_MATRIX")) {
+      throw std::invalid_argument("W_MATRIX is not present on workspace");
+    }
+    wMatArr = run.getPropertyValueAsType<std::vector<double>>("W_MATRIX");
+    try {
+      API::CoordTransform const * transform = infoWs->getTransformToOriginal();
+      affMat = transform->makeAffineMatrix();
+    } catch (std::runtime_error &) {
+      // Create identity matrix of dimension+1
+      std::size_t nDims = infoWs->getNumDims() + 1;
+      Kernel::Matrix<coord_t> temp(nDims, nDims, true);
+      affMat = temp;
     }
-    Kernel::DblMatrix wTrans(wMatArr);
-    this->createSkewInformation(oLatt, wTrans, affMat);
   }
+  // This is only here to make the unit test run.
+  if (boost::algorithm::find_first(wsType, "MDEventWorkspace")) {
+    API::IMDEventWorkspace_const_sptr infoWs =
+        boost::dynamic_pointer_cast<const API::IMDEventWorkspace>(ws);
+    m_numDims = infoWs->getNumDims();
+    m_coordType = infoWs->getSpecialCoordinateSystem();
+    if (Kernel::HKL != m_coordType) {
+      throw std::invalid_argument(
+          "Cannot create non-orthogonal view for non-HKL coordinates");
+    }
+    const API::Sample sample = infoWs->getExperimentInfo(0)->sample();
+    if (!sample.hasOrientedLattice()) {
+      throw std::invalid_argument(
+          "OrientedLattice is not present on workspace");
+    }
+    oLatt = sample.getOrientedLattice();
+    const API::Run run = infoWs->getExperimentInfo(0)->run();
+    if (!run.hasProperty("W_MATRIX")) {
+      throw std::invalid_argument("W_MATRIX is not present on workspace");
+    }
+    wMatArr = run.getPropertyValueAsType<std::vector<double>>("W_MATRIX");
+    try {
+      API::CoordTransform const *transform = infoWs->getTransformToOriginal();
+      affMat = transform->makeAffineMatrix();
+    } catch (std::runtime_error &) {
+      // Create identity matrix of dimension+1
+      std::size_t nDims = infoWs->getNumDims() + 1;
+      Kernel::Matrix<coord_t> temp(nDims, nDims, true);
+      affMat = temp;
+    }
+  }
+  Kernel::DblMatrix wTrans(wMatArr);
+  this->createSkewInformation(oLatt, wTrans, affMat);
 
   // Get the original points
   vtkPoints *points = data->GetPoints();
@@ -172,60 +196,17 @@ void vtkDataSetToNonOrthogonalDataSet::execute()
 
   /// Put together the skew matrix for use
   double skew[9];
-  switch (m_hc)
-  {
-  case 1:
-    // Gd, HEKL
-    skew[0] = 1.0;
-    skew[1] = 0.0;
-    skew[2] = 0.5;
-    skew[3] = 0.0;
-    skew[4] = 1.0;
-    skew[5] = 0.0;
-    skew[6] = 0.0;
-    skew[7] = 0.0;
-    skew[8] = 0.8660254;
-    break;
-  case 2:
-    // Gd2, HEKL
-    skew[0] = 1.0;
-    skew[1] = 0.0;
-    skew[2] = 0.0;
-    skew[3] = 0.0;
-    skew[4] = 1.0;
-    skew[5] = 0.0;
-    skew[6] = 0.0;
-    skew[7] = 0.0;
-    skew[8] = 1.0;
-    break;
-  case 3:
-    // Gd2, HEKL, a scaled
-    skew[0] = 1.0;
-    skew[1] = 0.0;
-    skew[2] = -0.65465367;
-    skew[3] = 0.0;
-    skew[4] = 1.0;
-    skew[5] = 0.0;
-    skew[6] = 0.0;
-    skew[7] = 0.0;
-    skew[8] = 0.75592895;
-    break;
-  default:
-    // Create from the internal skew matrix
-    std::size_t index = 0;
-    for (std::size_t i = 0; i < m_skewMat.numRows(); i++)
-    {
-      for(std::size_t j = 0; j < m_skewMat.numCols(); j++)
-      {
-        skew[index] = m_skewMat[i][j];
-        index++;
-      }
+
+  // Create from the internal skew matrix
+  std::size_t index = 0;
+  for (std::size_t i = 0; i < m_skewMat.numRows(); i++) {
+    for (std::size_t j = 0; j < m_skewMat.numCols(); j++) {
+      skew[index] = m_skewMat[i][j];
+      index++;
     }
-    break;
   }
 
-  for(int i = 0; i < points->GetNumberOfPoints(); i++)
-  {
+  for (int i = 0; i < points->GetNumberOfPoints(); i++) {
     double *inPoint = points->GetPoint(i);
     vtkMatrix3x3::MultiplyPoint(skew, inPoint, outPoint);
     newPoints->InsertNextPoint(outPoint);
@@ -238,14 +219,14 @@ void vtkDataSetToNonOrthogonalDataSet::execute()
  * This function will create the skew matrix and basis for a non-orthogonal
  * representation.
  *
- * @param ol : The oriented lattice containing B matrix and crystal basis vectors
+ * @param ol : The oriented lattice containing B matrix and crystal basis
+ *vectors
  * @param w : The tranform requested when MDworkspace was created
  * @param aff : The affine matrix taking care of coordinate transformations
  */
-void vtkDataSetToNonOrthogonalDataSet::createSkewInformation(Geometry::OrientedLattice &ol,
-                                                             Kernel::DblMatrix &w,
-                                                             Kernel::Matrix<coord_t> &aff)
-{
+void vtkDataSetToNonOrthogonalDataSet::createSkewInformation(
+    Geometry::OrientedLattice &ol, Kernel::DblMatrix &w,
+    Kernel::Matrix<coord_t> &aff) {
   // Get the B matrix
   Kernel::DblMatrix bMat = ol.getB();
   // Apply the W tranform matrix
@@ -257,11 +238,9 @@ void vtkDataSetToNonOrthogonalDataSet::createSkewInformation(Geometry::OrientedL
   m_skewMat = uc.getB();
   // Calculate the column normalisation
   std::vector<double> bNorm;
-  for (std::size_t i = 0; i < m_skewMat.numCols(); i++)
-  {
+  for (std::size_t i = 0; i < m_skewMat.numCols(); i++) {
     double sum = 0.0;
-    for (std::size_t j = 0; j < m_skewMat.numRows(); j++)
-    {
+    for (std::size_t j = 0; j < m_skewMat.numRows(); j++) {
       sum += m_skewMat[j][i] * m_skewMat[j][i];
     }
     bNorm.push_back(std::sqrt(sum));
@@ -275,20 +254,17 @@ void vtkDataSetToNonOrthogonalDataSet::createSkewInformation(Geometry::OrientedL
 
   // Setup basis normalisation array
   // Intel and MSBuild can't handle this
-  //m_basisNorm = {ol.astar(), ol.bstar(), ol.cstar()};
+  // m_basisNorm = {ol.astar(), ol.bstar(), ol.cstar()};
   m_basisNorm.push_back(ol.astar());
   m_basisNorm.push_back(ol.bstar());
   m_basisNorm.push_back(ol.cstar());
 
   // Expand matrix to 4 dimensions if necessary
-  if (4 == m_numDims)
-  {
+  if (4 == m_numDims) {
     m_basisNorm.push_back(1.0);
     Kernel::DblMatrix temp(4, 4, true);
-    for (std::size_t i = 0; i < 3; i++)
-    {
-      for (std::size_t j = 0; j < 3; j++)
-      {
+    for (std::size_t i = 0; i < 3; i++) {
+      for (std::size_t j = 0; j < 3; j++) {
         temp[i][j] = m_skewMat[i][j];
       }
     }
@@ -297,10 +273,8 @@ void vtkDataSetToNonOrthogonalDataSet::createSkewInformation(Geometry::OrientedL
 
   // Convert affine matrix to similar type as others
   Kernel::DblMatrix affMat(aff.numRows(), aff.numCols());
-  for (std::size_t i = 0; i < aff.numRows(); i++)
-  {
-    for (std::size_t j = 0; j < aff.numCols(); j++)
-    {
+  for (std::size_t i = 0; i < aff.numRows(); i++) {
+    for (std::size_t j = 0; j < aff.numCols(); j++) {
       affMat[i][j] = aff[i][j];
     }
   }
@@ -310,8 +284,7 @@ void vtkDataSetToNonOrthogonalDataSet::createSkewInformation(Geometry::OrientedL
   // Perform similarity transform to get coordinate orientation correct
   m_skewMat = affMat.Tprime() * (m_skewMat * affMat);
   m_basisNorm = affMat * m_basisNorm;
-  if (4 == m_numDims)
-  {
+  if (4 == m_numDims) {
     this->stripMatrix(m_skewMat);
   }
 
@@ -327,8 +300,7 @@ void vtkDataSetToNonOrthogonalDataSet::createSkewInformation(Geometry::OrientedL
  * @param scale : Scale factor for the basis vector.
  */
 void vtkDataSetToNonOrthogonalDataSet::findSkewBasis(Kernel::V3D &basis,
-                                                     double scale)
-{
+                                                     double scale) {
   basis = m_skewMat * basis;
   basis /= scale;
   basis.normalize();
@@ -340,34 +312,17 @@ void vtkDataSetToNonOrthogonalDataSet::findSkewBasis(Kernel::V3D &basis,
  *
  * @param mat : The matrix to strip dimensionality
  */
-void vtkDataSetToNonOrthogonalDataSet::stripMatrix(Kernel::DblMatrix &mat)
-{
+void vtkDataSetToNonOrthogonalDataSet::stripMatrix(Kernel::DblMatrix &mat) {
   std::size_t dim = mat.Ssize() - 1;
   Kernel::DblMatrix temp(dim, dim);
-  for (std::size_t i = 0; i < dim; i++)
-  {
-    for (std::size_t j = 0; j < dim; j++)
-    {
+  for (std::size_t i = 0; i < dim; i++) {
+    for (std::size_t j = 0; j < dim; j++) {
       temp[i][j] = mat[i][j];
     }
   }
   mat = temp;
 }
 
-/**
- * This function copies a vector to a C array.
- *
- * @param arr : The array to copy into
- * @param vec : The vector to copy from
- */
-void vtkDataSetToNonOrthogonalDataSet::copyToRaw(double *arr, MantidVec vec)
-{
-  for (std::size_t i = 0; i < vec.size(); i++)
-  {
-    arr[i] = vec[i];
-  }
-}
-
 /**
  * This function is responsible for adding the skew basis information to the
  * VTK dataset.
@@ -375,77 +330,8 @@ void vtkDataSetToNonOrthogonalDataSet::copyToRaw(double *arr, MantidVec vec)
  */
 void vtkDataSetToNonOrthogonalDataSet::updateMetaData(vtkUnstructuredGrid *ugrid)
 {
-  double baseX[3];
-  double baseY[3];
-  double baseZ[3];
-  switch (m_hc)
-  {
-  case 1:
-    // Gd, HEKL
-    baseX[0] = 1.0;
-    baseX[1] = 0.0;
-    baseX[2] = 0.0;
-    baseY[0] = 0.0;
-    baseY[1] = 1.0;
-    baseY[2] = 0.0;
-    baseZ[0] = 0.5;
-    baseZ[1] = 0.0;
-    baseZ[2] = 0.8660254;
-    break;
-  case 2:
-    // Gd2, HEKL
-    baseX[0] = 1.0;
-    baseX[1] = 0.0;
-    baseX[2] = 0.0;
-    baseY[0] = 0.0;
-    baseY[1] = 1.0;
-    baseY[2] = 0.0;
-    baseZ[0] = 0.0;
-    baseZ[1] = 0.0;
-    baseZ[2] = 1.0;
-    break;
-  case 3:
-    // Gd2, HEKL, a scaled
-    baseX[0] = 1.0;
-    baseX[1] = 0.0;
-    baseX[2] = 0.0;
-    baseY[0] = 0.0;
-    baseY[1] = 1.0;
-    baseY[2] = 0.0;
-    baseZ[0] = -0.65465367;
-    baseZ[1] = 0.0;
-    baseZ[2] = 0.75592895;
-    break;
-  default:
-    // Create from the internal basis vectors
-    this->copyToRaw(baseX, m_basisX);
-    this->copyToRaw(baseY, m_basisY);
-    this->copyToRaw(baseZ, m_basisZ);
-    break;
-  }
-
-  vtkFieldData *fieldData = ugrid->GetFieldData();
-
-  vtkNew<vtkFloatArray> uBase;
-  uBase->SetNumberOfComponents(3);
-  uBase->SetNumberOfTuples(1);
-  uBase->SetName("AxisBaseForX");
-  uBase->SetTuple(0, baseX);
-  fieldData->AddArray(uBase.GetPointer());
-
-  vtkNew<vtkFloatArray> vBase;
-  vBase->SetNumberOfComponents(3);
-  vBase->SetNumberOfTuples(1);
-  vBase->SetName("AxisBaseForY");
-  vBase->SetTuple(0, baseY);
-  fieldData->AddArray(vBase.GetPointer());
-
-  vtkNew<vtkFloatArray> wBase;
-  wBase->SetNumberOfComponents(3);
-  wBase->SetNumberOfTuples(1);
-  wBase->SetName("AxisBaseForZ");
-  wBase->SetTuple(0, baseZ);
-  fieldData->AddArray(wBase.GetPointer());
+  // Create and add the change of basis matrix
+  addChangeOfBasisMatrixToFieldData(ugrid, m_basisX, m_basisY, m_basisZ);
 }
 
 } // namespace VATES
diff --git a/Code/Mantid/Vates/VatesAPI/src/vtkMD0DFactory.cpp b/Code/Mantid/Vates/VatesAPI/src/vtkMD0DFactory.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..aec3c485aeef744243571fdd1e076cf5b9b8c46f
--- /dev/null
+++ b/Code/Mantid/Vates/VatesAPI/src/vtkMD0DFactory.cpp
@@ -0,0 +1,55 @@
+#include "MantidVatesAPI/vtkMD0DFactory.h"
+#include "MantidAPI/IMDWorkspace.h"
+#include "MantidVatesAPI/vtkNullUnstructuredGrid.h"
+#include "MantidVatesAPI/ProgressAction.h"
+#include "MantidKernel/Logger.h"
+
+using namespace Mantid::API;
+
+namespace
+{
+  Mantid::Kernel::Logger g_log("vtkMD0DFactory");
+}
+
+namespace Mantid
+{
+  namespace VATES
+  {
+    /**
+    Constructor
+    @param thresholdRange : Thresholding range functor
+    @param scalarName : Name to give to signal
+    */
+    vtkMD0DFactory::vtkMD0DFactory(ThresholdRange_scptr thresholdRange, const std::string& scalarName) : m_thresholdRange(thresholdRange), m_scalarName(scalarName)
+    {
+    }
+
+    /// Destructor
+    vtkMD0DFactory::~vtkMD0DFactory()
+    {
+    }
+
+    /**
+    Create the vtkStructuredGrid from the provided workspace
+    @param progressUpdating: Reporting object to pass progress information up the stack.
+    @return fully constructed vtkDataSet.
+    */
+    vtkDataSet* vtkMD0DFactory::create(ProgressAction&) const
+    {
+      g_log.warning() << "Factory " << this->getFactoryTypeName() << " is being used. You are viewing data with less than three dimensions in the VSI. \n";
+      vtkNullUnstructuredGrid nullGrid;
+      vtkUnstructuredGrid *visualDataSet = nullGrid.createNullData();
+      return visualDataSet;
+    }
+
+    /// Initalize with a target workspace.
+    void vtkMD0DFactory::initialize(Mantid::API::Workspace_sptr)
+    {
+    }
+
+   /// Validate the workspace 
+   void vtkMD0DFactory::validate() const
+   {
+   }
+  }
+}
diff --git a/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoHexFactory.cpp b/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoHexFactory.cpp
index 542279787b5bf392132c36c340e52080a7b5ef20..54935b90efdaaa948b0c533fe902dad3b6697f04 100644
--- a/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoHexFactory.cpp
+++ b/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoHexFactory.cpp
@@ -271,10 +271,6 @@ namespace VATES
       }
     }
     theHex->Delete();
-
-    std::cout << tim << " to create and add the hexadrons." << std::endl;
-
-
     points->Delete();
     signal->Delete();
     visualDataSet->Squeeze();
diff --git a/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoLineFactory.cpp b/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoLineFactory.cpp
index 87c7f890b2cb77042da5907fde1def4d9fe16187..b7aabb2e6cae64ccf6de42477baf153537c84c21 100644
--- a/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoLineFactory.cpp
+++ b/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoLineFactory.cpp
@@ -12,11 +12,17 @@
 #include "MantidAPI/NullCoordTransform.h"
 #include "MantidDataObjects/MDHistoWorkspace.h"
 #include "MantidKernel/ReadLock.h"
+#include "MantidKernel/Logger.h"
 
 using Mantid::API::IMDWorkspace;
 using Mantid::DataObjects::MDHistoWorkspace;
 using Mantid::API::NullCoordTransform;
 
+namespace
+{
+  Mantid::Kernel::Logger g_log("vtkMDHistoLineFactory");
+}
+
 namespace Mantid
 {
 
@@ -69,6 +75,8 @@ namespace Mantid
       }
       else
       {
+        g_log.warning() << "Factory " << this->getFactoryTypeName() << " is being used. You are viewing data with less than three dimensions in the VSI. \n";
+
         Mantid::Kernel::ReadLock lock(*m_workspace);
         const int nBinsX = static_cast<int>( m_workspace->getXDimension()->getNBins() );
 
diff --git a/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoQuadFactory.cpp b/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoQuadFactory.cpp
index dd30c422155a5aff6963394b795dca1f8de572ab..794622e51a72f7255722b59091a86bb9597b2676 100644
--- a/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoQuadFactory.cpp
+++ b/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoQuadFactory.cpp
@@ -13,17 +13,22 @@
 #include "vtkSmartPointer.h" 
 #include <vector>
 #include "MantidKernel/ReadLock.h"
+#include "MantidKernel/Logger.h"
 
 using Mantid::API::IMDWorkspace;
 using Mantid::Kernel::CPUTimer;
 using Mantid::DataObjects::MDHistoWorkspace;
 
+namespace
+{
+  Mantid::Kernel::Logger g_log("vtkMDHistoQuadFactory");
+}
+
 namespace Mantid
 {
 
   namespace VATES
   {
-
     vtkMDHistoQuadFactory::vtkMDHistoQuadFactory(ThresholdRange_scptr thresholdRange, const std::string& scalarName) : m_scalarName(scalarName), m_thresholdRange(thresholdRange)
     {
     }
@@ -69,6 +74,8 @@ namespace Mantid
       }
       else
       {
+        g_log.warning() << "Factory " << this->getFactoryTypeName() << " is being used. You are viewing data with less than three dimensions in the VSI. \n";
+
         Mantid::Kernel::ReadLock lock(*m_workspace);
         CPUTimer tim;
         const int nBinsX = static_cast<int>( m_workspace->getXDimension()->getNBins() );
diff --git a/Code/Mantid/Vates/VatesAPI/src/vtkMDLineFactory.cpp b/Code/Mantid/Vates/VatesAPI/src/vtkMDLineFactory.cpp
index d6b392cc3b06635aa21d80a7d2bc6b650616b00f..c66e528aff082005bf273639153724f70929e13c 100644
--- a/Code/Mantid/Vates/VatesAPI/src/vtkMDLineFactory.cpp
+++ b/Code/Mantid/Vates/VatesAPI/src/vtkMDLineFactory.cpp
@@ -13,9 +13,15 @@
 #include <vtkLine.h>
 #include <vtkCellData.h>
 #include "MantidKernel/ReadLock.h"
+#include "MantidKernel/Logger.h"
 
 using namespace Mantid::API;
 
+namespace
+{
+  Mantid::Kernel::Logger g_log("vtkMDLineFactory");
+}
+
 namespace Mantid
 {
   namespace VATES
@@ -48,6 +54,8 @@ namespace Mantid
       }
       else
       {
+        g_log.warning() << "Factory " << this->getFactoryTypeName() << " is being used. You are viewing data with less than three dimensions in the VSI. \n";
+
         IMDEventWorkspace_sptr imdws = doInitialize<IMDEventWorkspace, 1>(m_workspace);
         // Acquire a scoped read-only lock to the workspace (prevent segfault from algos modifying ws)
         Mantid::Kernel::ReadLock lock(*imdws);
diff --git a/Code/Mantid/Vates/VatesAPI/src/vtkMDQuadFactory.cpp b/Code/Mantid/Vates/VatesAPI/src/vtkMDQuadFactory.cpp
index b1a096fa9597155d821045b414a1f57c68201623..3debbc0aeb26cdb8f36730aafd86b4d689e10d24 100644
--- a/Code/Mantid/Vates/VatesAPI/src/vtkMDQuadFactory.cpp
+++ b/Code/Mantid/Vates/VatesAPI/src/vtkMDQuadFactory.cpp
@@ -13,9 +13,15 @@
 #include <vtkQuad.h>
 #include <vtkCellData.h>
 #include "MantidKernel/ReadLock.h"
+#include "MantidKernel/Logger.h"
 
 using namespace Mantid::API;
 
+namespace
+{
+  Mantid::Kernel::Logger g_log("vtkMDQuadFactory");
+}
+
 namespace Mantid
 {
   namespace VATES
@@ -44,6 +50,8 @@ namespace Mantid
       }
       else
       {
+        g_log.warning() << "Factory " << this->getFactoryTypeName() << " is being used. You are viewing data with less than three dimensions in the VSI. \n";
+
         IMDEventWorkspace_sptr imdws = this->castAndCheck<IMDEventWorkspace, 2>(m_workspace);
         // Acquire a scoped read-only lock to the workspace (prevent segfault from algos modifying ws)
         Mantid::Kernel::ReadLock lock(*imdws);
diff --git a/Code/Mantid/Vates/VatesAPI/src/vtkPeakMarkerFactory.cpp b/Code/Mantid/Vates/VatesAPI/src/vtkPeakMarkerFactory.cpp
index be22450371ac2316f269c44710fa64f2cb66e35a..b2f7c9056cd9908610674d4b907e8e172fd323fe 100644
--- a/Code/Mantid/Vates/VatesAPI/src/vtkPeakMarkerFactory.cpp
+++ b/Code/Mantid/Vates/VatesAPI/src/vtkPeakMarkerFactory.cpp
@@ -17,7 +17,7 @@
 #include <vtkPolyDataAlgorithm.h>
 #include <vtkAppendPolyData.h>
 #include <vtkVertex.h>
-#include <vtkGlyph3D.h>
+#include "MantidVatesAPI/vtkGlyph3D_Silent.h"
 #include <vtkSphereSource.h>
 #include <vtkUnstructuredGrid.h>
 #include <vtkFloatArray.h>
diff --git a/Code/Mantid/Vates/VatesAPI/src/vtkSplatterPlotFactory.cpp b/Code/Mantid/Vates/VatesAPI/src/vtkSplatterPlotFactory.cpp
index d777525c7668bc2f5f15af19fbe01bdd01e68973..11b8aecd891edc293b9e7fa29c91816081d108f6 100644
--- a/Code/Mantid/Vates/VatesAPI/src/vtkSplatterPlotFactory.cpp
+++ b/Code/Mantid/Vates/VatesAPI/src/vtkSplatterPlotFactory.cpp
@@ -65,6 +65,8 @@ namespace VATES
   m_buildSortedList(true), m_wsName(""), dataSet(NULL),
   slice(false), sliceMask(NULL), sliceImplicitFunction(NULL),
   m_time(0.0),
+  m_minValue(0.1),
+  m_maxValue(0.1),
   m_metaDataExtractor(new MetaDataExtractorUtils()),
   m_metadataJsonManager(new MetadataJsonManager()),
   m_vatesConfigurations(new VatesConfigurations())
diff --git a/Code/Mantid/Vates/VatesAPI/test/CompositePeaksPresenterVsiTest.h b/Code/Mantid/Vates/VatesAPI/test/CompositePeaksPresenterVsiTest.h
index a237129ebf5a1bb0f24e777e2ebbc645639f36b8..0db214886e04ca7fb23eb84d0834876a31c068d1 100644
--- a/Code/Mantid/Vates/VatesAPI/test/CompositePeaksPresenterVsiTest.h
+++ b/Code/Mantid/Vates/VatesAPI/test/CompositePeaksPresenterVsiTest.h
@@ -4,10 +4,13 @@
 #include <cxxtest/TestSuite.h>
 #include "MantidVatesAPI/CompositePeaksPresenterVsi.h"
 #include "MantidVatesAPI/ConcretePeaksPresenterVsi.h"
+#include "MantidVatesAPI/ViewFrustum.h"
 #include "MantidAPI/IPeaksWorkspace.h"
 #include "MantidDataObjects/PeaksWorkspace.h"
 
+
 #include <boost/shared_ptr.hpp>
+#include <boost/make_shared.hpp>
 #include <stdexcept>
 
 #include "MockObjects.h"
@@ -58,9 +61,10 @@ public:
     TopPlane top(0.0, -1.0, 0.0, 1.0);
     FarPlane farPlane(0.0, 0.0, 1.0, 1.0);
     NearPlane nearPlane(0.0, 0.0, -1.0,1.0);
-    ViewFrustum frustum(left, right, bottom, top, farPlane, nearPlane);
+    ViewFrustum_const_sptr frustum = boost::make_shared<const Mantid::VATES::ViewFrustum>(left, right, bottom, top, farPlane, nearPlane);
 
     boost::shared_ptr<MockPeaksWorkspaceComposite> pw_ptr(new MockPeaksWorkspaceComposite());
+    
     std::string name = "pw1";
     PeaksPresenterVsi_sptr p1(new ConcretePeaksPresenterVsi(pw_ptr, frustum, frame));
 
@@ -92,7 +96,7 @@ public:
     TopPlane top(0.0, -1.0, 0.0, 1.0);
     FarPlane farPlane(0.0, 0.0, 1.0, 1.0);
     NearPlane nearPlane(0.0, 0.0, -1.0,1.0);
-    ViewFrustum frustum(left, right, bottom, top, farPlane, nearPlane);
+    ViewFrustum_const_sptr frustum = boost::make_shared<const Mantid::VATES::ViewFrustum>(left, right, bottom, top, farPlane, nearPlane);
 
     boost::shared_ptr<MockPeaksWorkspaceComposite> pw_ptr(new MockPeaksWorkspaceComposite());
     std::string name = "pw1";
diff --git a/Code/Mantid/Vates/VatesAPI/test/ConcretePeaksPresenterVsiTest.h b/Code/Mantid/Vates/VatesAPI/test/ConcretePeaksPresenterVsiTest.h
index 0d0126ce10ecdacd0439353cacae27b39b18ca79..de24ad83113c7bca671c0ac576d832c10f00b632 100644
--- a/Code/Mantid/Vates/VatesAPI/test/ConcretePeaksPresenterVsiTest.h
+++ b/Code/Mantid/Vates/VatesAPI/test/ConcretePeaksPresenterVsiTest.h
@@ -12,6 +12,7 @@
 #include "MantidKernel/V3D.h"
 #include "MockObjects.h"
 #include <boost/shared_ptr.hpp>
+#include <boost/make_shared.hpp>
 
 #include <cxxtest/TestSuite.h>
 #include <gmock/gmock.h>
@@ -53,7 +54,7 @@ public:
     TopPlane top(0.0, -1.0, 0.0, 1.0);
     FarPlane farPlane(0.0, 0.0, 1.0, 1.0);
     NearPlane nearPlane(0.0, 0.0, -1.0,1.0);
-    ViewFrustum frustum(left, right, bottom, top, farPlane, nearPlane);
+    ViewFrustum_const_sptr frustum = boost::make_shared<const Mantid::VATES::ViewFrustum>(left, right, bottom, top, farPlane, nearPlane);
 
     boost::shared_ptr<MockPeaksWorkspaceConcrete> pw_ptr(new MockPeaksWorkspaceConcrete());
     // Act
@@ -73,7 +74,7 @@ public:
     TopPlane top(0.0, -1.0, 0.0, 1.0);
     FarPlane farPlane(0.0, 0.0, 1.0, 1.0);
     NearPlane nearPlane(0.0, 0.0, -1.0,1.0);
-    ViewFrustum frustum(left, right, bottom, top, farPlane, nearPlane);
+    ViewFrustum_const_sptr frustum = boost::make_shared<const Mantid::VATES::ViewFrustum>(left, right, bottom, top, farPlane, nearPlane);
 
     Mantid::Kernel::V3D coordinate(1,0,0);
     double peakRadius = 10;
diff --git a/Code/Mantid/Vates/VatesAPI/test/MockObjects.h b/Code/Mantid/Vates/VatesAPI/test/MockObjects.h
index 39404d1b97db3dac076d4de9e9d3890adb220ccd..9f2f74692bfa6a56754c42235b7847eb8e2d5394 100644
--- a/Code/Mantid/Vates/VatesAPI/test/MockObjects.h
+++ b/Code/Mantid/Vates/VatesAPI/test/MockObjects.h
@@ -30,6 +30,12 @@ using Mantid::Geometry::MDHistoDimension;
 using Mantid::Geometry::MDHistoDimension_sptr;
 using Mantid::coord_t;
 
+// Allow unused functions.
+#if __clang__
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wunused-function"
+#endif
+
 //=====================================================================================
 // Test Helper Types. These are shared by several tests in VatesAPI
 //=====================================================================================
@@ -479,4 +485,8 @@ Create a field data entry containing (as contents) the argument text.
 
 } // namespace
 
+#if __clang__
+#pragma clang diagnostic pop
+#endif
+
 #endif
diff --git a/Code/Mantid/Vates/VatesAPI/test/NullPeaksPresenterVsiTest.h b/Code/Mantid/Vates/VatesAPI/test/NullPeaksPresenterVsiTest.h
index 05826c892535f37ae7dbcb4664a6b8b39fcc35e8..7c668ed28cbdb23651120bceac8883f06a7ae101 100644
--- a/Code/Mantid/Vates/VatesAPI/test/NullPeaksPresenterVsiTest.h
+++ b/Code/Mantid/Vates/VatesAPI/test/NullPeaksPresenterVsiTest.h
@@ -33,9 +33,9 @@ public:
     int row = 0;
     double radius;
     Mantid::Kernel::V3D position;
-    Mantid::Kernel::SpecialCoordinateSystem coord;
+    Mantid::Kernel::SpecialCoordinateSystem coord = Mantid::Kernel::SpecialCoordinateSystem::None;
     Mantid::API::IPeaksWorkspace_sptr peaksWorkspace;
     TSM_ASSERT_THROWS("Should not implement this method", presenter.getPeaksInfo(peaksWorkspace,row,position,radius, coord), std::runtime_error);
   }
 };
-#endif
\ No newline at end of file
+#endif
diff --git a/Code/Mantid/Vates/VatesAPI/test/VatesKnowledgeSerializerTest.h b/Code/Mantid/Vates/VatesAPI/test/VatesKnowledgeSerializerTest.h
index 6100f48902c027f078d7b676cf4b98cb48704bd7..28aa62739202da3c7cca799a5b0fca53a27a397f 100644
--- a/Code/Mantid/Vates/VatesAPI/test/VatesKnowledgeSerializerTest.h
+++ b/Code/Mantid/Vates/VatesAPI/test/VatesKnowledgeSerializerTest.h
@@ -55,7 +55,7 @@ void testNoLocationDoesNotThrow()
   EXPECT_CALL(*pImpFunction, toXMLString()).Times(1).WillRepeatedly(testing::Return("<ImplicitFunction/>"));
   Mantid::Geometry::MDImplicitFunction_sptr impFunction(pImpFunction);
   
-  VatesKnowledgeSerializer generator(LocationNotRequired); //Location is not required.
+  VatesKnowledgeSerializer generator; //Location is not required.
   generator.setImplicitFunction(impFunction);
   generator.setWorkspace(workspace);
 
diff --git a/Code/Mantid/Vates/VatesAPI/test/vtkDataSetToNonOrthogonalDataSetTest.h b/Code/Mantid/Vates/VatesAPI/test/vtkDataSetToNonOrthogonalDataSetTest.h
index 6ca224d78ba7cf4948ff8d3405a19cbdb2849a03..faa9802da3a6770c470a36492b5a46aa62ffbf0a 100644
--- a/Code/Mantid/Vates/VatesAPI/test/vtkDataSetToNonOrthogonalDataSetTest.h
+++ b/Code/Mantid/Vates/VatesAPI/test/vtkDataSetToNonOrthogonalDataSetTest.h
@@ -160,12 +160,13 @@ private:
     return ds;
   }
 
-  float *getRangeComp(vtkDataSet *ds, std::string fieldname, int size)
+  template<typename T>
+  T *getRangeComp(vtkDataSet *ds, std::string fieldname, int size)
   {
     vtkDataArray *arr = ds->GetFieldData()->GetArray(fieldname.c_str());
-    vtkFloatArray *farr = vtkFloatArray::SafeDownCast(arr);
-    float *vals = new float[size];
-    farr->GetTupleValue(0, vals);
+    vtkTypedDataArray<T>* tarr = vtkTypedDataArray<T>::FastDownCast(arr);
+    T *vals = new T[size];
+    tarr->GetTupleValue(0, vals);
     return vals;
   }
 
@@ -181,21 +182,37 @@ private:
     TS_ASSERT_DELTA(point[1], 1.0, eps);
     TS_ASSERT_DELTA(point[2], 0.8660254, eps);
     // See if the basis vectors are available
-    float *xBasis = getRangeComp(grid, "AxisBaseForX", 3);
-    TS_ASSERT_DELTA(xBasis[0], 1.0, eps);
-    TS_ASSERT_DELTA(xBasis[1], 0.0, eps);
-    TS_ASSERT_DELTA(xBasis[2], 0.0, eps);
-    delete [] xBasis;
-    float *yBasis = getRangeComp(grid, "AxisBaseForY", 3);
-    TS_ASSERT_DELTA(yBasis[0], 0.0, eps);
-    TS_ASSERT_DELTA(yBasis[1], 1.0, eps);
-    TS_ASSERT_DELTA(yBasis[2], 0.0, eps);
-    delete [] yBasis;
-    float *zBasis = getRangeComp(grid, "AxisBaseForZ", 3);
-    TS_ASSERT_DELTA(zBasis[0], 0.5, eps);
-    TS_ASSERT_DELTA(zBasis[1], 0.0, eps);
-    TS_ASSERT_DELTA(zBasis[2], 0.8660254, eps);
-    delete [] zBasis;
+
+    double *basisMatrix = getRangeComp<double>(grid, "ChangeOfBasisMatrix", 16);
+    
+    // Row by row check
+
+    // basisX[0], basisY[0], basisZ[0], 0
+    int index = 0;
+    TS_ASSERT_DELTA(basisMatrix[index++], 1.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.5, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+
+    // basisX[1], basisY[1], basisZ[1], 0
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 1.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+
+    // basisX[2], basisY[2], basisZ[2], 0
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.8660254, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+
+    //0, 0, 0, 1
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 1.0, eps);
+
+    delete basisMatrix;
   }
 
 public:
@@ -296,21 +313,37 @@ public:
     TS_ASSERT_DELTA(point[1], 1.0, eps);
     TS_ASSERT_DELTA(point[2], 1.0, eps);
     // See if the basis vectors are available
-    float *xBasis = getRangeComp(ds, "AxisBaseForX", 3);
-    TS_ASSERT_DELTA(xBasis[0], 1.0, eps);
-    TS_ASSERT_DELTA(xBasis[1], 0.0, eps);
-    TS_ASSERT_DELTA(xBasis[2], 0.0, eps);
-    delete [] xBasis;
-    float *yBasis = getRangeComp(ds, "AxisBaseForY", 3);
-    TS_ASSERT_DELTA(yBasis[0], 0.0, eps);
-    TS_ASSERT_DELTA(yBasis[1], 1.0, eps);
-    TS_ASSERT_DELTA(yBasis[2], 0.0, eps);
-    delete [] yBasis;
-    float *zBasis = getRangeComp(ds, "AxisBaseForZ", 3);
-    TS_ASSERT_DELTA(zBasis[0], 0.0, eps);
-    TS_ASSERT_DELTA(zBasis[1], 0.0, eps);
-    TS_ASSERT_DELTA(zBasis[2], 1.0, eps);
-    delete [] zBasis;
+    double *basisMatrix = getRangeComp<double>(ds, "ChangeOfBasisMatrix", 16);
+    
+    // Row by row check
+
+    // basisX[0], basisY[0], basisZ[0], 0
+    int index = 0;
+    TS_ASSERT_DELTA(basisMatrix[index++], 1.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+
+    // basisX[1], basisY[1], basisZ[1], 0
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 1.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+
+    // basisX[2], basisY[2], basisZ[2], 0
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 1.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+
+    //0, 0, 0, 1
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 1.0, eps);
+
+    delete basisMatrix;
+    
     ds->Delete();
   }
 
@@ -338,21 +371,37 @@ public:
     TS_ASSERT_DELTA(point[1], 1.0, eps);
     TS_ASSERT_DELTA(point[2], 0.75592895, eps);
     // See if the basis vectors are available
-    float *xBasis = getRangeComp(ds, "AxisBaseForX", 3);
-    TS_ASSERT_DELTA(xBasis[0], 1.0, eps);
-    TS_ASSERT_DELTA(xBasis[1], 0.0, eps);
-    TS_ASSERT_DELTA(xBasis[2], 0.0, eps);
-    delete [] xBasis;
-    float *yBasis = getRangeComp(ds, "AxisBaseForY", 3);
-    TS_ASSERT_DELTA(yBasis[0], 0.0, eps);
-    TS_ASSERT_DELTA(yBasis[1], 1.0, eps);
-    TS_ASSERT_DELTA(yBasis[2], 0.0, eps);
-    delete [] yBasis;
-    float *zBasis = getRangeComp(ds, "AxisBaseForZ", 3);
-    TS_ASSERT_DELTA(zBasis[0], -0.65465367, eps);
-    TS_ASSERT_DELTA(zBasis[1], 0.0, eps);
-    TS_ASSERT_DELTA(zBasis[2], 0.75592895, eps);
-    delete [] zBasis;
+    double *basisMatrix = getRangeComp<double>(ds, "ChangeOfBasisMatrix", 16);
+
+    // Row by row check
+
+    // basisX[0], basisY[0], basisZ[0], 0
+    int index = 0;
+    TS_ASSERT_DELTA(basisMatrix[index++], 1.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], -0.65465367, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+
+    // basisX[1], basisY[1], basisZ[1], 0
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 1.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+
+    // basisX[2], basisY[2], basisZ[2], 0
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.75592895, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+
+    //0, 0, 0, 1
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
+    TS_ASSERT_DELTA(basisMatrix[index++], 1.0, eps);
+
+    delete basisMatrix;
+  
     ds->Delete();
   }
 };
diff --git a/Code/Mantid/Vates/VatesAPI/test/vtkMD0DFactoryTest.h b/Code/Mantid/Vates/VatesAPI/test/vtkMD0DFactoryTest.h
new file mode 100644
index 0000000000000000000000000000000000000000..3d8c9fd971019bb9684d68915fbc7aac5b6dc37e
--- /dev/null
+++ b/Code/Mantid/Vates/VatesAPI/test/vtkMD0DFactoryTest.h
@@ -0,0 +1,43 @@
+#ifndef VTK_MD_0D_FACTORY_TEST
+#define VTK_MD_0D_FACTORY_TEST
+#include <cxxtest/TestSuite.h>
+
+#include "MantidVatesAPI/vtkMD0DFactory.h"
+#include "MantidTestHelpers/MDEventsTestHelper.h"
+#include "MantidVatesAPI/UserDefinedThresholdRange.h"
+#include "MantidVatesAPI/NoThresholdRange.h"
+
+#include "MockObjects.h"
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+#include "MantidVatesAPI/vtkStructuredGrid_Silent.h"
+
+using namespace Mantid;
+using namespace Mantid::VATES;
+using namespace Mantid::API;
+using namespace Mantid::DataObjects;
+using namespace testing;
+
+
+class vtkMD0DFactoryTest : public CxxTest::TestSuite
+{
+public:
+
+  void testCreatesA0DDataSet()
+  {
+    // Arrange
+    FakeProgressAction progressUpdater;
+    vtkMD0DFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), "signal");
+
+    vtkDataSet* dataSet = NULL;
+
+    // Assert
+    TSM_ASSERT_THROWS_NOTHING("0D factory should create data set without exceptions", dataSet  = factory.create(progressUpdater));
+    TSM_ASSERT("Should have exactly one point", dataSet->GetNumberOfPoints() == 1);
+    TSM_ASSERT("Should have exactly one cell", dataSet->GetNumberOfCells() == 1);
+  }
+};
+
+
+#endif
diff --git a/Code/Mantid/Vates/VatesAPI/test/vtkMDHistoHexFactoryTest.h b/Code/Mantid/Vates/VatesAPI/test/vtkMDHistoHexFactoryTest.h
index cc152f7608b150ab119ff23cc2170729c409f6d6..0d7c346393895ed165bdf351987ec16ca2ddaecd 100644
--- a/Code/Mantid/Vates/VatesAPI/test/vtkMDHistoHexFactoryTest.h
+++ b/Code/Mantid/Vates/VatesAPI/test/vtkMDHistoHexFactoryTest.h
@@ -11,6 +11,7 @@
 #include <gmock/gmock.h>
 #include <gtest/gtest.h>
 #include "MantidVatesAPI/vtkStructuredGrid_Silent.h"
+#include "vtkUnstructuredGrid.h"
 
 using namespace Mantid;
 using namespace Mantid::API;
diff --git a/Code/Mantid/Vates/VatesSimpleGui/QtWidgets/CMakeLists.txt b/Code/Mantid/Vates/VatesSimpleGui/QtWidgets/CMakeLists.txt
index 9d3d7a37cd7243e039bf96eede987a6e1d7e1127..b9816a96ac0bced3aeba17e4bd33d2f41c9671d9 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/QtWidgets/CMakeLists.txt
+++ b/Code/Mantid/Vates/VatesSimpleGui/QtWidgets/CMakeLists.txt
@@ -65,4 +65,8 @@ ${MANTID_SUBPROJECT_LIBS}
 MantidQtAPI
 )
 
+if (OSX_VERSION VERSION_GREATER 10.8)
+  set_target_properties ( VatesSimpleGuiQtWidgets PROPERTIES INSTALL_RPATH "@loader_path/../Contents/Libraries;@loader_path/../Contents/MacOS")
+endif ()
+
 install( TARGETS VatesSimpleGuiQtWidgets ${SYSTEM_PACKAGE_TARGET} DESTINATION ${PVPLUGINS_DIR} )
diff --git a/Code/Mantid/Vates/VatesSimpleGui/QtWidgets/src/ModeControlWidget.cpp b/Code/Mantid/Vates/VatesSimpleGui/QtWidgets/src/ModeControlWidget.cpp
index 24494dd8077eddd30fee19dd184f91648b35e119..fb3a1631a6b388fd60192c02406f3ebca06bc880 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/QtWidgets/src/ModeControlWidget.cpp
+++ b/Code/Mantid/Vates/VatesSimpleGui/QtWidgets/src/ModeControlWidget.cpp
@@ -79,7 +79,7 @@ void ModeControlWidget::enableViewButtons(ModeControlWidget::Views initialView,
     break;
 
     default:
-      g_log.warning() << "Attempted to disable an unknown default view. \n";
+      g_log.warning("Attempted to disable an unknown default view. \n");
       break;
   }
 }
@@ -203,7 +203,7 @@ ModeControlWidget::Views ModeControlWidget::getViewFromString(QString view)
   else 
   {
     // The view was not found, hence return the standard view
-    g_log.warning() << "The specified default view could not be found! \n";
+    g_log.warning("The specified default view could not be found! \n");
 
     return ModeControlWidget::STANDARD;
   }
diff --git a/Code/Mantid/Vates/VatesSimpleGui/StandAloneExec/CMakeLists.txt b/Code/Mantid/Vates/VatesSimpleGui/StandAloneExec/CMakeLists.txt
index bcb80bf44f188c723e56314f298d862aaa9a404f..3e243f49870b3ac064d2a0abc3668edc44645ff9 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/StandAloneExec/CMakeLists.txt
+++ b/Code/Mantid/Vates/VatesSimpleGui/StandAloneExec/CMakeLists.txt
@@ -48,6 +48,10 @@ VatesSimpleGuiQtWidgets
 VatesSimpleGuiViewWidgets
 )
 
+if (OSX_VERSION VERSION_GREATER 10.8)
+  set_target_properties ( ${PROJECT_NAME} PROPERTIES INSTALL_RPATH "@loader_path/../Libraries;@loader_path/../MacOS")
+endif ()
+
 if( SQUISH_FOUND )
   # Need to set the AUT first
   set( SQUISH_AUT VatesSimpleGui )
diff --git a/Code/Mantid/Vates/VatesSimpleGui/StandAloneExec/src/SimpleGuiApp.cpp b/Code/Mantid/Vates/VatesSimpleGui/StandAloneExec/src/SimpleGuiApp.cpp
index 4e456176744a4265748a97005b87930130add703..93c1e5d511cfc6a3aa2588f3d69f8d390b8068c4 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/StandAloneExec/src/SimpleGuiApp.cpp
+++ b/Code/Mantid/Vates/VatesSimpleGui/StandAloneExec/src/SimpleGuiApp.cpp
@@ -7,6 +7,7 @@
 #include <QPushButton>
 
 #include <exception>
+#include <iostream>
 
 namespace
 {
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/CMakeLists.txt b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/CMakeLists.txt
index 98fb3b2fe5843f2f5051296c6f2b5bd42cb2cf2e..6094dcb99a3bb4ee8908f43b303447696d898d82 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/CMakeLists.txt
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/CMakeLists.txt
@@ -11,6 +11,7 @@ set( INCLUDE_FILES
   inc/MantidVatesSimpleGuiViewWidgets/LibHelper.h
   inc/MantidVatesSimpleGuiViewWidgets/MdViewerWidget.h
   inc/MantidVatesSimpleGuiViewWidgets/MultisliceView.h
+  inc/MantidVatesSimpleGuiViewWidgets/VatesParaViewApplication.h
   inc/MantidVatesSimpleGuiViewWidgets/RebinAlgorithmDialogProvider.h
   inc/MantidVatesSimpleGuiViewWidgets/PeaksTableControllerVsi.h
   inc/MantidVatesSimpleGuiViewWidgets/PeaksWidget.h
@@ -44,6 +45,7 @@ set( SOURCE_FILES
   src/SplatterPlotView.cpp
   src/ThreesliceView.cpp
   src/TimeControlWidget.cpp
+  src/VatesParaViewApplication.cpp
   src/ViewBase.cpp
 )
 
@@ -66,6 +68,7 @@ qt4_wrap_cpp( MOC_SOURCES
   inc/MantidVatesSimpleGuiViewWidgets/SplatterPlotView.h
   inc/MantidVatesSimpleGuiViewWidgets/ThreesliceView.h
   inc/MantidVatesSimpleGuiViewWidgets/TimeControlWidget.h
+  inc/MantidVatesSimpleGuiViewWidgets/VatesParaViewApplication.h
   inc/MantidVatesSimpleGuiViewWidgets/ViewBase.h
 )
 
@@ -97,7 +100,9 @@ include_directories(
   ${CMAKE_SOURCE_DIR}/MantidQt/Factory/inc
   ${CMAKE_CURRENT_BINARY_DIR}
   ${CMAKE_CURRENT_BINARY_DIR}/../QtWidgets
+  ${CMAKE_SOURCE_DIR}/MantidPlot/src
   ${QWT_INCLUDE_DIR}
+  ${PYTHON_INCLUDE_PATH}
 )
 
 set( ALL_FILES
@@ -128,6 +133,10 @@ include_directories( SYSTEM ${PARAVIEW_INCLUDE_DIRS} )
 target_link_libraries( VatesSimpleGuiViewWidgets
 pqApplicationComponents
 pqComponents
+vtkPVServerManagerRendering
+vtkRenderingFreeType
+vtkRenderingFreeTypeOpenGL
+vtksys
 ${QT_LIBRARIES}
 VatesSimpleGuiQtWidgets
 MantidQtAPI
@@ -135,12 +144,17 @@ VatesAPI
 ${MANTID_SUBPROJECT_LIBS}
 MantidQtSliceViewer
 MantidQtFactory
+${PYTHON_LIBRARIES}
 MantidWidgets
 )
 
+if (OSX_VERSION VERSION_GREATER 10.8)
+  set_target_properties ( VatesSimpleGuiViewWidgets PROPERTIES INSTALL_RPATH "@loader_path/../Contents/MacOS;@loader_path/../Contents/Libraries")
+endif ()
+
 # Create test file projects
 if( CXXTEST_FOUND AND GMOCK_FOUND AND GTEST_FOUND )
-  include_directories ( SYSTEM ${CXXTEST_INCLUDE_DIR} ${GMOCK_INCLUDE_DIR} ${GTEST_INCLUDE_DIR} )
+  include_directories ( SYSTEM ${CXXTEST_INCLUDE_DIR} ${GMOCK_INCLUDE_DIR} ${GTEST_INCLUDE_DIR})
 
   include_directories( inc ../../../Framework/TestHelpers/inc ../../../Framework/DataHandling/inc ../../../Framework/DataObjects/inc)
   set ( TESTHELPER_SRCS ../../../Framework/TestHelpers/src/ComponentCreationHelper.cpp 
@@ -148,7 +162,7 @@ if( CXXTEST_FOUND AND GMOCK_FOUND AND GTEST_FOUND )
                         ../../../Framework/TestHelpers/src/MDEventsTestHelper.cpp 
                         ../../../Framework/TestHelpers/src/StartFrameworkManager.cpp )
   cxxtest_add_test( VatesSimpleGuiViewWidgetsTest ${TEST_FILES} )
-  target_link_libraries( VatesSimpleGuiViewWidgetsTest VatesSimpleGuiViewWidgets DataHandling Kernel DataObjects ${GMOCK_LIBRARIES} ${GTEST_LIBRARIES} )
+  target_link_libraries( VatesSimpleGuiViewWidgetsTest VatesSimpleGuiViewWidgets DataHandling Kernel DataObjects ${GMOCK_LIBRARIES} ${GTEST_LIBRARIES})
   add_dependencies( AllTests VatesSimpleGuiViewWidgetsTest )
   # Add to the 'UnitTests' group in VS
   set_property ( TARGET VatesSimpleGuiViewWidgetsTest PROPERTY FOLDER "UnitTests" )
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/BackgroundRgbProvider.h b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/BackgroundRgbProvider.h
index 7322c63e0029f3881ec3b5c47bdd99e260f4890b..57a4bc2791fffdf560eb7c92f71e7f7a75a2f469 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/BackgroundRgbProvider.h
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/BackgroundRgbProvider.h
@@ -61,10 +61,10 @@ namespace Mantid
 
           /**
            * Set the Rgb values for the color of the view's background.
-           * @param viewSwitched Is this the initial loading or were the views switched?
+           * @param useCurrentBackgroundColor Is this the initial loading or were the views switched?
            * @param view The view which has its background color set.
            */
-          void setBackgroundColor(pqRenderView* view, bool viewSwitched);
+          void setBackgroundColor(pqRenderView* view, bool useCurrentBackgroundColor);
 
           /**
            * Listen to a change in the background color
@@ -80,26 +80,23 @@ namespace Mantid
        private:
           /**
           * Get the Rgb values for the color of the view's background from the user setting.
-          * @param viewSwitched Is this the initial loading or were the views switched?
+          * @param useCurrentBackgroundColor Is this the initial loading or were the views switched?
           * @returns A vector with the RGB values
           */
-          std::vector<double> getRgbFromSetting(bool viewSwitched);
+          std::vector<double> getRgbFromSetting(bool useCurrentBackgroundColor);
 
           /**
            * Get the Rgb values for the color of the view's background
-           * @param viewSwitched Is this the initial loading or were the views switched?
+           * @param useCurrentBackgroundColor Is this the initial loading or were the views switched?
            * @returns A vector with the RGB values
            */
-          std::vector<double> getRgb(bool viewSwitched);
+          std::vector<double> getRgb(bool useCurrentBackgroundColor);
 
           /**
            * Callback function for background color changing events
            *@param caller Calling object.
-           *@param eventId Not used.
-           *@param clientData Not used.
-           *@param callData Not used.
            */
-          static void backgroundColorChangeCallbackFunction(vtkObject* caller, long unsigned int vtkNotUsed(eventId), void* vtkNotUsed(clientData), void* vtkNotUsed(callData));
+          static void backgroundColorChangeCallbackFunction(vtkObject* caller, long unsigned int, void*, void*);
 
           static QColor currentBackgroundColor;
 
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/CameraManager.h b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/CameraManager.h
index 9f0c5f9cdba1f3738e983b1ec7b3e91e874db78e..8b2aa618458c0691ca56bb15cf6eff3096751108 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/CameraManager.h
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/CameraManager.h
@@ -4,6 +4,7 @@
 #include "MantidVatesSimpleGuiViewWidgets/WidgetDllOption.h"
 #include "MantidVatesAPI/ViewFrustum.h"
 
+
 namespace Mantid
 {
 namespace Vates
@@ -45,7 +46,7 @@ public:
 
   ~CameraManager();
   
-  Mantid::VATES::ViewFrustum getCurrentViewFrustum();
+  Mantid::VATES::ViewFrustum_const_sptr getCurrentViewFrustum();
 
   void setCameraToPeak(double xpos, double ypos, double zpos, double peakRadius);
 };
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ColorMapManager.h b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ColorMapManager.h
index ac9824a7e7644293952181736e2f8d19a1d2ea1b..7cd2b3b441a1a1fde84c038f851c0faa6be94345 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ColorMapManager.h
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ColorMapManager.h
@@ -49,10 +49,10 @@ namespace Mantid
           
           /**
            * Get default color map
-           * @param viewSwitched If the view has switched or not.
+           * @param useCurrentColorMap If we should use the current color map.
            * @returns index The index of the default color map in the list of color maps.
            */
-          int getDefaultColorMapIndex(bool viewSwitched);
+          int getDefaultColorMapIndex(bool useCurrentColorMap);
 
           /**
            * Read in and store the available color maps
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/LibHelper.h.in b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/LibHelper.h.in
index ec05e10878cd95bedff5ea92a589eaa0e5a9287b..db63b291206ac399eb8310bdcb2ab62118fcd7be 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/LibHelper.h.in
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/LibHelper.h.in
@@ -10,8 +10,6 @@ namespace Vates
 namespace SimpleGui
 {
 
-const QString QUADVIEW_LIBRARY("@CMAKE_SHARED_LIBRARY_PREFIX@QuadView@CMAKE_SHARED_LIBRARY_SUFFIX@");
-
 } // namespace SimpleGui
 } // namespace Vates
 } // namespace Mantid
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/MdViewerWidget.h b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/MdViewerWidget.h
index fcd8880ecfd02421d393af3a07effee553fef3bc..5c80e631d4e9bfeb451589fbac94cf025d1c229d 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/MdViewerWidget.h
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/MdViewerWidget.h
@@ -17,9 +17,9 @@
 #include <QWidget>
 #include <QString>
 
+class pqApplicationSettingsReaction;
 class pqLoadDataReaction;
 class pqPipelineSource;
-class pqViewSettingsReaction;
 class vtkSMDoubleVectorProperty;
 
 class QDragEnterEvent;
@@ -110,13 +110,14 @@ protected slots:
   void renderingDone();
   /// Execute view switch.
   void switchViews(ModeControlWidget::Views v);
+  /// Triggered when panel is changed.
+  void panelChanged();
   /// On rebin 
   void onRebin(std::string algorithmType);
   /// On  unbin
   void onUnbin();
   /// On switching an MDEvent source to a temporary source.
   void onSwitchSoures(std::string rebinnedWorkspaceName, std::string sourceType);
-
 protected:
   /// Handle workspace preDeletion tasks.
   void preDeleteHandle(const std::string &wsName,
@@ -130,11 +131,10 @@ protected:
  void dropEvent(QDropEvent *e);
 private:
   Q_DISABLE_COPY(MdViewerWidget)
-
+  QString m_widgetName;
   ViewBase *currentView; ///< Holder for the current view
   pqLoadDataReaction *dataLoader; ///< Holder for the load data reaction
   ViewBase *hiddenView; ///< Holder for the view that is being switched from
-  bool isPluginInitialized; ///< Flag for plugin initialization
   double lodThreshold; ///< Default value for the LOD threshold (5 MB)
   QAction *lodAction; ///< Holder for the LOD threshold menu item
   bool pluginMode; ///< Flag to say widget is in plugin mode
@@ -142,8 +142,9 @@ private:
   SaveScreenshotReaction *screenShot; ///< Holder for the screen shot reaction
   Ui::MdViewerWidgetClass ui; ///< The MD viewer's UI form
   QHBoxLayout *viewLayout; ///< Layout manager for the view widget
-  pqViewSettingsReaction *viewSettings; ///< Holder for the view settings reaction
+  pqApplicationSettingsReaction *viewSettings; ///< Holder for the view settings reaction
   bool viewSwitched;
+  bool useCurrentColorSettings;
   ModeControlWidget::Views initialView; ///< Holds the initial view
   MantidQt::API::MdSettings mdSettings;///<Holds the MD settings which are used to persist data
   MantidQt::API::MdConstants mdConstants;/// < Holds the MD constants
@@ -151,32 +152,24 @@ private:
   RebinnedSourcesManager m_rebinnedSourcesManager; ///<Holds the rebinned sources manager
   QString m_rebinnedWorkspaceIdentifier; ///< Holds the identifier for temporary workspaces
 
-  /// Check the environmental variables.
-  void checkEnvSetup();
   /// Setup color selection widget connections.
   void connectColorSelectionWidget();
   /// Setup connections for all dialogs.
   void connectDialogs();
   /// Setup rotation point dialog connections.
   void connectRotationPointDialog();
-  /// Create the pqPVApplicationCore object in plugin mode.
-  void createAppCoreForPlugin();
   /// Add view specific stuff to a menu.
   void createMenus();
   /// Disconnect dialog connections.
   void disconnectDialogs();
   /// Consolidate constructor related items.
   void internalSetup(bool pMode);
-  /// Disable communication with the proxy tab widget.
-  void removeProxyTabWidgetConnections();
   /// Perform first render and final setup for mode buttons.
   void renderAndFinalSetup();
   /// Set the signals/slots for the ParaView components based on the view.
   void setParaViewComponentsForView();
   /// Run the necessary setup for the main view.
   void setupMainView();
-  /// Mimic ParaView behavior setup without QMainWindow.
-  void setupParaViewBehaviors();
   /// Creates the UI and mode switch connection.
   void setupUiAndConnections();
   /// Create the requested view.
@@ -198,15 +191,15 @@ private:
   /// Reset the current view to the appropriate initial view.
   void resetCurrentView(int workspaceType, const std::string& instrumentName);
   /// Render rebinned workspace
-  void prepareRebinnedWorkspace(const std::string rebinnedWorkspaceName, std::string sourceType); 
+  pqPipelineSource* prepareRebinnedWorkspace(const std::string rebinnedWorkspaceName, std::string sourceType); 
   /// Handle drag and drop of peaks workspcaes
   void handleDragAndDropPeaksWorkspaces(QEvent* e, QString text, QStringList& wsNames);
   /// Set up the default color for the background of the view.
   void setColorForBackground();
+  /// Set the color map 
+  void setColorMap();
   /// Render the original workspace
-  void renderOriginalWorkspace(const std::string originalWorkspaceName);
-  /// Delete a specific workspace
-  void deleteSpecificSource(std::string workspaceName);
+  pqPipelineSource* renderOriginalWorkspace(const std::string originalWorkspaceName);
   /// Remove the rebinning when switching views or otherwise.
   void removeRebinning(pqPipelineSource* source, bool forced, ModeControlWidget::Views view = ModeControlWidget::STANDARD);
   /// Remove all rebinned sources
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/MdViewerWidget.ui b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/MdViewerWidget.ui
index 7198a510525a1e32566398a977b540f2c0b53c5f..c4e62505498f5e137f902c2fa6b86b4f53b94e59 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/MdViewerWidget.ui
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/MdViewerWidget.ui
@@ -6,7 +6,7 @@
    <rect>
     <x>0</x>
     <y>0</y>
-    <width>1057</width>
+    <width>1361</width>
     <height>710</height>
    </rect>
   </property>
@@ -167,14 +167,24 @@
     </layout>
    </item>
    <item>
-    <widget class="QSplitter" name="splitter_2">
+    <widget class="QSplitter" name="splitter_3">
      <property name="orientation">
       <enum>Qt::Horizontal</enum>
      </property>
-     <widget class="QSplitter" name="splitter">
+     <property name="handleWidth">
+      <number>3</number>
+     </property>
+     <widget class="QSplitter" name="splitter_2">
       <property name="orientation">
-       <enum>Qt::Vertical</enum>
+       <enum>Qt::Horizontal</enum>
+      </property>
+      <property name="handleWidth">
+       <number>3</number>
       </property>
+      <widget class="QSplitter" name="splitter">
+       <property name="orientation">
+        <enum>Qt::Vertical</enum>
+       </property>
       <widget class="pqPipelineBrowserWidget" name="pipelineBrowser" native="true">
        <property name="minimumSize">
         <size>
@@ -187,54 +197,68 @@
        <property name="currentIndex">
         <number>0</number>
        </property>
-       <widget class="QWidget" name="properties">
-        <attribute name="title">
-         <string>Properties</string>
-        </attribute>
-        <layout class="QVBoxLayout" name="verticalLayout_3">
-         <item>
-          <widget class="pqPropertiesPanel" name="propertiesPanel" native="true"/>
-         </item>
-        </layout>
-       </widget>
-       <widget class="QWidget" name="information">
-        <attribute name="title">
-         <string>Information</string>
-        </attribute>
-        <layout class="QVBoxLayout" name="verticalLayout_2">
-         <item>
-          <widget class="QScrollArea" name="scrollArea">
-           <property name="widgetResizable">
-            <bool>true</bool>
-           </property>
-           <widget class="QWidget" name="scrollAreaWidgetContents">
-            <property name="geometry">
-             <rect>
-              <x>0</x>
-              <y>0</y>
-              <width>274</width>
-              <height>370</height>
-             </rect>
+        <widget class="QWidget" name="properties">
+         <attribute name="title">
+          <string>Properties</string>
+         </attribute>
+         <layout class="QVBoxLayout" name="verticalLayout_31">
+          <item>
+           <widget class="pqPropertiesPanel" name="propertiesPanel" native="true"/>
+          </item>
+         </layout>
+        </widget>
+        <widget class="QWidget" name="information">
+         <attribute name="title">
+          <string>Information</string>
+         </attribute>
+         <layout class="QVBoxLayout" name="verticalLayout_2">
+          <item>
+           <widget class="QScrollArea" name="scrollArea">
+            <property name="widgetResizable">
+             <bool>true</bool>
             </property>
-            <layout class="QVBoxLayout" name="verticalLayout">
-             <item>
-              <widget class="pqProxyInformationWidget" name="proxyInfo" native="true"/>
-             </item>
-            </layout>
+            <widget class="QWidget" name="scrollAreaWidgetContents">
+             <property name="geometry">
+              <rect>
+               <x>0</x>
+               <y>0</y>
+               <width>105</width>
+               <height>387</height>
+              </rect>
+             </property>
+             <layout class="QVBoxLayout" name="verticalLayout">
+              <item>
+               <widget class="pqProxyInformationWidget" name="proxyInfo" native="true"/>
+              </item>
+             </layout>
+            </widget>
            </widget>
-          </widget>
-         </item>
-        </layout>
+          </item>
+         </layout>
+        </widget>
        </widget>
       </widget>
+      <widget class="QWidget" name="viewWidget" native="true">
+       <property name="minimumSize">
+        <size>
+         <width>800</width>
+         <height>600</height>
+        </size>
+       </property>
+      </widget>
      </widget>
-     <widget class="QWidget" name="viewWidget" native="true">
-      <property name="minimumSize">
-       <size>
-        <width>600</width>
-        <height>600</height>
-       </size>
+     <widget class="QDockWidget" name="colorMapEditorDock">
+      <property name="windowTitle">
+       <string>Color Map Editor</string>
       </property>
+      <widget class="pqColorMapEditor" name="colorMapEditorPanel">
+       <property name="minimumSize">
+        <size>
+         <width>400</width>
+         <height>0</height>
+        </size>
+       </property>
+      </widget>
      </widget>
     </widget>
    </item>
@@ -305,6 +329,17 @@
    <header>pqAxesToolbar.h</header>
    <container>1</container>
   </customwidget>
+  <customwidget>
+   <class>pqColorMapEditor</class>
+   <extends>QWidget</extends>
+   <header>pqColorMapEditor.h</header>
+   <container>1</container>
+  </customwidget>
+  <customwidget>
+   <class>pqProxiesWidget</class>
+   <extends>QWidget</extends>
+   <header>pqProxiesWidget.h</header>
+  </customwidget>
  </customwidgets>
  <resources>
   <include location="../../icons/ViewWidgetsIcons.qrc"/>
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/MultisliceView.h b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/MultisliceView.h
index 953d3dcc6e78d5d8806ecd638d628fc3a46db02b..6b7ad2cb5fd53ab5b2f66dc6f2405952519a4a51 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/MultisliceView.h
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/MultisliceView.h
@@ -1,6 +1,7 @@
 #ifndef MULTISLICEVIEW_H_
 #define MULTISLICEVIEW_H_
 
+#include "MantidKernel/VMD.h"
 #include "ui_MultisliceView.h"
 #include "MantidVatesSimpleGuiViewWidgets/ViewBase.h"
 #include "MantidVatesSimpleGuiViewWidgets/WidgetDllOption.h"
@@ -16,6 +17,8 @@ namespace Vates
 {
 namespace SimpleGui
 {
+
+  class RebinnedSourcesManager;
 /**
  *
   This class uses the MultiSliceView created by Kitware based on our
@@ -51,8 +54,9 @@ public:
   /**
    * Default constructor.
    * @param parent the parent widget of the multislice view widget
+   * @param rebinnedSourcesManager Pointer to a RebinnedSourcesManager
    */
-  MultiSliceView(QWidget *parent = 0);
+  MultiSliceView(QWidget *parent = 0, RebinnedSourcesManager* rebinnedSourcesManager = 0);
   /// Default constructor.
   virtual ~MultiSliceView();
 
@@ -87,6 +91,9 @@ protected slots:
                          int button, int modifier);
   /// Launch SliceViewer with the specified cut.
   void showCutInSliceViewer(int axisIndex, double sliceOffsetOnAxis);
+  
+  //// changes the slice point in VATES.
+  void changedSlicePoint(Mantid::Kernel::VMD selectedPoint);
 
 private:
   Q_DISABLE_COPY(MultiSliceView)
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/PeaksTableControllerVsi.h b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/PeaksTableControllerVsi.h
index 18dfc9c661858e32b498249faac1ed241fafb92e..063c54093e1ef2465691b5b3d7888b517fda68af 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/PeaksTableControllerVsi.h
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/PeaksTableControllerVsi.h
@@ -61,6 +61,7 @@ private:
   void removeLayout(QWidget *widget);
   void createTable();
   void updatePeakWorkspaceColor();
+  void setPeakSourceColorToDefault();
   std::map<std::string, QColor> getColors();
   MantidQt::SliceViewer::PeakPalette m_peakPalette;
   boost::shared_ptr<CameraManager> m_cameraManager;
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/RebinAlgorithmDialogProvider.h b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/RebinAlgorithmDialogProvider.h
index 5d9768accfc6281d740abda37520e9fa7f585b0c..7a98cdc0b49af4dab89723010d457cc9a0f24df6 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/RebinAlgorithmDialogProvider.h
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/RebinAlgorithmDialogProvider.h
@@ -51,22 +51,21 @@ namespace Mantid
 
           void showDialog(std::string inputWorkspace, std::string outputWorkspace, std::string algorithmType);
 
-        private:
-          MantidQt::API::AlgorithmDialog* createDialog(Mantid::API::IAlgorithm_sptr algorithm, std::string inputWorkspace, std::string outputWorkspace, std::string algorithmType);
+           static const size_t BinCutOffValue;
 
-          void getPresetsForSliceMDAlgorithmDialog( std::string inputWorkspace, std::string outputWorkspace, QHash<QString, QString>& presets);
+        private:
+          MantidQt::API::AlgorithmDialog* createDialog(Mantid::API::IAlgorithm_sptr algorithm, const std::string& inputWorkspace, const std::string& outputWorkspace, const std::string& algorithmType);
 
           void setAxisDimensions(MantidQt::MantidWidgets::SlicingAlgorithmDialog* dialog,  std::string inputWorkspace);
 
-          Mantid::API::IMDEventWorkspace_sptr getWorkspace(std::string workspaceName);
+          Mantid::API::IMDEventWorkspace_sptr getWorkspace(const std::string& workspaceName);
 
           Mantid::API::IAlgorithm_sptr createAlgorithm(const std::string& algName, int version);
 
           Mantid::VATES::ADSWorkspaceProvider<Mantid::API::IMDEventWorkspace> m_adsWorkspaceProvider;
 
-          QString m_lblInputWorkspace;
-          QString m_lblOutputWorkspace;
-          size_t m_binCutOffValue;
+          const QString m_lblInputWorkspace;
+          const QString m_lblOutputWorkspace;
           QWidget* m_parent;
       };
 
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/RebinnedSourcesManager.h b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/RebinnedSourcesManager.h
index 039006502c62e0f64acf8b6e882232f1ac0e65d9..0edcc52ad1cdbabf8a772c761fb0160c7b4f5760 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/RebinnedSourcesManager.h
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/RebinnedSourcesManager.h
@@ -19,6 +19,7 @@
 #endif
 
 #include <QWidget>
+#include <QList>
 #include <map>
 #include <string>
 
@@ -65,15 +66,15 @@ namespace Mantid
 
           void checkSource(pqPipelineSource* source, std::string& inputWorkspace, std::string& outputWorkspace,  std::string algorithmType);
 
-          void repipeRebinnedSource(std::string rebinnedSource, std::string& sourceToBeDeleted);
+          void repipeRebinnedSource();
 
-          void repipeOriginalSource(std::string rebinnedSource, std::string originalSource);
+          void repipeOriginalSource(pqPipelineSource* rebinnedSource, pqPipelineSource* originalSource);
 
           void getStoredWorkspaceNames(pqPipelineSource* source, std::string& originalWorkspaceName, std::string& rebinnedWorkspaceName);
 
           void registerRebinnedSource(pqPipelineSource* source);
 
-          bool isRebinnedSource(std::string name);
+          bool isRebinnedSourceBeingTracked(pqPipelineSource* source);
 
         signals:
           void switchSources(std::string rebinnedWorkspaceName,  std::string sourceType);
@@ -84,41 +85,51 @@ namespace Mantid
 
           void preDeleteHandle(const std::string &wsName, const boost::shared_ptr<Mantid::API::Workspace> );
 
+          void afterReplaceHandle(const std::string &workspaceName, const boost::shared_ptr<Mantid::API::Workspace> workspace);
+
         private slots:
           void onRebinnedSourceDestroyed();
 
         private:
-          std::map<std::string, std::string> m_originalWorkspaceToRebinnedWorkspace; ///< Holds the mapping from the original source to the rebinned source
-
-          std::map<std::string, std::string> m_rebinnedWorkspaceToOriginalWorkspace; ///< Holds the mapping from the rebinned source to the original source
-
-          std::map<std::string, std::string> m_rebinnedWorkspaceToRebinnedWorkspace; ///< Holds information from a rebinned source to another temproary source which replaces it.
+          std::map<std::pair<std::string, std::string>, std::string> m_rebinnedWorkspaceAndSourceToOriginalWorkspace; ///< Holds a mapping from (RebinnedWsName, RebinnedSourceName unique ID) to (OriginalWsName)
+          std::map<std::string, std::pair<std::string, pqPipelineSource*>>  m_newWorkspacePairBuffer; ///< Holds information for the name of a new, rebinned workspace vs an original workspace and source
+          std::map<std::string, std::pair<std::string, pqPipelineSource*>>  m_newRebinnedWorkspacePairBuffer; ///< Holds information for the name of a new, rebinned workspace vs an old rebinned workspace and source
 
           std::string m_tempPostfix;
 
           std::string m_tempPrefix;
 
-          pqPipelineSource* getSourceForWorkspace(std::string workspaceName);
+          pqPipelineSource* m_inputSource;
 
-          void swapSources(std::string source1, std::string source2);
+          pqPipelineSource* m_rebinnedSource;
 
-          void rebuildPipeline(pqPipelineSource* source1, pqPipelineSource* source2);
-
-          void processWorkspaceNames(std::string& inputWorkspace, std::string& outputWorkspace, std::string workspaceName, std::string algorithmType);
+          std::vector<pqPipelineSource*> findAllRebinnedSourcesForWorkspace(std::string workspaceName);
 
-          void removeUnusedRebinnedWorkspaces();
+          void swapSources(pqPipelineSource* source1, pqPipelineSource* source2);
 
-          void untrackWorkspaces(std::string rebinnedSource);
+          void rebuildPipeline(pqPipelineSource* source1, pqPipelineSource* source2);
 
-          void removeRebinnedWorkspace(std::string rebinnedWorkspace);
+          void processWorkspaceNames(std::string& inputWorkspace, std::string& outputWorkspace, pqPipelineSource* source, std::string workspaceName, std::string algorithmType);
 
-          void compareToSources(std::string workspaceName);
+          void untrackWorkspaces(std::pair<std::string, std::string> key);
 
           void copyProperties(pqPipelineFilter* filter1, pqPipelineFilter* filter2);
 
           static void copySafe(vtkSMProxy* dest, vtkSMProxy* source);
 
           void getWorkspaceInfo(pqPipelineSource* source, std::string& workspaceName, std::string& workSpaceType);
+
+          void removePipeline(pqPipelineSource* source);
+
+          void deleteSpecificSource(pqPipelineSource* source);
+
+          std::string getSourceName(pqPipelineSource* source);
+
+          std::pair<std::string, std::string> createKeyPairForSource(pqPipelineSource* source);
+
+          pqPipelineSource* goToPipelineBeginning(pqPipelineSource* source);
+
+          bool doesSourceNeedToBeDeleted(std::string sourceName, std::vector<std::string> trackedSources);
       };
 
     } // SimpleGui
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/SplatterPlotView.h b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/SplatterPlotView.h
index 22312e91fa9e9ef8b2c5dc4db1e215db51e7a1e6..3f4c0c7297a4a7eb27d59005838b396f35948aee 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/SplatterPlotView.h
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/SplatterPlotView.h
@@ -25,6 +25,7 @@ namespace Vates
 {
 namespace SimpleGui
 {
+  class RebinnedSourcesManager;
 /**
  *
  This class creates a scatter plot using the SplatterPlot ParaView plugin. The
@@ -61,8 +62,9 @@ public:
   /**
    * Default constructor.
    * @param parent the parent widget for the threeslice view
+   * @param rebinnedSourcesManager Pointer to a RebinnedSourcesManager
    */
-  explicit SplatterPlotView(QWidget *parent = 0);
+  explicit SplatterPlotView(QWidget *parent = 0, RebinnedSourcesManager* rebinnedSourcesManager = 0);
   /// Default destructor
   virtual ~SplatterPlotView();
 
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/StandardView.h b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/StandardView.h
index 4dee0413a3c6797aef47595c0f78f483773af357..f9c0cab1046872969937666f143395fb266d1d0c 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/StandardView.h
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/StandardView.h
@@ -18,6 +18,8 @@ namespace Vates
 {
 namespace SimpleGui
 {
+
+  class RebinnedSourcesManager;
 /**
  *
  This class represents the initial view for the main program. It is meant to
@@ -51,7 +53,7 @@ class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS StandardView : public ViewBas
 
 public:
   /// Default constructor.
-  StandardView(QWidget *parent = 0);
+  StandardView(QWidget *parent = 0, RebinnedSourcesManager* rebinnedSourcesManager = 0);
   /// Default destructor.
   virtual ~StandardView();
 
@@ -75,8 +77,6 @@ public:
   void closeSubWindows();
 
 public slots:
-  /// React when the visibility of a representation changes
-  void onSourceDestroyed();
   /// Listen to a change in the active source.
   void activeSourceChangeListener(pqPipelineSource* source);
 
@@ -88,9 +88,7 @@ protected slots:
   /// Invoke the ScaleWorkspace on the current dataset.
   void onScaleButtonClicked();
   /// On BinMD button clicked
-  void onBinMD();
-  /// On SliceMD button clicked
-  void onSliceMD();
+  void onRebin();
 
 private:
   Q_DISABLE_COPY(StandardView)
@@ -104,9 +102,14 @@ private:
   void setRebinAndUnbinButtons();
   /// Set up the buttons
   void setupViewButtons();
+  ///  Give the user the ability to rebin
+  void allowRebinningOptions(bool allow);
+  ///  Allow the user the ability to unbin
+  void allowUnbinOption(bool allow);
 
   QAction* m_binMDAction;
   QAction* m_sliceMDAction;
+  QAction* m_cutMDAction;
   QAction* m_unbinAction;
 };
 
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ThreesliceView.h b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ThreesliceView.h
index 5757ac2fa938f99d2c71e4b400a337d359db9035..01abe1c6f54cb412c375cd0faeaa030966a5b1cd 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ThreesliceView.h
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ThreesliceView.h
@@ -16,6 +16,8 @@ namespace Vates
 {
 namespace SimpleGui
 {
+
+  class RebinnedSourcesManager;
 /**
  *
  This class creates four views of the given dataset. There are three 2D views
@@ -53,8 +55,9 @@ public:
   /**
    * Default constructor.
    * @param parent the parent widget for the threeslice view
+   * @param rebinnedSourcesManager Pointer to a RebinnedSourcesManager
    */
-  ThreeSliceView(QWidget *parent = 0);
+  ThreeSliceView(QWidget *parent = 0, RebinnedSourcesManager* rebinnedSourcesManager = 0);
   /// Default destructor.
   virtual ~ThreeSliceView();
 
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/VatesParaViewApplication.h b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/VatesParaViewApplication.h
new file mode 100644
index 0000000000000000000000000000000000000000..5bb39f268e3ec12ee6ecfce770156fbffebf116c
--- /dev/null
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/VatesParaViewApplication.h
@@ -0,0 +1,64 @@
+#ifndef VATESPARAVIEWAPPLICATION_H_
+#define VATESPARAVIEWAPPLICATION_H_
+
+#include "MantidVatesSimpleGuiViewWidgets/WidgetDllOption.h"
+#include "MantidKernel/Logger.h"
+
+#include <QObject>
+#include <QPointer>
+
+namespace Mantid
+{
+  namespace Vates
+  {
+    namespace SimpleGui
+    {
+      /**
+       *
+       This class creates four views of the given dataset. There are three 2D views
+       for the three orthogonal Cartesian planes and one 3D view of the dataset
+       showing the planes.
+
+       @author
+       @date
+
+       Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+
+       This file is part of Mantid.
+
+       Mantid is free software; you can redistribute it and/or modify
+       it under the terms of the GNU General Public License as published by
+       the Free Software Foundation; either version 3 of the License, or
+       (at your option) any later version.
+
+       Mantid 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 General Public License for more details.
+
+       You should have received a copy of the GNU General Public License
+       along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+       File change history is stored at: <https://github.com/mantidproject/mantid>
+       Code Documentation is available at: <http://doxygen.mantidproject.org>
+       */
+      class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS VatesParaViewApplication : public QObject
+      {
+        Q_OBJECT
+
+      public:
+        static VatesParaViewApplication* instance();
+        void setupParaViewBehaviors();
+      protected:
+        VatesParaViewApplication();
+        ~VatesParaViewApplication();
+      private:
+        Q_DISABLE_COPY(VatesParaViewApplication)
+        Mantid::Kernel::Logger m_logger;
+        bool m_behaviorsSetup;
+
+      };
+    } //SimpleGui
+  } //Vates
+} //Mantid
+#endif
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ViewBase.h b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ViewBase.h
index 93ce9a1c73b272875bf8a520b493c812a2b33027..50217be212b29fe7f1557b8c1f19b14380c016ab 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ViewBase.h
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ViewBase.h
@@ -27,6 +27,7 @@ namespace SimpleGui
 {
 
 class ColorSelectionWidget;
+class RebinnedSourcesManager;
 
 /**
  *
@@ -59,7 +60,8 @@ class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS ViewBase : public QWidget
   Q_OBJECT
 public:
   /// Default constructor.
-  ViewBase(QWidget *parent = 0);
+  ViewBase(QWidget *parent = 0, RebinnedSourcesManager* rebinnedSourcesManager = 0);
+
   /// Default destructor.
   virtual ~ViewBase() {}
 
@@ -73,7 +75,7 @@ public:
   virtual pqRenderView *createRenderView(QWidget *container,
                                          QString viewName=QString(""));
   /// Remove all filters of a given name: i.e. Slice.
-  virtual void destroyFilter(pqObjectBuilder *builder, const QString &name);
+  virtual void destroyFilter(const QString &name);
   /// Destroy sources and view relevant to mode switching.
   virtual void destroyView() = 0;
   /// Retrieve the current time step.
@@ -97,8 +99,8 @@ public:
   virtual bool hasWorkspaceType(const QString &wsTypeName);
   /// Check if file/workspace is a MDHistoWorkspace.
   virtual bool isMDHistoWorkspace(pqPipelineSource *src);
-  /// Check if file/workspace is a temporary workspace
-  virtual bool isTemporaryWorkspace(pqPipelineSource* src);
+  /// Check if file/workspace is an internally rebinned workspace
+  virtual bool isInternallyRebinnedWorkspace(pqPipelineSource* src);
   /// Check if file/workspace is a Peaks one.
   virtual bool isPeaksWorkspace(pqPipelineSource *src);
   /// Prints properties for given source.
@@ -118,7 +120,7 @@ public:
   /// Determines if source has timesteps (4D).
   virtual bool srcHasTimeSteps(pqPipelineSource *src);
   /// Set the the background color for the view
-  virtual void setColorForBackground(bool viewSwitched);
+  virtual void setColorForBackground(bool useCurrentColorSettings);
   /// Sets the splatterplot button to the desired visibility.
   virtual void setSplatterplot(bool visibility);
   /// Initializes the settings of the color scale 
@@ -219,7 +221,7 @@ signals:
    */
   void unbin();
   /**
-   * Singal to tell other elements that the log scale was altered programatically
+   * Signal to tell other elements that the log scale was altered programatically
    * @param state flag wheter or not to enable the 
    */
   void setLogScale(bool state);
@@ -244,9 +246,10 @@ private:
 
   ColorUpdater colorUpdater; ///< Handle to the color updating delegator
   BackgroundRgbProvider backgroundRgbProvider; /// < Holds the manager for background color related tasks.
-   const pqColorMapModel* m_currentColorMapModel;
+  RebinnedSourcesManager* m_rebinnedSourcesManager;
+  const pqColorMapModel* m_currentColorMapModel;
 
-  QString m_temporaryWorkspaceIdentifier;
+  QString m_internallyRebinnedWorkspaceIdentifier;
 };
 
 }
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/AutoScaleRangeGenerator.cpp b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/AutoScaleRangeGenerator.cpp
index 8bb04709ace7bf305902120620028907daefc127..b1e338b6a3c6dce3265fe5b5656d9253059bee74 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/AutoScaleRangeGenerator.cpp
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/AutoScaleRangeGenerator.cpp
@@ -165,6 +165,9 @@ namespace SimpleGui
     // Set the color scale output
     VsiColorScale vsiColorScale;
 
+    // Initialize log scale to false
+    vsiColorScale.useLogScale = false;
+
     // If either the min or max value are at the end of the double spectrum, we might only have a peak Ws visible, 
     // we need to hedge for that
     if (minValue == DBL_MAX || maxValue == -DBL_MAX) {
@@ -230,7 +233,9 @@ namespace SimpleGui
 
     // Check if Peak Workspace. This workspace should not contribute to colorscale
     if (QString(proxy->GetXMLName()).contains("Peaks Source") ||
-        QString(proxy->GetXMLName()).contains("SinglePeakMarkerSource"))
+        QString(proxy->GetXMLName()).contains("SinglePeakMarkerSource") ||
+        QString(proxy->GetXMLName()).contains("Threshold") ||
+        QString(proxy->GetXMLName()).contains("ProbePoint"))
     {
       minValue = DBL_MAX;
       maxValue = -DBL_MAX;
@@ -239,11 +244,11 @@ namespace SimpleGui
     }
 
     // Otherwise get the data range of the representation for the active view
-    pqPipelineRepresentation* pipelineRepresenation = qobject_cast<pqPipelineRepresentation*>(source->getRepresentation(pqActiveObjects::instance().activeView()));
+    pqPipelineRepresentation* pipelineRepresentation = qobject_cast<pqPipelineRepresentation*>(source->getRepresentation(pqActiveObjects::instance().activeView()));
 
-    if (pipelineRepresenation)
+    if (pipelineRepresentation)
     {
-      QPair<double, double> range = pipelineRepresenation->getColorFieldRange();
+      QPair<double, double> range = pipelineRepresentation->getLookupTable()->getScalarRange();
 
       minValue = range.first;
       maxValue = range.second;
@@ -261,7 +266,10 @@ namespace SimpleGui
 
     QList<pqPipelineSource *> sources;
 
-    sources = smModel->findItems<pqPipelineSource *>(server);
+    if (server)
+    {
+      sources = smModel->findItems<pqPipelineSource *>(server);
+    }
 
     return sources;
   }
@@ -304,4 +312,4 @@ namespace SimpleGui
   }
 }
 }
-}
\ No newline at end of file
+}
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/BackgroundRgbProvider.cpp b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/BackgroundRgbProvider.cpp
index 59b0757a017629cff5dc453b01656a09b1bf9f23..d679dcb42d00e2dd19bccf09bbdbd356bb76448d 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/BackgroundRgbProvider.cpp
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/BackgroundRgbProvider.cpp
@@ -37,10 +37,10 @@ namespace Mantid
          update();
       }
 
-      std::vector<double> BackgroundRgbProvider::getRgb(bool viewSwitched)
+      std::vector<double> BackgroundRgbProvider::getRgb(bool useCurrentBackgroundColor)
       {
         // Get the rgb setting from the config file
-        std::vector<double> userSettingRgb = getRgbFromSetting(viewSwitched);
+        std::vector<double> userSettingRgb = getRgbFromSetting(useCurrentBackgroundColor);
         
         // Normalize the entries to 256
         userSettingRgb[0] = userSettingRgb[0]/255.0;
@@ -50,13 +50,13 @@ namespace Mantid
         return userSettingRgb;
       }
 
-      std::vector<double> BackgroundRgbProvider::getRgbFromSetting(bool viewSwitched)
+      std::vector<double> BackgroundRgbProvider::getRgbFromSetting(bool useCurrentBackgroundColor)
       {
         // Set the mantid default here
         std::vector<double> background;
         QColor userBackground;
 
-        if (viewSwitched)
+        if (useCurrentBackgroundColor)
         {
           // Update the settings
           update();
@@ -113,9 +113,9 @@ namespace Mantid
         m_mdSettings.setLastSessionBackgroundColor(currentBackgroundColor);
       }
 
-      void BackgroundRgbProvider::setBackgroundColor(pqRenderView* view, bool viewSwitched)
+      void BackgroundRgbProvider::setBackgroundColor(pqRenderView* view, bool useCurrentBackgroundColor)
       {
-        std::vector<double> backgroundRgb = getRgb(viewSwitched);
+        std::vector<double> backgroundRgb = getRgb(useCurrentBackgroundColor);
 
         vtkSMDoubleVectorProperty* background = vtkSMDoubleVectorProperty::SafeDownCast(view->getViewProxy()->GetProperty("Background"));
 
@@ -134,7 +134,7 @@ namespace Mantid
         view->getViewProxy()->GetProperty("Background")->AddObserver(vtkCommand::ModifiedEvent, backgroundColorChangeCallback);
       }
 
-      void BackgroundRgbProvider::backgroundColorChangeCallbackFunction(vtkObject* caller, long unsigned int vtkNotUsed(eventId), void* vtkNotUsed(clientData), void* vtkNotUsed(callData))
+      void BackgroundRgbProvider::backgroundColorChangeCallbackFunction(vtkObject* caller, long unsigned int, void*, void*)
       {
         // Extract the background color and persist it 
         vtkSMDoubleVectorProperty* background =vtkSMDoubleVectorProperty::SafeDownCast(caller);
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/CameraManager.cpp b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/CameraManager.cpp
index 89e72483e2fc9c3fc71a3eb37958c20f1cf10197..2c691f7aba0456e0522492bf758df0c407732a73 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/CameraManager.cpp
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/CameraManager.cpp
@@ -7,12 +7,12 @@
 #endif
 
 #include <pqView.h>
-#include <pqActiveView.h>
+#include <pqActiveObjects.h>
 #include <vtkSMRenderViewProxy.h>
 #include <vtkCamera.h>
 #include <vtkRenderer.h>
 #include <vtkRenderWindow.h>
-
+#include <boost/make_shared.hpp>
 namespace Mantid
 {
   namespace Vates
@@ -30,7 +30,7 @@ namespace Mantid
       /**
        * Get the plane equation for the view frustum.
        */
-      Mantid::VATES::ViewFrustum CameraManager::getCurrentViewFrustum()
+      Mantid::VATES::ViewFrustum_const_sptr CameraManager::getCurrentViewFrustum()
       {
         double left[4];
         double right[4];
@@ -39,7 +39,7 @@ namespace Mantid
         double far[4];
         double near[4];
 
-        pqView * view = pqActiveView::instance().current();
+        pqView * view = pqActiveObjects::instance().activeView();
 
         vtkSMRenderViewProxy* proxy = NULL;
 
@@ -87,12 +87,13 @@ namespace Mantid
           near[k] = planes[k + 16];
           far[k] = planes[k + 20];
         }
-        Mantid::VATES::ViewFrustum frustum(Mantid::VATES::LeftPlane(left[0], left[1], left[2], left[3]),
-                                           Mantid::VATES::RightPlane(right[0], right[1], right[2], right[3]),
-                                           Mantid::VATES::BottomPlane(bottom[0], bottom[1], bottom[2], bottom[3]),
-                                           Mantid::VATES::TopPlane(top[0], top[1], top[2], top[3]),
-                                           Mantid::VATES::FarPlane(far[0], far[1], far[2], far[3]),
-                                           Mantid::VATES::NearPlane(near[0], near[1], near[2], near[3]));
+
+        Mantid::VATES::ViewFrustum_const_sptr frustum = boost::make_shared<const Mantid::VATES::ViewFrustum>(Mantid::VATES::LeftPlane(left[0], left[1], left[2], left[3]),
+                                                                                                             Mantid::VATES::RightPlane(right[0], right[1], right[2], right[3]),
+                                                                                                             Mantid::VATES::BottomPlane(bottom[0], bottom[1], bottom[2], bottom[3]),
+                                                                                                             Mantid::VATES::TopPlane(top[0], top[1], top[2], top[3]),
+                                                                                                             Mantid::VATES::FarPlane(far[0], far[1], far[2], far[3]),
+                                                                                                             Mantid::VATES::NearPlane(near[0], near[1], near[2], near[3]));
 
         return frustum;
       }
@@ -106,7 +107,7 @@ namespace Mantid
       */
       void CameraManager::setCameraToPeak(double xpos, double ypos, double zpos, double peakRadius)
       {
-        pqView * view = pqActiveView::instance().current();
+        pqView * view = pqActiveObjects::instance().activeView();
         vtkSMRenderViewProxy* proxy = NULL;
 
         if (view)
@@ -136,4 +137,4 @@ namespace Mantid
       }
     }
   }
-}
\ No newline at end of file
+}
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/ColorMapManager.cpp b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/ColorMapManager.cpp
index c32a2a5429488ad057f30b1cb1a6290bce90ea0c..b775d9fb08dcb9d7e1031839b8c8164e4b2069d6 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/ColorMapManager.cpp
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/ColorMapManager.cpp
@@ -19,12 +19,12 @@ namespace Mantid
       {
       }
 
-      int ColorMapManager::getDefaultColorMapIndex(bool viewSwitched)
+      int ColorMapManager::getDefaultColorMapIndex(bool useCurrentColorMap)
       {
         QString defaultColorMap;
 
-        // If the view has switched use the last color map index
-        if (viewSwitched)
+        // If the view has switched or the VSI is loaded use the last color map index
+        if (useCurrentColorMap)
         {
           defaultColorMap = m_mdSettings.getLastSessionColorMap();
         }
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/ColorUpdater.cpp b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/ColorUpdater.cpp
index 07bdd917902011e80702dd3831ef7db2d9237776..be8b16c75049d39a6b068ef6bc2ec3865739a523 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/ColorUpdater.cpp
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/ColorUpdater.cpp
@@ -2,6 +2,8 @@
 #include "MantidVatesSimpleGuiViewWidgets/ColorSelectionWidget.h"
 #include "MantidVatesSimpleGuiViewWidgets/AutoScaleRangeGenerator.h"
 
+#include "MantidKernel/Logger.h"
+
 // Have to deal with ParaView warnings and Intel compiler the hard way.
 #if defined(__INTEL_COMPILER)
   #pragma warning disable 1170
@@ -30,6 +32,9 @@
 
 namespace Mantid
 {
+  // static logger
+  Kernel::Logger g_log("ColorUpdater");
+
 namespace Vates
 {
 namespace SimpleGui
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/MdViewerWidget.cpp b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/MdViewerWidget.cpp
index d72a07fb5de86f48ed5dd486aec6fc73a06d1286..3ade38a6c553fb5b27c5de26a1cd03d87fa8ad6a 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/MdViewerWidget.cpp
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/MdViewerWidget.cpp
@@ -1,3 +1,5 @@
+#include "PythonThreading.h"
+
 #include "MantidVatesSimpleGuiViewWidgets/MdViewerWidget.h"
 
 #include "MantidVatesSimpleGuiQtWidgets/ModeControlWidget.h"
@@ -31,9 +33,11 @@
 #include <pqAnimationManager.h>
 #include <pqAnimationScene.h>
 #include <pqApplicationCore.h>
+#include <pqApplicationSettingsReaction.h>
+#include <pqApplyBehavior.h>
+#include <pqDeleteReaction.h>
 #include <pqLoadDataReaction.h>
 #include <pqObjectBuilder.h>
-#include <pqObjectInspectorWidget.h>
 #include <pqParaViewBehaviors.h>
 #include <pqPipelineSource.h>
 #include <pqPipelineFilter.h>
@@ -43,7 +47,6 @@
 #include <pqServer.h>
 #include <pqServerManagerModel.h>
 #include <pqStatusBar.h>
-#include <pqViewSettingsReaction.h>
 #include <vtkSMDoubleVectorProperty.h>
 #include <vtkSMPropertyHelper.h>
 #include <vtkSMProxyManager.h>
@@ -64,10 +67,8 @@
 #include <pqDataTimeStepBehavior.h>
 #include <pqDataRepresentation.h>
 #include <pqDefaultViewBehavior.h>
-#include <pqDeleteBehavior.h>
 #include <pqFixPathsInStateFilesBehavior.h>
 #include <pqInterfaceTracker.h>
-#include <pqMultiServerBehavior.h>
 #include <pqObjectPickingBehavior.h>
 //#include <pqPersistentMainWindowStateBehavior.h>
 #include <pqPipelineContextMenuBehavior.h>
@@ -75,18 +76,19 @@
 //#include <pqPluginActionGroupBehavior.h>
 //#include <pqPluginDockWidgetsBehavior.h>
 #include <pqPluginManager.h>
-#include <pqPVNewSourceBehavior.h>
+#include <pqPluginSettingsBehavior.h>
 #include <pqQtMessageHandlerBehavior.h>
 #include <pqServer.h>
 #include <pqServerManagerModel.h>
 #include <pqSpreadSheetVisibilityBehavior.h>
 #include <pqStandardPropertyWidgetInterface.h>
-#include <pqStandardViewModules.h>
+#include <pqStandardViewFrameActionsImplementation.h>
 #include <pqUndoRedoBehavior.h>
 #include <pqView.h>
-#include <pqViewFrameActionsBehavior.h>
+//#include <pqViewFrameActionsBehavior.h>
 #include <pqViewStreamingBehavior.h>
 #include <pqVerifyRequiredPluginBehavior.h>
+#include <pqSaveDataReaction.h>
 
 #if defined(__INTEL_COMPILER)
   #pragma warning enable 1170
@@ -111,6 +113,8 @@
 #include <boost/regex.hpp>
 #include <boost/shared_ptr.hpp>
 
+#include "MantidVatesSimpleGuiViewWidgets/VatesParaViewApplication.h"
+
 namespace Mantid
 {
 namespace Vates
@@ -132,8 +136,11 @@ REGISTER_VATESGUI(MdViewerWidget)
  */
 MdViewerWidget::MdViewerWidget() : VatesViewerInterface(), currentView(NULL),
   dataLoader(NULL), hiddenView(NULL), lodAction(NULL), screenShot(NULL), viewLayout(NULL),
-  viewSettings(NULL), m_rebinAlgorithmDialogProvider(this), m_rebinnedWorkspaceIdentifier("_tempvsi")
+  viewSettings(NULL), useCurrentColorSettings(false), initialView(ModeControlWidget::STANDARD), m_rebinAlgorithmDialogProvider(this), m_rebinnedWorkspaceIdentifier("_tempvsi")
 {
+  //this will initialize the ParaView application if needed.
+  VatesParaViewApplication::instance();
+  
   // Calling workspace observer functions.
   observeAfterReplace();
   observePreDelete();
@@ -153,19 +160,13 @@ MdViewerWidget::MdViewerWidget() : VatesViewerInterface(), currentView(NULL),
  */
 MdViewerWidget::MdViewerWidget(QWidget *parent) : VatesViewerInterface(parent), m_rebinAlgorithmDialogProvider(this)
 {
-  this->checkEnvSetup();
+  
+  //this will initialize the ParaView application if needed.
+  VatesParaViewApplication::instance();
+  
   // We're in the standalone application mode
   this->internalSetup(false);
   this->setupUiAndConnections();
-  // FIXME: This doesn't allow a clean split of the classes. I will need
-  //        to investigate creating the individual behaviors to see if that
-  //        eliminates the dependence on the QMainWindow.
-  if (parent->inherits("QMainWindow"))
-  {
-    QMainWindow *mw = qobject_cast<QMainWindow *>(parent);
-    new pqParaViewBehaviors(mw, mw);
-  }
-
   this->setupMainView();
 }
 
@@ -180,27 +181,15 @@ MdViewerWidget::~MdViewerWidget()
  */
 void MdViewerWidget::internalSetup(bool pMode)
 {
-  this->isPluginInitialized = false;
+  static int widgetNumber = 0;
+  this->m_widgetName = QString("MdViewerWidget%1").arg(widgetNumber++);
   this->pluginMode = pMode;
   this->rotPointDialog = NULL;
   this->lodThreshold = 5.0;
   this->viewSwitched = false;
 }
 
-/**
- * This function uses VTK's system tools to check the environmental variables
- * to make sure PV_PLUGIN_PATH is available.
- */
-void MdViewerWidget::checkEnvSetup()
-{
-  QString pv_plugin_path = vtksys::SystemTools::GetEnv("PV_PLUGIN_PATH");
-  if (pv_plugin_path.isEmpty())
-  {
-    throw std::runtime_error("PV_PLUGIN_PATH not setup.\nVates plugins will not be available.\n"
-                             "Further use will cause the program to crash.\nPlease exit and "
-                             "set this variable.");
-  }
-}
+
 
 /**
  * This function sets up the UI components and connects some of the main
@@ -210,11 +199,9 @@ void MdViewerWidget::setupUiAndConnections()
 {
   this->ui.setupUi(this);
   this->ui.splitter_2->setStretchFactor(1, 1);
+  this->ui.splitter_3->setStretchFactor(0, 1);
   this->ui.statusBar->setSizeGripEnabled(false);
 
-  // Unset the connections since the views aren't up yet.
-  this->removeProxyTabWidgetConnections();
-
   QObject::connect(this->ui.modeControlWidget,
                    SIGNAL(executeSwitchViews(ModeControlWidget::Views)),
                    this, SLOT(switchViews(ModeControlWidget::Views)));
@@ -225,14 +212,36 @@ void MdViewerWidget::setupUiAndConnections()
                    this,
                    SLOT(onRotationPoint()));
 
+  /// Provide access to the color-editor panel for the application.
+  pqApplicationCore::instance()->registerManager(
+    "COLOR_EDITOR_PANEL", this->ui.colorMapEditorDock);
+  this->ui.colorMapEditorDock->hide();
+  //this->connect(this->ui.proxiesPanel,SIGNAL(changeFinished(vtkSMProxy*)),SLOT(panelChanged()));
+  QAction* temp = new QAction(this);
+  pqDeleteReaction* deleteHandler = new pqDeleteReaction(temp);
+  deleteHandler->connect(this->ui.propertiesPanel,SIGNAL(deleteRequested(pqPipelineSource*)),SLOT(deleteSource(pqPipelineSource*)));
+  
+  pqApplyBehavior* applyBehavior = new pqApplyBehavior(this);
+  applyBehavior->registerPanel(this->ui.propertiesPanel);
+  VatesParaViewApplication::instance()->setupParaViewBehaviors();
+  //this->ui.pipelineBrowser->enableAnnotationFilter(m_widgetName);
+  //this->ui.pipelineBrowser->disableAnnotationFilter();
+  //this->ui.pipelineBrowser->enableAnnotationFilter(m_widgetName);
+  //this->ui.pipelineBrowser->hide();
+  g_log.warning("Annotation Name: " + m_widgetName.toStdString());
+  
   // Connect the rebinned sources manager
   QObject::connect(&m_rebinnedSourcesManager,
                    SIGNAL(triggerAcceptForNewFilters()),
                    this->ui.propertiesPanel,
                    SLOT(apply()));
-
 }
 
+void MdViewerWidget::panelChanged()
+{
+    this->currentView->renderAll();
+}
+    
 /**
  * This function places the standard view to the main window, installs an
  * event filter, tweaks the UI layout for the view and calls the routine that
@@ -259,81 +268,6 @@ void MdViewerWidget::setupMainView()
   this->setParaViewComponentsForView();
 }
 
-
-
-/**
- * This function ensures that the main ParaView instance is only initialized
- * once. On the second call, it checks to make sure one doesn't exist. This is
- * only important for plugin mode operation of the VSI.
- */
-void MdViewerWidget::createAppCoreForPlugin()
-{
-  if (!pqApplicationCore::instance())
-  {
-    // Provide ParaView's application core with a path to ParaView
-    std::string paraviewPath = Mantid::Kernel::ConfigService::Instance().getParaViewPath();
-    if(paraviewPath.empty())
-    {
-      // ParaView crashes with an empty string but on Linux/OSX we dont set this property
-      paraviewPath = "/tmp/MantidPlot";
-    }
-    std::vector<char> argvConversion(paraviewPath.begin(), paraviewPath.end());
-    argvConversion.push_back('\0');
-
-    int argc = 1;
-    char *argv[] = {&argvConversion[0]};
-    g_log.debug() << "Intialize pqApplicationCore with " << argv << "\n";
-    new pqPVApplicationCore(argc, argv);
-  }
-  else
-  {
-    this->isPluginInitialized = true;
-  }
-}
-
-/**
- * This function duplicates the nearly identical call in ParaView for their
- * main program setup. This is necessary for the plugin mode since it does
- * not have access to the QMainWindow of MantidPlot.
- */
-void MdViewerWidget::setupParaViewBehaviors()
-{
-  // Register ParaView interfaces.
-  pqInterfaceTracker* pgm = pqApplicationCore::instance()->interfaceTracker();
-
-  // * adds support for standard paraview views.
-  pgm->addInterface(new pqStandardViewModules(pgm));
-
-  pgm->addInterface(new pqStandardPropertyWidgetInterface(pgm));
-
-  // Load plugins distributed with application.
-  pqApplicationCore::instance()->loadDistributedPlugins();
-
-  // Define application behaviors.
-  new pqQtMessageHandlerBehavior(this);
-  new pqDataTimeStepBehavior(this);
-  new pqViewFrameActionsBehavior(this);
-  new pqSpreadSheetVisibilityBehavior(this);
-  new pqPipelineContextMenuBehavior(this);
-  new pqDefaultViewBehavior(this);
-  new pqAlwaysConnectedBehavior(this);
-  new pqPVNewSourceBehavior(this);
-  new pqDeleteBehavior(this);
-  new pqUndoRedoBehavior(this);
-  new pqCrashRecoveryBehavior(this);
-  new pqAutoLoadPluginXMLBehavior(this);
-  //new pqPluginDockWidgetsBehavior(mainWindow);
-  new pqVerifyRequiredPluginBehavior(this);
-  //new pqPluginActionGroupBehavior(mainWindow);
-  new pqFixPathsInStateFilesBehavior(this);
-  new pqCommandLineOptionsBehavior(this);
-  //new pqPersistentMainWindowStateBehavior(mainWindow);
-  new pqObjectPickingBehavior(this);
-  new pqCollaborationBehavior(this);
-  new pqMultiServerBehavior(this);
-  new pqViewStreamingBehavior(this);
-}
-
 /**
  * This function connects ParaView's data loader the given action.
  * @param action the action to connect data loading to
@@ -347,19 +281,6 @@ void MdViewerWidget::connectLoadDataReaction(QAction *action)
                    this, SLOT(onDataLoaded(pqPipelineSource*)));
 }
 
-/**
- * This function disconnects ParaView connections between pqActiveObjects
- * and the pqProxyTabWidget. This is necessary for clean view switching.
- */
-void MdViewerWidget::removeProxyTabWidgetConnections()
-{
-  QObject::disconnect(&pqActiveObjects::instance(), 0,
-                      this->ui.propertiesPanel, 0);
-  this->ui.propertiesPanel->setRepresentation(NULL);
-  this->ui.propertiesPanel->setView(NULL);
-  this->ui.propertiesPanel->setOutputPort(NULL);
-}
-
 /**
  * This function creates the requested view on the main window.
  * @param container the UI widget to associate the view mode with
@@ -374,22 +295,22 @@ ViewBase* MdViewerWidget::setMainViewWidget(QWidget *container,
   {
   case ModeControlWidget::STANDARD:
   {
-    view = new StandardView(container);
+    view = new StandardView(container, &m_rebinnedSourcesManager);
   }
   break;
   case ModeControlWidget::THREESLICE:
   {
-    view = new ThreeSliceView(container);
+    view = new ThreeSliceView(container, &m_rebinnedSourcesManager);
   }
   break;
   case ModeControlWidget::MULTISLICE:
   {
-    view = new MultiSliceView(container);
+    view = new MultiSliceView(container, &m_rebinnedSourcesManager);
   }
   break;
   case ModeControlWidget::SPLATTERPLOT:
   {
-    view = new SplatterPlotView(container);
+    view = new SplatterPlotView(container, &m_rebinnedSourcesManager);
   }
   break;
   default:
@@ -407,22 +328,22 @@ ViewBase* MdViewerWidget::setMainViewWidget(QWidget *container,
 void MdViewerWidget::setParaViewComponentsForView()
 {
   // Extra setup stuff to hook up view to other items
-  this->ui.propertiesPanel->setView(this->currentView->getView());
+  //this->ui.propertiesPanel->setView(this->currentView->getView());
   this->ui.pipelineBrowser->setActiveView(this->currentView->getView());
 
   pqActiveObjects *activeObjects = &pqActiveObjects::instance();
   QObject::connect(activeObjects, SIGNAL(portChanged(pqOutputPort*)),
                    this->ui.propertiesPanel, SLOT(setOutputPort(pqOutputPort*)));
 
-  QObject::connect(activeObjects, SIGNAL(representationChanged(pqRepresentation*)),
-                   this->ui.propertiesPanel, SLOT(setRepresentation(pqRepresentation*)));
- 
+  //QObject::connect(activeObjects, SIGNAL(representationChanged(pqRepresentation*)),
+  //                 this->ui.propertiesPanel, SLOT(setRepresentation(pqRepresentation*)));
+
   QObject::connect(activeObjects, SIGNAL(viewChanged(pqView*)),
                    this->ui.propertiesPanel, SLOT(setView(pqView*)));
 
-  this->ui.propertiesPanel->setOutputPort(activeObjects->activePort());
-  this->ui.propertiesPanel->setView(this->currentView->getView());
-  this->ui.propertiesPanel->setRepresentation(activeObjects->activeRepresentation());
+  //this->ui.propertiesPanel->setOutputPort(activeObjects->activePort());
+  //this->ui.propertiesPanel->setView(this->currentView->getView());
+  //this->ui.propertiesPanel->setRepresentation(activeObjects->activeRepresentation());
 
   QObject::connect(this->currentView,
                    SIGNAL(triggerAccept()),
@@ -511,23 +432,24 @@ void MdViewerWidget::onRebin(std::string algorithmType)
 void MdViewerWidget::onSwitchSoures(std::string rebinnedWorkspaceName, std::string sourceType)
 {
   // Create the rebinned workspace
-  prepareRebinnedWorkspace(rebinnedWorkspaceName, sourceType); 
+  pqPipelineSource* rebinnedSource = prepareRebinnedWorkspace(rebinnedWorkspaceName, sourceType); 
 
   try
   {
-    std::string sourceToBeDeleted;
-
     // Repipe the filters to the rebinned source
-    m_rebinnedSourcesManager.repipeRebinnedSource(rebinnedWorkspaceName, sourceToBeDeleted);
+    m_rebinnedSourcesManager.repipeRebinnedSource();
 
-    // Remove the original source
-    deleteSpecificSource(sourceToBeDeleted);
+    // Update the animation controls in order to get the correct time slice
+    this->currentView->updateAnimationControls();
 
     // Update the color scale
     this->currentView->onAutoScale(this->ui.colorSelectionWidget);
 
     // Set the splatterplot button explicitly
     this->currentView->setSplatterplot(true);
+
+    pqActiveObjects::instance().setActiveSource(NULL);
+    pqActiveObjects::instance().setActiveSource(rebinnedSource);
   }
   catch (const std::runtime_error& error)
   {
@@ -540,7 +462,7 @@ void MdViewerWidget::onSwitchSoures(std::string rebinnedWorkspaceName, std::stri
  * @param rebinnedWorkspaceName The name of the rebinned workspace.
  * @param sourceType The name of the source plugin. 
  */
-void MdViewerWidget::prepareRebinnedWorkspace(const std::string rebinnedWorkspaceName, std::string sourceType)
+pqPipelineSource* MdViewerWidget::prepareRebinnedWorkspace(const std::string rebinnedWorkspaceName, std::string sourceType)
 {
   // Load a new source plugin
   pqPipelineSource* newRebinnedSource = this->currentView->setPluginSource(QString::fromStdString(sourceType), QString::fromStdString(rebinnedWorkspaceName));
@@ -548,25 +470,31 @@ void MdViewerWidget::prepareRebinnedWorkspace(const std::string rebinnedWorkspac
   // It seems that the new source gets set as active before it is fully constructed. We therefore reset it.
   pqActiveObjects::instance().setActiveSource(NULL);
   pqActiveObjects::instance().setActiveSource(newRebinnedSource);
-  m_rebinnedSourcesManager.registerRebinnedSource(newRebinnedSource);
 
   this->renderAndFinalSetup();
 
   this->currentView->onAutoScale(this->ui.colorSelectionWidget);
+
+  // Register the source
+  m_rebinnedSourcesManager.registerRebinnedSource(newRebinnedSource);
+
+  return newRebinnedSource;
 }
 
 /**
  * Creates and renders back to the original source 
  * @param originalWorkspaceName The name of the original workspace
  */
-void MdViewerWidget::renderOriginalWorkspace(const std::string originalWorkspaceName)
+pqPipelineSource* MdViewerWidget::renderOriginalWorkspace(const std::string originalWorkspaceName)
 {
   // Load a new source plugin
   QString sourcePlugin = "MDEW Source";
-  this->currentView->setPluginSource(sourcePlugin, QString::fromStdString(originalWorkspaceName));
+  pqPipelineSource* source = this->currentView->setPluginSource(sourcePlugin, QString::fromStdString(originalWorkspaceName));
 
   // Render and final setup
   this->renderAndFinalSetup();
+
+  return source;
 }
 
 
@@ -610,22 +538,25 @@ void MdViewerWidget::removeRebinning(pqPipelineSource* source, bool forced, Mode
       return;
     }
 
+    // We need to check that the rebinned workspace name has still a source associated to it
+    if (!m_rebinnedSourcesManager.isRebinnedSourceBeingTracked(source))
+    {
+      return;
+    }
+
     // Create the original source
-    renderOriginalWorkspace(originalWorkspaceName);
+    pqPipelineSource* originalSource = renderOriginalWorkspace(originalWorkspaceName);
 
     // Repipe the filters to the original source
     try
     {
-      m_rebinnedSourcesManager.repipeOriginalSource(rebinnedWorkspaceName, originalWorkspaceName);
+      m_rebinnedSourcesManager.repipeOriginalSource(source, originalSource);
     }
     catch (const std::runtime_error& error)
     {
       g_log.warning() << error.what();
     }
 
-    // Remove the rebinned workspace source
-    deleteSpecificSource(rebinnedWorkspaceName);
-
     // Render and final setup
     pqActiveObjects::instance().activeView()->forceRender();
 
@@ -690,7 +621,7 @@ void MdViewerWidget::renderingDone()
 {
   if (this->viewSwitched)
   {
-    this->ui.colorSelectionWidget->loadColorMap(this->viewSwitched); // Load the default color map
+    this->setColorMap(); // Load the default color map
     this->currentView->setColorsForView(this->ui.colorSelectionWidget);
     this->viewSwitched = false;
   }
@@ -705,13 +636,14 @@ void MdViewerWidget::renderingDone()
  */
 void MdViewerWidget::renderWorkspace(QString workspaceName, int workspaceType, std::string instrumentName)
 {
+  GlobalInterpreterLock gil;
   // Workaround: Note that setting to the standard view was part of the eventFilter. This causes the 
   //             VSI window to not close properly. Moving it here ensures that we have the switch, but
   //             after the window is started again.
   if (this->currentView->getNumSources() == 0)
   {
     this->setColorForBackground();
-    this->ui.colorSelectionWidget->loadColorMap(this->viewSwitched);
+    this->setColorMap();
 
     this->ui.modeControlWidget->setToStandardView();
     this->currentView->hide();
@@ -719,6 +651,12 @@ void MdViewerWidget::renderWorkspace(QString workspaceName, int workspaceType, s
     this->currentView->initializeColorScale();
   }
 
+  // Set usage of current color settings to true, since we have loade the VSI
+  if (!this->useCurrentColorSettings)
+  {
+    this->useCurrentColorSettings = true;
+  }
+
   QString sourcePlugin = "";
   if (VatesViewerInterface::PEAKS == workspaceType)
   {
@@ -733,20 +671,10 @@ void MdViewerWidget::renderWorkspace(QString workspaceName, int workspaceType, s
     sourcePlugin = "MDEW Source";
   }
 
-  // Make sure that we are not loading a rebinned vsi workspace.
-  if (workspaceName.contains(m_rebinnedWorkspaceIdentifier))
-  {
-    QMessageBox::information(this, QApplication::tr("Loading Source Warning"),
-                             QApplication::tr("You cannot load a rebinned rebinned vsi source. \n "\
-                                              "Please select another source."));
-
-    return;
-  }
-
   // Load a new source plugin
-  this->currentView->setPluginSource(sourcePlugin, workspaceName);
-
-  this->renderAndFinalSetup();
+    pqPipelineSource* source = this->currentView->setPluginSource(sourcePlugin, workspaceName);
+    source->getProxy()->SetAnnotation(this->m_widgetName.toLatin1().data(), "1");
+    this->renderAndFinalSetup();
 
   // Reset the current view to the correct initial view
   // Note that we can only reset if a source plugin exists.
@@ -931,7 +859,9 @@ ModeControlWidget::Views MdViewerWidget::checkViewAgainstWorkspace(ModeControlWi
     // Histo workspaces cannot have a splatter plot, 
     if (view == ModeControlWidget::SPLATTERPLOT)
     {
-      g_log.warning() << "Selected a splatter plot for a histo workspace. Defaulted to standard view. \n";  
+      g_log.notice() << "The preferred initial view favours the splatterplot as initial view, "
+                          << "but an MDHisto workspace is being loaded. An MDHisto workspace "
+                          << "cannot be loaded into a splatterplot view. Defaulted to standard view. \n";  
 
       selectedView =  ModeControlWidget::STANDARD;
     } 
@@ -954,18 +884,13 @@ ModeControlWidget::Views MdViewerWidget::checkViewAgainstWorkspace(ModeControlWi
  */
 void MdViewerWidget::setupPluginMode()
 {
-  this->createAppCoreForPlugin();
-  this->checkEnvSetup();
+  GlobalInterpreterLock gil;
+  this->useCurrentColorSettings = false; // Don't use the current color map at start up.
   this->setupUiAndConnections();
-  if (!this->isPluginInitialized)
-  {
-    this->setupParaViewBehaviors();
-    this->createMenus();
-  }
+  this->createMenus();
   this->setupMainView();
 }
 
-
 /**
  * This function tells the current view to render the data, perform any
  * necessary checks on the view given the workspace type and update the
@@ -975,10 +900,20 @@ void MdViewerWidget::renderAndFinalSetup()
 {
   this->setColorForBackground();
   this->currentView->render();
-  this->ui.colorSelectionWidget->loadColorMap(this->viewSwitched);
+  this->setColorMap();
   this->currentView->setColorsForView(this->ui.colorSelectionWidget);
   this->currentView->checkView(this->initialView);
   this->currentView->updateAnimationControls();
+  pqPipelineSource *source = this->currentView->origSrc;
+  //suppress unused variable;
+  (void)source;
+  pqPipelineRepresentation *repr = this->currentView->origRep;
+  //suppress unused variable;
+  (void)repr;
+  //this->ui.proxiesPanel->clear();
+  //this->ui.proxiesPanel->addProxy(source->getProxy(),"datasource",QStringList(),true);
+  //this->ui.proxiesPanel->addProxy(repr->getProxy(),"display",QStringList("CubeAxesVisibility"),true);
+  //this->ui.proxiesPanel->updateLayout();
   this->setDestroyedListener();
   this->currentView->setVisibilityListener();
   this->currentView->onAutoScale(this->ui.colorSelectionWidget);
@@ -989,7 +924,7 @@ void MdViewerWidget::renderAndFinalSetup()
  */
 void MdViewerWidget::setColorForBackground()
 {
-  this->currentView->setColorForBackground(this->viewSwitched);
+  this->currentView->setColorForBackground(this->useCurrentColorSettings);
 }
 
 /**
@@ -1038,7 +973,6 @@ void MdViewerWidget::switchViews(ModeControlWidget::Views v)
   this->viewSwitched = true;
   this->currentView->closeSubWindows();
   this->disconnectDialogs();
-  this->removeProxyTabWidgetConnections();
   this->hiddenView = this->setMainViewWidget(this->ui.viewWidget, v);
   this->hiddenView->setColorScaleState(this->ui.colorSelectionWidget);
   this->hiddenView->hide();
@@ -1052,7 +986,7 @@ void MdViewerWidget::switchViews(ModeControlWidget::Views v)
   this->connectDialogs();
   this->hiddenView->close();
   this->hiddenView->destroyView();
-  delete this->hiddenView;
+  this->hiddenView->deleteLater();
   this->setColorForBackground();
   this->currentView->render();
   this->currentView->setColorsForView(this->ui.colorSelectionWidget);
@@ -1101,10 +1035,20 @@ bool MdViewerWidget::eventFilter(QObject *obj, QEvent *ev)
       this->currentView ->destroyAllSourcesInView();
       this->currentView->updateSettings();
       this->currentView->hide();
+      this->useCurrentColorSettings = false;
 
       return true;
     }
   }
+  if(ev->type() == QEvent::WindowActivate)
+  {
+    if(this->currentView)
+    {
+      pqView* view = this->currentView->getView();
+      pqActiveObjects::instance().setActiveView(view);
+      pqActiveObjects::instance().setActiveSource(this->currentView->origSrc);
+    }
+  }
   return VatesViewerInterface::eventFilter(obj, ev);
 }
 
@@ -1151,10 +1095,10 @@ void MdViewerWidget::createMenus()
   this->screenShot = new SaveScreenshotReaction(screenShotAction);
   viewMenu->addAction(screenShotAction);
 
-  QAction *settingsAction = new QAction(QApplication::tr("View Settings..."), this);
+  QAction *settingsAction = new QAction(QApplication::tr("Settings..."), this);
   settingsAction->setShortcut(QKeySequence::fromString("Ctrl+Shift+S"));
   settingsAction->setStatusTip(QApplication::tr("Show the settings for the current view."));
-  this->viewSettings = new pqViewSettingsReaction(settingsAction);
+  this->viewSettings = new pqApplicationSettingsReaction(settingsAction);
   viewMenu->addAction(settingsAction);
 
   QMenu *helpMenu = menubar->addMenu(QApplication::tr("&Help"));
@@ -1295,8 +1239,6 @@ void MdViewerWidget::connectDialogs()
  */
 void MdViewerWidget::updateAppState()
 {
-  this->viewSettings->updateEnableState();
-
   ThreeSliceView *tsv = dynamic_cast<ThreeSliceView *>(this->currentView);
   SplatterPlotView *spv = dynamic_cast<SplatterPlotView *>(this->currentView);
   if (NULL != tsv || NULL != spv)
@@ -1328,33 +1270,26 @@ void MdViewerWidget::afterReplaceHandle(const std::string &wsName,
     // Have to mark the filter as modified to get it to update. Do this by
     // changing the requested workspace name to a dummy name and then change
     // back. However, push the change all the way down for it to work.
-    vtkSMPropertyHelper(src->getProxy(),
+    vtkSMProxy* proxy = src->getProxy();
+    vtkSMPropertyHelper(proxy,
                         "Mantid Workspace Name").Set("ChangeMe!");
-    vtkSMSourceProxy *srcProxy = vtkSMSourceProxy::SafeDownCast(src->getProxy());
-    srcProxy->UpdateVTKObjects();
-    srcProxy->Modified();
-    srcProxy->UpdatePipelineInformation();
-    src->updatePipeline();
+    proxy->UpdateVTKObjects();
 
-    vtkSMPropertyHelper(src->getProxy(),
+    vtkSMPropertyHelper(proxy,
                         "Mantid Workspace Name").Set(wsName.c_str());
     // Update the source so that it retrieves the data from the Mantid workspace
-    srcProxy = vtkSMSourceProxy::SafeDownCast(src->getProxy());
-    srcProxy->UpdateVTKObjects();
-    srcProxy->Modified();
-    srcProxy->UpdatePipelineInformation();
+    proxy->UpdateVTKObjects();
     src->updatePipeline();
 
     this->currentView->setColorsForView(this->ui.colorSelectionWidget);
-    this->currentView->renderAll();;
+    this->currentView->renderAll();
   }
 }
 
 /**
  * This function responds to a workspace being deleted. If there are one or
- * more PeaksWorkspaces present, the requested one will be deleted. If the
- * deleted source is a rebinned source, then we revert back to the
-*  original source. Otherwise, if it is an IMDWorkspace, everything goes! 
+ * more PeaksWorkspaces present, the requested one will be deleted. 
+ * Otherwise, if it is an IMDWorkspace, everything goes! 
  * @param wsName : Name of workspace being deleted
  * @param ws : Pointer to workspace being deleted
  */
@@ -1377,13 +1312,6 @@ void MdViewerWidget::preDeleteHandle(const std::string &wsName,
       }
     }
 
-    // Check if rebinned source and perform an unbinning
-    if (m_rebinnedSourcesManager.isRebinnedSource(wsName))
-    {
-      removeRebinning(src, true);
-      return;
-    }
-    
     // Remove all visibility listeners
     this->currentView->removeVisibilityListener();
 
@@ -1391,39 +1319,6 @@ void MdViewerWidget::preDeleteHandle(const std::string &wsName,
   }
 }
 
-/**
- * Delete a specific source and all of its filters. This assumes a linear filter system
- * @param workspaceName The workspaceName associated with the source which is to be deleted
- */
-void MdViewerWidget::deleteSpecificSource(std::string workspaceName)
-{
-  pqPipelineSource *source = this->currentView->hasWorkspace(workspaceName.c_str());
-  if (NULL != source)
-  {
-    // Go to the end of the source and work your way back
-    pqPipelineSource* tempSource = source;
-
-    while ((tempSource->getAllConsumers()).size() > 0)
-    {
-      tempSource = tempSource->getConsumer(0);
-    }
-
-    // Now delete all filters and the source
-    pqObjectBuilder *builder = pqApplicationCore::instance()->getObjectBuilder();
-
-    // Crawl up to the source level 
-    pqPipelineFilter* filter = qobject_cast<pqPipelineFilter*>(tempSource);
-
-    while (filter)
-    {
-      tempSource = filter->getInput(0);
-      builder->destroy(filter);
-      filter = qobject_cast<pqPipelineFilter*>(tempSource);
-    }
-
-    builder->destroy(tempSource);
-  }
-}
 
 /**
 * Set the listener for when sources are being destroyed
@@ -1510,6 +1405,14 @@ void MdViewerWidget::dropEvent(QDropEvent *e) {
   }
 }
 
+/**
+ * Set the color map
+ */
+void MdViewerWidget::setColorMap()
+{
+   // If it is not the first startup of the color map, then we want to use the current color map
+  this->ui.colorSelectionWidget->loadColorMap(this->useCurrentColorSettings);
+}
 
 } // namespace SimpleGui
 } // namespace Vates
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/MultisliceView.cpp b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/MultisliceView.cpp
index 6a6ea3228523ee6e7f8600ed88ec2daa3cb908f1..555190a1d441b65e27db9705fcbad64d4ae3fdef 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/MultisliceView.cpp
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/MultisliceView.cpp
@@ -1,7 +1,6 @@
 #include "MantidVatesSimpleGuiViewWidgets/MultisliceView.h"
-
+#include "MantidVatesSimpleGuiViewWidgets/RebinnedSourcesManager.h"
 #include "MantidVatesSimpleGuiQtWidgets/GeometryParser.h"
-
 #include "MantidGeometry/MDGeometry/MDPlaneImplicitFunction.h"
 #include "MantidQtSliceViewer/SliceViewerWindow.h"
 #include "MantidQtFactory/WidgetFactory.h"
@@ -21,8 +20,15 @@
 #include <pqRenderView.h>
 #include <pqServerManagerModel.h>
 #include <vtkContextMouseEvent.h>
+#include <vtkDataObject.h>
+#include <vtkMatrix4x4.h>
+#include <vtkNew.h>
+#include <vtkPVArrayInformation.h>
+#include <vtkPVChangeOfBasisHelper.h>
+#include <vtkPVDataInformation.h>
 #include <vtkSMPropertyHelper.h>
-#include <vtkSMProxy.h>
+#include <vtkSMSourceProxy.h>
+#include <vtkVector.h>
 
 #if defined(__INTEL_COMPILER)
   #pragma warning enable 1170
@@ -42,7 +48,70 @@ namespace Vates
 namespace SimpleGui
 {
 
-MultiSliceView::MultiSliceView(QWidget *parent) : ViewBase(parent)
+//-----------------------------------------------------------------------------
+// This is copied from ParaView's
+// pqModelTransformSupportBehavior::getChangeOfBasisMatrix(). Once ParaView min
+// version is updated to > 4.3, simply use that method.
+template<class T, int size>
+vtkTuple<T, size> GetValues(
+  const char* aname, vtkSMSourceProxy* producer, int port, bool *pisvalid)
+{
+  bool dummy;
+  pisvalid = pisvalid? pisvalid : &dummy;
+  *pisvalid = false;
+
+  vtkTuple<T, size> value;
+  vtkPVDataInformation* dinfo = producer->GetDataInformation(port);
+  if (vtkPVArrayInformation* ainfo =
+    (dinfo? dinfo->GetArrayInformation(aname, vtkDataObject::FIELD) : NULL))
+    {
+    if (ainfo->GetNumberOfComponents() == size)
+      {
+      *pisvalid = true;
+      for (int cc=0; cc < size; cc++)
+        {
+        value[cc] = ainfo->GetComponentRange(cc)[0];
+        }
+      }
+    }
+  return value;
+}
+
+static vtkTuple<double, 16> GetChangeOfBasisMatrix(
+  vtkSMSourceProxy* producer, int port=0, bool* pisvalid=NULL)
+{
+  return GetValues<double, 16>("ChangeOfBasisMatrix", producer, port, pisvalid);
+}
+
+static void GetOrientations(vtkSMSourceProxy* producer, vtkVector3d sliceNormals[3])
+{
+  bool isvalid = false;
+  vtkTuple<double, 16> cobm = GetChangeOfBasisMatrix(producer, 0, &isvalid);
+  if (isvalid)
+    {
+    vtkNew<vtkMatrix4x4> changeOfBasisMatrix;
+    std::copy(&cobm[0], &cobm[0] + 16, &changeOfBasisMatrix->Element[0][0]);
+    vtkVector3d axisBases[3];
+    vtkPVChangeOfBasisHelper::GetBasisVectors(changeOfBasisMatrix.GetPointer(),
+      axisBases[0], axisBases[1], axisBases[2]);
+    for (int cc=0; cc < 3; cc++)
+      {
+      sliceNormals[cc] = axisBases[(cc+1)%3].Cross(axisBases[(cc+2)%3]);
+      sliceNormals[cc].Normalize();
+      }
+    }
+  else
+    {
+    sliceNormals[0] = vtkVector3d(1, 0, 0);
+    sliceNormals[1] = vtkVector3d(0, 1, 0);
+    sliceNormals[2] = vtkVector3d(0, 0, 1);
+    }
+}
+
+//-----------------------------------------------------------------------------
+
+
+MultiSliceView::MultiSliceView(QWidget *parent, RebinnedSourcesManager* rebinnedSourcesManager) : ViewBase(parent, rebinnedSourcesManager)
 {
   this->ui.setupUi(this);
   pqRenderView *tmp = this->createRenderView(this->ui.renderFrame,
@@ -139,6 +208,13 @@ void MultiSliceView::checkSliceViewCompat()
     QObject::disconnect(this->mainView, 0, this, 0);
   }
 }
+  
+void MultiSliceView::changedSlicePoint(Mantid::Kernel::VMD selectedPoint)
+{
+  vtkSMPropertyHelper(this->mainView->getProxy(),"XSlicesValues").Set(selectedPoint[0]);
+  this->mainView->getProxy()->UpdateVTKObjects();
+  this->mainView->render();
+}
 
 /**
  * This function is responsible for opening the given cut in SliceViewer.
@@ -214,7 +290,10 @@ void MultiSliceView::showCutInSliceViewer(int axisIndex,
       sliceOffsetOnAxis /= scaling[0];
     }
   }
-  const double *orient = this->mainView->GetSliceNormal(axisIndex);
+
+  vtkVector3d sliceNormals[3];
+  GetOrientations(vtkSMSourceProxy::SafeDownCast(src1->getProxy()), sliceNormals);
+  vtkVector3d& orient = sliceNormals[axisIndex];
 
   // Construct origin vector from orientation vector
   double origin[3];
@@ -223,11 +302,11 @@ void MultiSliceView::showCutInSliceViewer(int axisIndex,
   origin[2] = sliceOffsetOnAxis * orient[2];
 
   // Create the XML holder
-  VATES::VatesKnowledgeSerializer rks(VATES::LocationNotRequired);
+  VATES::VatesKnowledgeSerializer rks;
   rks.setWorkspaceName(wsName.toStdString());
   rks.setGeometryXML(geomXML);
 
-  MDImplicitFunction_sptr impplane(new MDPlaneImplicitFunction(3, orient,
+  MDImplicitFunction_sptr impplane(new MDPlaneImplicitFunction(3, orient.GetData(),
                                                                origin));
   rks.setImplicitFunction(impplane);
   QString titleAddition = "";
@@ -239,6 +318,7 @@ void MultiSliceView::showCutInSliceViewer(int axisIndex,
     // Set the slice points, etc, using the XML definition of the plane function
     w->getSlicer()->openFromXML( QString::fromStdString(rks.createXMLString()) );
     w->show();
+    this->connect(w->getSlicer(), SIGNAL(changedSlicePoint(Mantid::Kernel::VMD)), SLOT(changedSlicePoint(Mantid::Kernel::VMD)));
   }
   catch (std::runtime_error & e)
   {
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/PeaksTableControllerVsi.cpp b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/PeaksTableControllerVsi.cpp
index 5cdd8552c9ec1cfe196150910aeec261ad0b6ea0..e5414a9c4c9c4c57ae3ac63b799c3693d33a1878 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/PeaksTableControllerVsi.cpp
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/PeaksTableControllerVsi.cpp
@@ -11,6 +11,7 @@
 #include "MantidKernel/V3D.h"
 #include "MantidKernel/SpecialCoordinateSystem.h"
 #include "MantidKernel/Logger.h"
+#include "MantidVatesAPI/ViewFrustum.h"
 #include "MantidVatesAPI/PeaksPresenterVsi.h"
 #include "MantidVatesAPI/NullPeaksPresenterVsi.h"
 #include "MantidVatesAPI/ConcretePeaksPresenterVsi.h"
@@ -72,7 +73,7 @@ PeaksTableControllerVsi::PeaksTableControllerVsi(
     boost::shared_ptr<CameraManager> cameraManager, QWidget *parent)
     : QWidget(parent), m_cameraManager(cameraManager),
       m_presenter(new Mantid::VATES::CompositePeaksPresenterVsi()),
-      m_peaksTabWidget(NULL), m_peakMarker(NULL) {
+      m_peaksTabWidget(NULL), m_peakMarker(NULL), m_coordinateSystem(Mantid::Kernel::SpecialCoordinateSystem::QLab) {
   m_peakTransformSelector.registerCandidate(
       boost::make_shared<Mantid::API::PeakTransformHKLFactory>());
   m_peakTransformSelector.registerCandidate(
@@ -266,8 +267,7 @@ void PeaksTableControllerVsi::updatePeakWorkspaceColor() {
  * Update the view region for the presenters
  */
 void PeaksTableControllerVsi::updateViewableArea() {
-  Mantid::VATES::ViewFrustum frustum = m_cameraManager->getCurrentViewFrustum();
-  m_presenter->updateViewFrustum(frustum);
+  m_presenter->updateViewFrustum(m_cameraManager->getCurrentViewFrustum());
 }
 
 /**
@@ -396,6 +396,9 @@ void PeaksTableControllerVsi::removeLayout(QWidget *widget) {
  * Remove the table.
  */
 void PeaksTableControllerVsi::removeTable() {
+  // Reset the color of peaks sources
+  setPeakSourceColorToDefault();
+
   destroySinglePeakSource();
   if (m_peaksTabWidget) {
     m_peaksTabWidget->deleteLater();
@@ -609,6 +612,50 @@ void PeaksTableControllerVsi::onPeaksSorted(
   m_presenter->sortPeaksWorkspace(columnToSortBy, sortAscending, ws);
   // Update the tabs
 }
+
+/**
+ * Reset the color of the peaks workspace glyphs to white
+ */
+void PeaksTableControllerVsi::setPeakSourceColorToDefault() {
+  pqServer *server = pqActiveObjects::instance().activeServer();
+  pqServerManagerModel *smModel = pqApplicationCore::instance()->getServerManagerModel();
+  QList<pqPipelineSource *> sources = smModel->findItems<pqPipelineSource *>(server);
+  for (QList<pqPipelineSource *>::iterator src = sources.begin(); src != sources.end(); ++src) {
+
+    std::string xmlName((*src)->getProxy()->GetXMLName());
+    if ((xmlName.find("Peaks Source") != std::string::npos)) {
+        double red = 1.0;
+        double green = 1.0;
+        double blue = 1.0;
+
+        pqDataRepresentation *rep =
+            (*src)
+                ->getRepresentation(pqActiveObjects::instance().activeView());
+        if (!rep)
+        {
+          continue;
+        }
+          pqPipelineRepresentation *pipelineRepresentation =
+              qobject_cast<pqPipelineRepresentation *>(rep);
+        if (!pipelineRepresentation)
+        {
+          continue;
+        }
+        pipelineRepresentation->getProxy()->UpdatePropertyInformation();
+
+        vtkSMDoubleVectorProperty *prop =
+            vtkSMDoubleVectorProperty::SafeDownCast(
+                pipelineRepresentation->getProxy()->GetProperty(
+                    "AmbientColor"));
+        prop->SetElement(0, red);
+        prop->SetElement(1, green);
+        prop->SetElement(2, blue);
+        pipelineRepresentation->getProxy()->UpdateVTKObjects();
+        pipelineRepresentation->updateHelperProxies();
+        pqActiveObjects::instance().activeView()->forceRender();
+    }
+  }
+}
 }
 }
 }
\ No newline at end of file
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/PeaksWidget.cpp b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/PeaksWidget.cpp
index 33aaf8f0aa1178662246bfc7a61dbb9a45af39a7..e70f9497873d16d93e8dd085eebdfdf5fe026842 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/PeaksWidget.cpp
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/PeaksWidget.cpp
@@ -21,7 +21,7 @@ Constructor
 */
 PeaksWidget::PeaksWidget(Mantid::API::IPeaksWorkspace_sptr ws,
                          const std::string &coordinateSystem, QWidget *parent)
-    : QWidget(parent), m_ws(ws), m_coordinateSystem(coordinateSystem) {
+    : QWidget(parent), m_ws(ws), m_coordinateSystem(coordinateSystem), m_originalTableWidth(1) {
   ui.setupUi(this);
 }
 
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/RebinAlgorithmDialogProvider.cpp b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/RebinAlgorithmDialogProvider.cpp
index 494f211d022486ca654e544e3fe41bdd52bff83f..611150b1d375a770586d86ab8e7ce69608a179d5 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/RebinAlgorithmDialogProvider.cpp
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/RebinAlgorithmDialogProvider.cpp
@@ -25,6 +25,8 @@
 #include <QHash>
 #include "boost/shared_ptr.hpp"
 
+using namespace MantidQt::MantidWidgets;
+
 namespace Mantid
 {
   namespace Vates
@@ -37,10 +39,11 @@ namespace Mantid
       Mantid::Kernel::Logger g_log("RebinAlgorithmDialogProvider");
     }
 
+      const size_t RebinAlgorithmDialogProvider::BinCutOffValue = 50;
+
       RebinAlgorithmDialogProvider::RebinAlgorithmDialogProvider(QWidget* parent) : 
                                                     m_lblInputWorkspace("InputWorkspace"),
                                                     m_lblOutputWorkspace("OutputWorkspace"),
-                                                    m_binCutOffValue(50),
                                                     m_parent(parent)
       {
       }
@@ -82,7 +85,7 @@ namespace Mantid
        * @param workspaceName The name of the input workspace.
        * @returns A pointer to the current event workspace
        */
-      Mantid::API::IMDEventWorkspace_sptr RebinAlgorithmDialogProvider::getWorkspace(std::string workspaceName)
+      Mantid::API::IMDEventWorkspace_sptr RebinAlgorithmDialogProvider::getWorkspace(const std::string& workspaceName)
       {
         Mantid::API::IMDEventWorkspace_sptr eventWorkspace;
 
@@ -129,9 +132,9 @@ namespace Mantid
        * @returns The algorithm dialog
        */
       MantidQt::API::AlgorithmDialog* RebinAlgorithmDialogProvider::createDialog(Mantid::API::IAlgorithm_sptr algorithm,
-                                                                 std::string inputWorkspace,
-                                                                 std::string outputWorkspace,
-                                                                 std::string algorithmType)
+                                                                 const std::string& inputWorkspace,
+                                                                 const std::string& outputWorkspace,
+                                                                 const std::string& algorithmType)
       {
         QHash<QString, QString> presets;
        //Check if a workspace is selected in the dock and set this as a preference for the input workspace
@@ -140,21 +143,12 @@ namespace Mantid
 
         MantidQt::API::AlgorithmDialog* dialog = NULL;
 
-        // Set the correct algorithm dialog, Add CutMD here once it is ready.
-        if (algorithmType == "BinMD")
-        {
-          dialog = new MantidQt::MantidWidgets::BinMDDialog(m_parent);
-          getPresetsForSliceMDAlgorithmDialog(inputWorkspace, outputWorkspace, presets);
-        }
-        else if (algorithmType == "SliceMD")
-        {
-          dialog = new MantidQt::MantidWidgets::SliceMDDialog(m_parent);
-          getPresetsForSliceMDAlgorithmDialog(inputWorkspace, outputWorkspace, presets);
-        }
-        else
-        {
-          return dialog;
-        }
+        
+        MantidQt::API::InterfaceManager interfaceManager;
+        presets.insert(m_lblInputWorkspace, QString::fromStdString(inputWorkspace));
+        presets.insert(m_lblOutputWorkspace, QString::fromStdString(outputWorkspace));
+
+        dialog = interfaceManager.createDialogFromName(QString::fromStdString(algorithmType), -1, m_parent, false, presets);
 
         // The parent so that the dialog appears on top of it
         dialog->setParent(m_parent);
@@ -166,48 +160,18 @@ namespace Mantid
         flags |= Qt::WindowContextHelpButtonHint;
         dialog->setWindowFlags(flags);
 
-        dialog->setAlgorithm(algorithm);
-        dialog->setPresetValues(presets);
-        dialog->setOptionalMessage(QString(algorithm->summary().c_str()));
-
-        MantidQt::MantidWidgets::BinMDDialog * binDialog = dynamic_cast<MantidQt::MantidWidgets::BinMDDialog *>(dialog);
-        MantidQt::MantidWidgets::SliceMDDialog * sliceDialog = dynamic_cast<MantidQt::MantidWidgets::SliceMDDialog *>(dialog);
-
-
-        if (binDialog)
+        if (SlicingAlgorithmDialog * slicingDialog = dynamic_cast<SlicingAlgorithmDialog *>(dialog))
         {
-          binDialog->initializeLayout();
-          binDialog->customiseLayoutForVsi(inputWorkspace);
+    
+          slicingDialog->customiseLayoutForVsi(inputWorkspace);
 
           // Setup the values of the axis dimensions
-          setAxisDimensions(binDialog, inputWorkspace);
-        }
-        else if (sliceDialog)
-        {
-          sliceDialog->initializeLayout();
-          sliceDialog->customiseLayoutForVsi(inputWorkspace);
-
-         // Setup the values of the axis dimensions
-          setAxisDimensions(sliceDialog, inputWorkspace);
+          setAxisDimensions(slicingDialog, inputWorkspace);
         }
 
         return dialog;
       }
 
-      /**
-        * Determine the preset values 
-        * @param inputWorkspace The name of the input workspace.
-        * @param outputWorkspace The name of the output workspace.
-        * @param presets A container for the preset values.
-        */
-      void RebinAlgorithmDialogProvider::getPresetsForSliceMDAlgorithmDialog(std::string inputWorkspace, std::string outputWorkspace, QHash<QString, QString>& presets)
-      {
-        // Set the input workspace
-        presets.insert(QString(m_lblInputWorkspace),QString::fromStdString(inputWorkspace));
-
-        // Set the output workspace
-        presets.insert(QString(m_lblOutputWorkspace),QString::fromStdString(outputWorkspace));
-      }
 
       /**
        * Resets the aligned dimensions properties in a SlicingAlgorithmDialog.
@@ -232,12 +196,12 @@ namespace Mantid
 
           // Check the bins size
           QString newNumberOfBins;
-          if (numberOfBins < m_binCutOffValue && index < 3)
+          if (numberOfBins < BinCutOffValue && index < 3)
           {
             // Only do this for BinMD, it is too costly for SliceMD to have very large cuts
             if (dynamic_cast<MantidQt::MantidWidgets::BinMDDialog *>(dialog))
             {
-              newNumberOfBins = QString::number(static_cast<unsigned long long>(m_binCutOffValue));
+              newNumberOfBins = QString::number(static_cast<unsigned long long>(BinCutOffValue));
             }
             else
             {
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/RebinnedSourcesManager.cpp b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/RebinnedSourcesManager.cpp
index 19dda8218a3876aac992014e27710638b1742a96..b7e54f944db15f908213287b56490016c2d38420 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/RebinnedSourcesManager.cpp
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/RebinnedSourcesManager.cpp
@@ -51,9 +51,10 @@ namespace Mantid
       Mantid::Kernel::Logger g_log("RebinnedSourcesManager");
     }
 
-      RebinnedSourcesManager::RebinnedSourcesManager(QWidget* parent) : QWidget(parent), m_tempPostfix("_tempvsi"), m_tempPrefix("__")
+      RebinnedSourcesManager::RebinnedSourcesManager(QWidget* parent) : QWidget(parent), m_tempPostfix("_rebinned_vsi"), m_tempPrefix(""), m_inputSource(NULL), m_rebinnedSource(NULL)
       {
         observeAdd();
+        observeAfterReplace();
         observePreDelete();
       }
 
@@ -68,7 +69,15 @@ namespace Mantid
        */
       void RebinnedSourcesManager::addHandle(const std::string &workspaceName, Mantid::API::Workspace_sptr workspace)
       {
-        if (m_rebinnedWorkspaceToOriginalWorkspace.count(workspaceName) > 0 || m_rebinnedWorkspaceToRebinnedWorkspace.count(workspaceName) > 0)
+        // Check if the workspace which has experienced a change is being tracked in our buffer
+        if (m_newWorkspacePairBuffer.size() == 0)
+        {
+          return;
+        }
+
+        std::string outputWorkspace = m_newWorkspacePairBuffer.begin()->second.first;
+
+        if (outputWorkspace == workspaceName)
         {
           std::string sourceType;
           Mantid::API::IMDEventWorkspace_sptr eventWorkspace = boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(workspace);
@@ -97,44 +106,40 @@ namespace Mantid
        */
       void RebinnedSourcesManager::preDeleteHandle(const std::string &wsName, const boost::shared_ptr<Mantid::API::Workspace>)
       {
-        // If the original workspace has been deleted, then delete the rebinned
-        // source (and workspace via the listener)
-        if (m_originalWorkspaceToRebinnedWorkspace.count(wsName))
-        {
-          // Get the rebinned source and destroy the entire pipeline
-          pqPipelineSource* source = getSourceForWorkspace(m_originalWorkspaceToRebinnedWorkspace[wsName]);
+        // Check if the workspace which is to be deleted is a tracked rebinned workspace
+        std::vector<pqPipelineSource*> sources = findAllRebinnedSourcesForWorkspace(wsName);
 
-          // Go to the end of the pipeline
-          while(source->getNumberOfConsumers() > 0)
-          {
-            source = source->getConsumer(0);
-          }
-
-          //Destroy the pipeline from the end
-          pqObjectBuilder* builder = pqApplicationCore::instance()->getObjectBuilder();
-          pqPipelineFilter* filter = qobject_cast<pqPipelineFilter*>(source);
-
-          while (filter)
-          {
-            source = filter->getInput(0);
-            builder->destroy(filter);
-            filter = qobject_cast<pqPipelineFilter*>(source);
-          }
+        for (std::vector<pqPipelineSource *>::const_iterator it = sources.begin(); it != sources.end(); ++it)
+        {
+          // Untrack the source
+          untrackWorkspaces(createKeyPairForSource(*it));
 
-          builder->destroy(source); // The listener takes now care of the workspace.
-          untrackWorkspaces(m_originalWorkspaceToRebinnedWorkspace[wsName]);
+          // Delete pipeline
+          removePipeline(*it);
         }
       }
 
+      /**
+       * Catch a change of a workspace
+       * @param workspaceName Name of the workspace.
+       * @param workspace A pointer to the added workspace.
+       */
+      void RebinnedSourcesManager::afterReplaceHandle(const std::string &workspaceName, const boost::shared_ptr<Mantid::API::Workspace> workspace)
+      {
+        addHandle(workspaceName, workspace);
+      }
+
       /**
        * Check if the sources are valid.
-       * @param source The pipeline source.
+       * @param src The pipeline source.
        * @param inputWorkspace Reference for the name of the input workspace.
        * @param outputWorkspace Reference for the name of the output workspace.
        * @param algorithmType The type of the algorithm which will be used to create the rebinned source.
        */
-      void RebinnedSourcesManager::checkSource(pqPipelineSource* source, std::string& inputWorkspace, std::string& outputWorkspace, std::string algorithmType)
+      void RebinnedSourcesManager::checkSource(pqPipelineSource* src, std::string& inputWorkspace, std::string& outputWorkspace, std::string algorithmType)
       {
+        pqPipelineSource* source = goToPipelineBeginning(src);
+
         std::string workspaceName;
         std::string workspaceType;
 
@@ -146,7 +151,7 @@ namespace Mantid
         // Check if it is a Histo or Event workspace, if it is neither, then don't do anything
         if (isHistoWorkspace || isEventWorkspace)
         {
-          processWorkspaceNames(inputWorkspace, outputWorkspace, workspaceName, algorithmType);
+          processWorkspaceNames(inputWorkspace, outputWorkspace, source, workspaceName, algorithmType);
         }
       }
 
@@ -179,11 +184,10 @@ namespace Mantid
           filter = qobject_cast<pqPipelineFilter*>(source);
         }
 
-        proxy = source->getProxy();
-
         // Ensure that the source is either an MDEvent source or an MDHisto source
-        if (!QString(proxy->GetXMLName()).contains("MDEW Source") &&
-            !QString(proxy->GetXMLName()).contains("MDHW Source"))
+        std::string sourceName(source->getProxy()->GetXMLName());
+        if (sourceName.find("MDEW Source") == std::string::npos &&
+            sourceName.find("MDHW Source") == std::string::npos)
         {
           return;
         }
@@ -192,43 +196,27 @@ namespace Mantid
         workspaceName = vtkSMPropertyHelper(source->getProxy(), "WorkspaceName", true).GetAsString();
 
         workspaceType = vtkSMPropertyHelper(source->getProxy(), "WorkspaceTypeName", true).GetAsString();
-
       }
 
       /**
        * Creates the pipeline for the rebinned source.
-       * @param rebinnedSource The name of the rebinned source.
-       * @param sourceToBeDeleted The name of the sources which needs to be removed from the pipeline browser.
        */
-      void RebinnedSourcesManager::repipeRebinnedSource(std::string rebinnedSource, std::string& sourceToBeDeleted)
+      void RebinnedSourcesManager::repipeRebinnedSource()
       {
-        // We need to check if the source from which we receive our filters is the original source or 
-        // a rebinned source.
-        if (m_rebinnedWorkspaceToRebinnedWorkspace.count(rebinnedSource) == 0)
-        {
-          std::string originalSource = m_rebinnedWorkspaceToOriginalWorkspace[rebinnedSource];
-
-          // Swap with the original source
-          swapSources(originalSource, rebinnedSource);
-
-          sourceToBeDeleted = originalSource;
-        }
-        else
-        {
-          std::string oldRebinnedSource = m_rebinnedWorkspaceToRebinnedWorkspace[rebinnedSource];
-          std::string originalSource = m_rebinnedWorkspaceToOriginalWorkspace[oldRebinnedSource];
+       swapSources(m_inputSource, m_rebinnedSource);
 
-          // Swap with the other rebinned source
-          swapSources(oldRebinnedSource, rebinnedSource);
-          
-          sourceToBeDeleted = oldRebinnedSource;
+       // If we had been dealing with rebinning a rebinned workspace and changing the algorithm,
+       // e.g. when changing from BinMD to SliceMD, then we need to untrack the old, rebinned
+       // workspace
+       if (m_newRebinnedWorkspacePairBuffer.size() > 0)
+       {
+         untrackWorkspaces(createKeyPairForSource(m_inputSource));
+       }
 
-          m_originalWorkspaceToRebinnedWorkspace.insert(std::pair<std::string, std::string>(originalSource, rebinnedSource));
-          m_rebinnedWorkspaceToOriginalWorkspace.insert(std::pair<std::string, std::string>(rebinnedSource, originalSource));
+       m_newRebinnedWorkspacePairBuffer.clear();
+       m_newWorkspacePairBuffer.clear();
 
-          // Unregister the connection between the two rebinned sources.
-          m_rebinnedWorkspaceToRebinnedWorkspace.erase(rebinnedSource);
-        }
+       deleteSpecificSource(m_inputSource);
       }
 
       /**
@@ -236,25 +224,27 @@ namespace Mantid
        * @param rebinnedSource The name of the rebinned source.
        * @param originalSource The name of the original source.
        */
-      void RebinnedSourcesManager::repipeOriginalSource(std::string rebinnedSource, std::string originalSource)
+      void RebinnedSourcesManager::repipeOriginalSource(pqPipelineSource* rebinnedSource, pqPipelineSource* originalSource)
       {
+        // Advance the rebinnedSource to the start of the pipeline
+        pqPipelineSource* rebSource = goToPipelineBeginning(rebinnedSource);
+
         // Swap source from rebinned source to original source.
-        swapSources(rebinnedSource, originalSource);
+        swapSources(rebSource, originalSource);
+
+        // Untrack the sources
+        untrackWorkspaces(createKeyPairForSource(rebSource));
 
-        m_originalWorkspaceToRebinnedWorkspace.erase(originalSource);
-        m_rebinnedWorkspaceToOriginalWorkspace.erase(rebinnedSource);
+        deleteSpecificSource(rebSource);
       }
 
       /**
        * Swap the sources at the bottom level of the pipeline.
-       * @param source1 First source.
-       * @param source2 Second source.
+       * @param src1 First source.
+       * @param src2 Second source.
        */
-      void RebinnedSourcesManager::swapSources(std::string source1, std::string source2)
+      void RebinnedSourcesManager::swapSources(pqPipelineSource* src1, pqPipelineSource* src2)
       {
-        pqPipelineSource* src1= getSourceForWorkspace(source1);
-        pqPipelineSource* src2 = getSourceForWorkspace(source2);
-
         if (!src1 || !src2)
         {
           throw std::runtime_error("VSI error: Either the original or rebinned source don't seem to exist.");
@@ -279,217 +269,153 @@ namespace Mantid
 
       /**
        * Get the stored workspace names assoicated with a source.
-       * @param source The name of the source.
+       * @param src The name of the source.
        * @param originalWorkspaceName The name of the original workspace.
        * @param rebinnedWorkspaceName The name of the rebinned workspace.
        */
-      void RebinnedSourcesManager::getStoredWorkspaceNames(pqPipelineSource* source, std::string& originalWorkspaceName, std::string& rebinnedWorkspaceName)
+      void RebinnedSourcesManager::getStoredWorkspaceNames(pqPipelineSource* src, std::string& originalWorkspaceName, std::string& rebinnedWorkspaceName)
       {
-        if (!source)
+        if (!src)
         {
           return;
         }
 
-        // Get the underlying workspace name and type
-        std::string workspaceName;
-        std::string workspaceType;
-        getWorkspaceInfo(source, workspaceName, workspaceType);
+        pqPipelineSource* source = goToPipelineBeginning(src);
+
+        // Get the key pair which contains the name of the rebinned workspace and the source name
+        std::pair<std::string, std::string> key = createKeyPairForSource(source);
+        rebinnedWorkspaceName = key.first;
 
-        // The input can either be a rebinned source or a 
-        if (m_rebinnedWorkspaceToOriginalWorkspace.count(workspaceName) > 0)
+        if (m_rebinnedWorkspaceAndSourceToOriginalWorkspace.count(key) > 0 )
         {
-          originalWorkspaceName = m_rebinnedWorkspaceToOriginalWorkspace[workspaceName];
-          rebinnedWorkspaceName = workspaceName;
-        } else if (m_originalWorkspaceToRebinnedWorkspace.count(workspaceName) > 0)
+          originalWorkspaceName = m_rebinnedWorkspaceAndSourceToOriginalWorkspace[key];
+        }
+        else
         {
-          originalWorkspaceName = workspaceName;
-          rebinnedWorkspaceName = m_originalWorkspaceToRebinnedWorkspace[workspaceName];
+          originalWorkspaceName  = "";
         }
       }
 
       /**
-       * Get the desired source
+       * Get all sources which are linked to the workspace which is to be deleted. The workspace
+       * can be a rebinned workspace or an unrebinned workspace.
        * @param workspaceName The workspace name associated with the source.
+       * @returns a list with all tracked (true sources) which are associated with the workspace
        */
-      pqPipelineSource* RebinnedSourcesManager::getSourceForWorkspace(std::string workspaceName)
+      std::vector<pqPipelineSource*> RebinnedSourcesManager::findAllRebinnedSourcesForWorkspace(std::string workspaceName)
       {
+        std::vector<std::string> linkedSources;
+        // We need to iterate over the map
+        for (std::map<std::pair<std::string, std::string>, std::string>::const_iterator it = m_rebinnedWorkspaceAndSourceToOriginalWorkspace.begin();
+             it != m_rebinnedWorkspaceAndSourceToOriginalWorkspace.begin(); ++it)
+        {
+          // Check the first part of the key and the value ofthe map
+          std::string rebinnedWorkspaceName = it->first.first;
+          std::string originalWorkspaceName = it->second;
+
+          if (workspaceName == rebinnedWorkspaceName || workspaceName == originalWorkspaceName)
+          {
+            linkedSources.push_back(it->first.second);
+          }
+        }
+
+        // Now that we have the sources it is time to get them from the ParaView server
+        std::vector<pqPipelineSource*> sourcesToBeDeleted;
+
         pqServer *server = pqActiveObjects::instance().activeServer();
         pqServerManagerModel *smModel = pqApplicationCore::instance()->getServerManagerModel();
-        QList<pqPipelineSource *> sources;
-        QList<pqPipelineSource *>::Iterator source;
-        sources = smModel->findItems<pqPipelineSource *>(server);
+        QList<pqPipelineSource *> sources = smModel->findItems<pqPipelineSource *>(server);
 
-        for (source = sources.begin(); source != sources.end(); ++source)
+        for (QList<pqPipelineSource*>::Iterator source = sources.begin(); source != sources.end(); ++source)
         {
-
           pqPipelineFilter* filter = qobject_cast<pqPipelineFilter*>(*source);
-
           if (!filter)
           {
-            std::string wsName(vtkSMPropertyHelper((*source)->getProxy(),
-                                                  "WorkspaceName", true).GetAsString());
-            if (!wsName.empty())
+            std::string sourceName((*source)->getProxy()->GetGlobalIDAsString());
+
+            if (doesSourceNeedToBeDeleted(sourceName, linkedSources))
             {
-              if (wsName == workspaceName)
-              {
-                return (*source);
-              }
+              sourcesToBeDeleted.push_back(*source);
             }
           }
         }
-        return NULL;
+
+        return sourcesToBeDeleted;
+      }
+
+      /**
+       * Check if a source is being tracked and hence needs to be deleted
+       * @param sourceName the name of the source which we want to check
+       * @param trackedSources a list of tracked sources which need to be deleted
+       */
+      bool RebinnedSourcesManager::doesSourceNeedToBeDeleted(std::string sourceName, std::vector<std::string> trackedSources)
+      {
+        for (std::vector<std::string>::iterator it = trackedSources.begin(); it != trackedSources.end(); ++it)
+        {
+          if (!sourceName.empty() && *it == sourceName)
+          {
+            return true;
+          }
+        }
+
+        return false;
       }
 
       /**
        * Process the workspaces names for the original source and the input source
        * @param inputWorkspace Reference to the input workpspace.
        * @param outputWorkspace Reference to the output workspace.
+       * @param source A pointer to the original source
        * @param workspaceName The name of the workspace of the current source.
        * @param algorithmType The algorithm which creates the rebinned source.
        */
-      void RebinnedSourcesManager::processWorkspaceNames(std::string& inputWorkspace, std::string& outputWorkspace, std::string workspaceName, std::string algorithmType)
+      void RebinnedSourcesManager::processWorkspaceNames(std::string& inputWorkspace, std::string& outputWorkspace, pqPipelineSource* source,  std::string workspaceName, std::string algorithmType)
       {
-        // If the workspace is the original workspace
-        if (workspaceName.find(m_tempPostfix) == std::string::npos)
+        // Reset the temporary tracking elements, which are needed only for the duration of the rebinning itself
+        m_newWorkspacePairBuffer.clear();
+        m_newRebinnedWorkspacePairBuffer.clear();
+        m_inputSource = NULL;
+        m_rebinnedSource = NULL;
+
+        // If the workspace is the original workspace or it is a freshly loaded, i.e. it is not being tracked
+        if (workspaceName.find(m_tempPostfix) == std::string::npos || !isRebinnedSourceBeingTracked(source))
         {
           inputWorkspace = workspaceName;
           outputWorkspace =  m_tempPrefix + workspaceName + algorithmType + m_tempPostfix;
-
-          // Record the workspace
-          m_originalWorkspaceToRebinnedWorkspace.insert(std::pair<std::string, std::string>(inputWorkspace, outputWorkspace));
-          m_rebinnedWorkspaceToOriginalWorkspace.insert(std::pair<std::string, std::string>(outputWorkspace, inputWorkspace));
         } // If the workspace is rebinned and was created with the same algorithm as the currently selected one.
-        else if (workspaceName.find(algorithmType) != std::string::npos) 
+        else if (workspaceName.find(algorithmType) != std::string::npos && workspaceName.find(m_tempPostfix) != std::string::npos) 
         {
-          if (m_rebinnedWorkspaceToOriginalWorkspace.count(workspaceName) > 0)
+          // Check if the source and the workspace name are being tracked already
+          if (isRebinnedSourceBeingTracked(source))
           {
-            inputWorkspace = m_rebinnedWorkspaceToOriginalWorkspace[workspaceName];
+            inputWorkspace = m_rebinnedWorkspaceAndSourceToOriginalWorkspace[createKeyPairForSource(source)];
             outputWorkspace = workspaceName;
           }
         }
         else // If the workspace is rebinned but was not created with the same algorithm as the currently selected one.
         {
-          if (m_rebinnedWorkspaceToOriginalWorkspace.count(workspaceName) > 0)
+          if (isRebinnedSourceBeingTracked(source))
           {
-            inputWorkspace = m_rebinnedWorkspaceToOriginalWorkspace[workspaceName];
+            inputWorkspace = m_rebinnedWorkspaceAndSourceToOriginalWorkspace[createKeyPairForSource(source)];
             outputWorkspace = m_tempPrefix + inputWorkspace + algorithmType + m_tempPostfix;
-
-            // Map the new rebinned workspace name to the old rebinned workspace name
-            m_rebinnedWorkspaceToRebinnedWorkspace.insert(std::pair<std::string, std::string>(outputWorkspace, workspaceName));
+            // Keep track of the old rebinned workspace and source
+            m_newRebinnedWorkspacePairBuffer.insert(std::pair<std::string, std::pair<std::string, pqPipelineSource*>>(workspaceName, std::pair<std::string, pqPipelineSource*>(outputWorkspace, source)));
           }
         }
+        // Record the workspaces
+        m_newWorkspacePairBuffer.insert(std::pair<std::string, std::pair<std::string, pqPipelineSource*>>(inputWorkspace, std::pair<std::string, pqPipelineSource*>(outputWorkspace, source)));
+        m_inputSource= source;
       }
 
       /**
        * Stop keeping tabs on the specific workspace pair
-       * @param rebinnedWorkspace The name of the rebinned workspace.
-       */
-      void RebinnedSourcesManager::untrackWorkspaces(std::string rebinnedWorkspace)
-      {
-        std::string originalWorkspace = m_rebinnedWorkspaceToOriginalWorkspace[rebinnedWorkspace];
-
-        // Remove the mapping ofthe rebinned workspace to the original workspace.
-        if (m_rebinnedWorkspaceToOriginalWorkspace.count(rebinnedWorkspace) > 0)
-        {
-          m_rebinnedWorkspaceToOriginalWorkspace.erase(rebinnedWorkspace);
-        }
-
-        // Remove the mapping of the original workspace to the rebinned workspace, if the mapping is still intact.
-        if (m_originalWorkspaceToRebinnedWorkspace.count(originalWorkspace) > 0 && m_originalWorkspaceToRebinnedWorkspace[originalWorkspace] == rebinnedWorkspace)
-        {
-          m_originalWorkspaceToRebinnedWorkspace.erase(originalWorkspace);
-        }
-      }
-
-      /**
-       * Register the rebinned source. Specifically, connect to the destroyed signal of the rebinned source.
-       * @param source The rebinned source.
-       */
-      void RebinnedSourcesManager::registerRebinnedSource(pqPipelineSource* source)
-      {
-        if (!source)
-        {
-          return;
-        }
-
-        QObject::connect(source, SIGNAL(destroyed()),
-                         this, SLOT(onRebinnedSourceDestroyed()));
-      }
-
-      /**
-       * React to the deletion of a rebinned source.
+       * @param key a key to the tracking map
        */
-      void RebinnedSourcesManager::onRebinnedSourceDestroyed()
+      void RebinnedSourcesManager::untrackWorkspaces(std::pair<std::string, std::string> key)
       {
-        removeUnusedRebinnedWorkspaces();
-      }
-
-      /**
-       * Remove unused rebinned workspaces, by comparing the workspaces against the sources.
-       */
-      void RebinnedSourcesManager::removeUnusedRebinnedWorkspaces()
-      {
-        // Iterate through all workspaces and check for ones ending with the tempIdentifier
-        std::set<std::string> workspaceNames = Mantid::API::AnalysisDataService::Instance().getObjectNamesInclHidden();
-  
-        for (std::set<std::string>::iterator it = workspaceNames.begin(); it != workspaceNames.end(); ++it)
+        if (m_rebinnedWorkspaceAndSourceToOriginalWorkspace.count(key) > 0)
         {
-          // Only look at the rebinned files
-          if (it->find(m_tempPostfix) != std::string::npos)
-          {
-              compareToSources(*it);
-          }
-        }
-      }
-
-       /**
-        * Compare if the workspace name exists among the sources. If it doesnt't exist, remove it.
-        * @param workspaceName The name of the workspace
-        */
-       void RebinnedSourcesManager::compareToSources(std::string workspaceName)
-       {
-          pqServer *server = pqActiveObjects::instance().activeServer();
-          pqServerManagerModel *smModel = pqApplicationCore::instance()->getServerManagerModel();
-          QList<pqPipelineSource *> sources = smModel->findItems<pqPipelineSource *>(server);
-
-          for (QList<pqPipelineSource *>::Iterator source = sources.begin(); source != sources.end(); ++source)
-          {
-            const QString srcProxyName = (*source)->getProxy()->GetXMLGroup();
-
-            if (srcProxyName == QString("sources"))
-            {
-              std::string name(vtkSMPropertyHelper((*source)->getProxy(),
-                                                    "WorkspaceName", true).GetAsString());
-
-              // If the rebinned workspace has a source equivalent, then exit
-              if (name==workspaceName)
-              {
-                return;
-              }
-            }
-          }
-
-          // There is no source which corresponds to the workspace, hence delete and unregister the workspace.
-          removeRebinnedWorkspace(workspaceName);
-          untrackWorkspaces(workspaceName);
-       }
-
-      /**
-        * Removes the rebinned workspace from memory.
-        * @param rebinnedWorkspace The name of the rebinned workspace.
-        */
-      void RebinnedSourcesManager::removeRebinnedWorkspace(std::string rebinnedWorkspace)
-      {
-        Mantid::VATES::ADSWorkspaceProvider<Mantid::API::IMDHistoWorkspace> adsHistoWorkspaceProvider;
-        Mantid::VATES::ADSWorkspaceProvider<Mantid::API::IMDEventWorkspace> adsEventWorkspaceProvider;
-
-        if (adsHistoWorkspaceProvider.canProvideWorkspace(rebinnedWorkspace))
-        {
-          adsHistoWorkspaceProvider.disposeWorkspace(rebinnedWorkspace);
-        }
-        else if (adsEventWorkspaceProvider.canProvideWorkspace(rebinnedWorkspace))
-        {
-          adsEventWorkspaceProvider.disposeWorkspace(rebinnedWorkspace);
+          m_rebinnedWorkspaceAndSourceToOriginalWorkspace.erase(key);
         }
       }
 
@@ -635,12 +561,133 @@ namespace Mantid
       }
 
       /**
-       * Check if we have a rebinned source
-       * @param name The source name.
+       * Register the rebinned source. Specifically, connect to the destroyed signal of the rebinned source.
+       * @param source The rebinned source.
+       */
+      void RebinnedSourcesManager::registerRebinnedSource(pqPipelineSource* source)
+      {
+        if (!source)
+        {
+          return;
+        }
+
+        // Make sure that the underlying source is associated with the buffered workspace pair and register it
+        try
+        {
+          // Add entry to map from (rebinnedWsName, rebinnedSourceName) -> (originalWsName)
+          if (m_newWorkspacePairBuffer.size() != 1)
+          {
+            throw std::runtime_error("Original source for rebinned source could not be found.");
+          }
+
+          std::string originalWorkspaceName = m_newWorkspacePairBuffer.begin()->first;
+          std::string rebinnedWorkspaceName = m_newWorkspacePairBuffer.begin()->second.first;
+
+          std::pair<std::string, std::string> key = std::pair<std::string, std::string>(rebinnedWorkspaceName, getSourceName(source));
+          m_rebinnedWorkspaceAndSourceToOriginalWorkspace.insert(std::pair<std::pair<std::string, std::string>, std::string>(key, originalWorkspaceName));
+
+          // Record the rebinned source
+          m_rebinnedSource = source;
+        }
+        catch (std::runtime_error &ex)
+        {
+          g_log.warning() << ex.what(); 
+        }
+
+        QObject::connect(source, SIGNAL(destroyed()),
+                         this, SLOT(onRebinnedSourceDestroyed()));
+      }
+
+      /**
+       * React to the deletion of a rebinned source. We need to make sure that the source is untracked
+       */
+      void RebinnedSourcesManager::onRebinnedSourceDestroyed()
+      {
+        pqServer *server = pqActiveObjects::instance().activeServer();
+        pqServerManagerModel *smModel = pqApplicationCore::instance()->getServerManagerModel();
+        QList<pqPipelineSource *> sources = smModel->findItems<pqPipelineSource *>(server);
+
+        std::vector<std::pair<std::string, std::string>> toBeUntracked;
+
+        // Compare all registered sources to all loaded sources,
+        for (std::map<std::pair<std::string, std::string>, std::string>::iterator it = m_rebinnedWorkspaceAndSourceToOriginalWorkspace.begin();
+             it != m_rebinnedWorkspaceAndSourceToOriginalWorkspace.end(); ++it)
+        {
+          std::string registeredSourceName = it->first.second;
+
+          QList<pqPipelineSource*>::Iterator source = sources.begin();
+
+          // Find the source which matches the registered source
+          while(source != sources.end())
+          {
+            if (registeredSourceName == getSourceName(*source))
+            {
+              break;
+            }
+            ++source;
+          }
+
+          // If there was no matching source then mark it to be untracked
+          if (source == sources.end())
+          {
+            toBeUntracked.push_back(it->first);
+          }
+        }
+
+        // Finally untrack all sources which need it
+        for (std::vector<std::pair<std::string, std::string>>::iterator key = toBeUntracked.begin(); key != toBeUntracked.end(); ++key)
+        {
+          untrackWorkspaces(*key);
+        }
+      }
+
+      /**
+       * Remove the pipeline
        */
-      bool RebinnedSourcesManager::isRebinnedSource(std::string name)
+      void RebinnedSourcesManager::removePipeline(pqPipelineSource* source)
       {
-        if (m_rebinnedWorkspaceToOriginalWorkspace.count(name) > 0)
+        // Go to the end of the pipeline
+        while(source->getNumberOfConsumers() > 0)
+        {
+          source = source->getConsumer(0);
+        }
+
+        //Destroy the pipeline from the end
+        pqObjectBuilder* builder = pqApplicationCore::instance()->getObjectBuilder();
+        pqPipelineFilter* filter = qobject_cast<pqPipelineFilter*>(source);
+
+        while (filter)
+        {
+          source = filter->getInput(0);
+          builder->destroy(filter);
+          filter = qobject_cast<pqPipelineFilter*>(source);
+        }
+
+        builder->destroy(source); // The listener takes now care of the workspace.
+      }
+
+      /**
+       * Gets the source name
+       * @param source A pointer to a source
+       * @returns the name of the source
+       */
+      std::string RebinnedSourcesManager::getSourceName(pqPipelineSource* source)
+      {
+        return std::string(source->getProxy()->GetGlobalIDAsString());
+      }
+
+      /**
+       * Check if a rebinned source is being tracked.
+       * @param src A pointer to a source
+       * @returns if it is being tracked or not
+       */
+      bool RebinnedSourcesManager::isRebinnedSourceBeingTracked(pqPipelineSource* src)
+      {
+        pqPipelineSource* source = goToPipelineBeginning(src);
+
+        std::pair<std::string, std::string> key = createKeyPairForSource(source);
+
+        if (m_rebinnedWorkspaceAndSourceToOriginalWorkspace.count(key) > 0)
         {
           return true;
         }
@@ -650,6 +697,74 @@ namespace Mantid
         }
       }
 
+      /**
+       * Construct a workspaceName, sourceName key pair for a given source
+       * @param source A pointer to a source
+       * @returns a key which can be used with the tracking map
+       */
+      std::pair<std::string, std::string> RebinnedSourcesManager::createKeyPairForSource(pqPipelineSource* source)
+      {
+        if (!source)
+        {
+          return std::pair<std::string, std::string>("", "");
+        }
+
+        std::string workspaceName = vtkSMPropertyHelper(source->getProxy(), "WorkspaceName", true).GetAsString();
+        return std::pair<std::string, std::string>(workspaceName, getSourceName(source));
+      }
+
+      /**
+       * Delete a specific source and all of its filters. This assumes a linear filter system
+       * @param source A pointer to the source
+       */
+      void RebinnedSourcesManager::deleteSpecificSource(pqPipelineSource* source)
+      {
+        if (NULL != source)
+        {
+          // Go to the end of the source and work your way back
+          pqPipelineSource* tempSource = source;
+
+          while ((tempSource->getAllConsumers()).size() > 0)
+          {
+            tempSource = tempSource->getConsumer(0);
+          }
+
+          // Now delete all filters and the source
+          pqObjectBuilder *builder = pqApplicationCore::instance()->getObjectBuilder();
+
+          // Crawl up to the source level 
+          pqPipelineFilter* filter = qobject_cast<pqPipelineFilter*>(tempSource);
+
+          while (filter)
+          {
+            tempSource = filter->getInput(0);
+            builder->destroy(filter);
+            filter = qobject_cast<pqPipelineFilter*>(tempSource);
+          }
+
+          builder->destroy(tempSource);
+        }
+      }
+
+      /**
+        * Go to the beginning of a pipeline (assuming that it is linear
+        * @param source A pointer to a source
+        * @returns a pointer to the beginning of the pipeline
+        */
+        pqPipelineSource* RebinnedSourcesManager::goToPipelineBeginning(pqPipelineSource* source)
+        {
+          // Crawl up to the beginnign of the pipeline
+          pqPipelineSource* tempSource = source;
+          pqPipelineFilter* filter = qobject_cast<pqPipelineFilter*>(tempSource);
+          while (filter)
+          {
+            tempSource = filter->getInput(0);
+            filter = qobject_cast<pqPipelineFilter*>(tempSource);
+          }
+
+          return tempSource;
+        }
+
     }
   }
 }
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/SaveScreenshotReaction.cpp b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/SaveScreenshotReaction.cpp
index 123ad34afb9a126bac92aa4b64321184ca227ada..05f5c76ed5729da8ab53f48ec25e3ed5b8bc0e5b 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/SaveScreenshotReaction.cpp
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/SaveScreenshotReaction.cpp
@@ -17,6 +17,7 @@
 #include "MantidVatesAPI/vtkImageData_Silent.h"
 #include <vtkPVXMLElement.h>
 #include <vtkSmartPointer.h>
+#include <vtkSMSessionProxyManager.h>
 #include <vtkPVConfig.h>
 
 #if defined(__INTEL_COMPILER)
@@ -108,13 +109,21 @@ void SaveScreenshotReaction::saveScreenshot()
   QSize size = ssDialog.viewSize();
   QString palette = ssDialog.palette();
 
-  // temporarily load the color palette chosen by the user.
-  vtkSmartPointer<vtkPVXMLElement> currentPalette;
-  pqApplicationCore* core = pqApplicationCore::instance();
-  if (!palette.isEmpty())
+  vtkSMSessionProxyManager *pxm =
+      pqActiveObjects::instance().activeServer()->proxyManager();
+  vtkSMProxy *colorPalette = pxm->GetProxy("global_properties", "ColorPalette");
+  vtkSmartPointer<vtkSMProxy> clone;
+  if (colorPalette && !palette.isEmpty())
   {
-    currentPalette.TakeReference(core->getCurrrentPalette());
-    core->loadPalette(palette);
+    // save current property values
+    clone.TakeReference(pxm->NewProxy(colorPalette->GetXMLGroup(),
+                                      colorPalette->GetXMLName()));
+    clone->Copy(colorPalette);
+
+    vtkSMProxy *chosenPalette = pxm->NewProxy("palettes",
+                                              palette.toLatin1().data());
+    colorPalette->Copy(chosenPalette);
+    chosenPalette->Delete();
   }
 
   int stereo = ssDialog.getStereoMode();
@@ -123,19 +132,25 @@ void SaveScreenshotReaction::saveScreenshot()
     pqRenderViewBase::setStereo(stereo);
   }
 
-  SaveScreenshotReaction::saveScreenshot(file,
-                                         size, ssDialog.quality());
+  SaveScreenshotReaction::saveScreenshot(file, size, ssDialog.quality());
 
-  // restore palette.
-  if (!palette.isEmpty())
+  // restore color palette.
+  if (clone)
   {
-    core->loadPalette(currentPalette);
+    colorPalette->Copy(clone);
   }
 
+  // restore stereo
   if (stereo)
   {
     pqRenderViewBase::setStereo(0);
-    core->render();
+  }
+
+  // check if need to render to clear the changes we did
+  // while saving the screenshot.
+  if (clone || stereo)
+  {
+    pqApplicationCore::instance()->render();
   }
 }
 
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/SplatterPlotView.cpp b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/SplatterPlotView.cpp
index bf3661dd8f94d84c5aafb6268049dbef6aac051a..481da4e1f00cbfef96778cd70608b4093be0c50a 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/SplatterPlotView.cpp
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/SplatterPlotView.cpp
@@ -3,6 +3,7 @@
 #include "MantidVatesSimpleGuiViewWidgets/PeaksTableControllerVsi.h"
 #include "MantidAPI/IMDEventWorkspace.h"
 #include "MantidQtAPI/SelectionNotificationService.h"
+#include "MantidQtAPI/MdConstants.h"
 #include "MantidVatesAPI/ADSWorkspaceProvider.h"
 #include "MantidVatesAPI/vtkPeakMarkerFactory.h"
 #include "MantidVatesAPI/ViewFrustum.h"
@@ -25,8 +26,10 @@
 #include <pqServerManagerModel.h>
 #include <vtkDataObject.h>
 #include <vtkProperty.h>
+#include <vtkPVRenderView.h>
 #include <vtkSMDoubleVectorProperty.h>
 #include <vtkSMPropertyHelper.h>
+#include <vtkSMPVRepresentationProxy.h>
 #include <vtkSMSourceProxy.h>
 
 #if defined(__INTEL_COMPILER)
@@ -55,7 +58,7 @@ namespace
 }
 
 
-SplatterPlotView::SplatterPlotView(QWidget *parent) : ViewBase(parent),
+SplatterPlotView::SplatterPlotView(QWidget *parent, RebinnedSourcesManager* rebinnedSourcesManager) : ViewBase(parent, rebinnedSourcesManager),
                                                       m_cameraManager(boost::make_shared<CameraManager>()),
                                                       m_peaksTableController(NULL),
                                                       m_peaksWorkspaceNameDelimiter(";")                         
@@ -134,6 +137,7 @@ void SplatterPlotView::destroyView()
   // Destroy the view.
   pqObjectBuilder *builder = pqApplicationCore::instance()->getObjectBuilder();
   builder->destroy(this->view);
+  pqActiveObjects::instance().setActiveSource(this->origSrc);
 }
 
 pqRenderView* SplatterPlotView::getView()
@@ -145,6 +149,18 @@ void SplatterPlotView::render()
 {
   pqPipelineSource *src = NULL;
   src = pqActiveObjects::instance().activeSource();
+  bool isPeaksWorkspace = this->isPeaksWorkspace(src);
+  // Hedge for two things.
+  // 1. If there is no active source
+  // 2. If we are loading a peak workspace without haveing
+  //    a splatterplot source in place
+  bool isBadInput = !src || (isPeaksWorkspace && this->splatSource == NULL);
+  if (isBadInput)
+  {
+    g_log.warning() << "SplatterPlotView: Could not render source. You are either loading an active source " 
+                    << "or you are loading a peak source without having a splatterplot source in place.\n";
+    return;
+  }
 
   QString renderType = "Points";
   pqObjectBuilder* builder = pqApplicationCore::instance()->getObjectBuilder();
@@ -164,12 +180,11 @@ void SplatterPlotView::render()
     return;
   }
 
-  bool isPeaksWorkspace = this->isPeaksWorkspace(src);
   if (!isPeaksWorkspace)
   {
     this->origSrc = src;
     this->splatSource = builder->createFilter("filters",
-                                              "MantidParaViewSplatterPlot",
+                                              MantidQt::API::MdConstants::MantidParaViewSplatterPlot,
                                               this->origSrc);
     src = this->splatSource;
   }
@@ -206,9 +221,9 @@ void SplatterPlotView::render()
   drep->getProxy()->UpdateVTKObjects();
   if (!isPeaksWorkspace)
   {
-    pqPipelineRepresentation *prep = NULL;
-    prep = qobject_cast<pqPipelineRepresentation*>(drep);
-    prep->colorByArray("signal", vtkDataObject::FIELD_ASSOCIATION_CELLS);
+    vtkSMPVRepresentationProxy::SetScalarColoring(drep->getProxy(), "signal",
+                                                  vtkDataObject::FIELD_ASSOCIATION_CELLS);
+    drep->getProxy()->UpdateVTKObjects();
   }
 
   this->resetDisplay();
@@ -240,6 +255,16 @@ void SplatterPlotView::render()
   }
 
   emit this->triggerAccept();
+  if (vtkSMProxy* viewProxy = this->getView()->getProxy())
+    {
+    vtkSMPropertyHelper helper(viewProxy, "InteractionMode");
+    if (helper.GetAsInt() == vtkPVRenderView::INTERACTION_MODE_2D)
+      {
+      helper.Set(vtkPVRenderView::INTERACTION_MODE_3D);
+      viewProxy->UpdateProperty("InteractionMode",1);
+      this->resetCamera();
+      }
+    }
 }
 
 void SplatterPlotView::renderAll()
@@ -274,14 +299,14 @@ void SplatterPlotView::checkPeaksCoordinates()
   {
 
     int peakViewCoords = vtkSMPropertyHelper(this->origSrc->getProxy(),
-                                             "SpecialCoordinates").GetAsInt();
+                                             MantidQt::API::MdConstants::MantidParaViewSpecialCoordinates).GetAsInt();
     // Make commensurate with vtkPeakMarkerFactory
     peakViewCoords--;
 
     foreach(pqPipelineSource *src, this->peaksSource)
     {
       vtkSMPropertyHelper(src->getProxy(),
-                          "Peak Dimensions").Set(peakViewCoords);
+                          MantidQt::API::MdConstants::PeakDimensions).Set(peakViewCoords);
       src->getProxy()->UpdateVTKObjects();
     }
   }
@@ -290,7 +315,7 @@ void SplatterPlotView::checkPeaksCoordinates()
 void SplatterPlotView::onThresholdButtonClicked()
 {
   pqObjectBuilder* builder = pqApplicationCore::instance()->getObjectBuilder();
-  this->threshSource = builder->createFilter("filters", "Threshold",
+  this->threshSource = builder->createFilter("filters", MantidQt::API::MdConstants::Threshold,
                                              this->splatSource);
   emit this->lockColorControls();
 }
@@ -323,7 +348,7 @@ void SplatterPlotView::onPickModeToggled(bool state)
     {
       src = this->splatSource;
     }
-    this->probeSource = builder->createFilter("filters", "ProbePoint", src);
+    this->probeSource = builder->createFilter("filters", MantidQt::API::MdConstants::ProbePoint, src);
     emit this->triggerAccept();
   }
   else
@@ -350,6 +375,7 @@ void SplatterPlotView::destroyPeakSources()
   QList<pqPipelineSource *> sources;
   QList<pqPipelineSource *>::Iterator source;
   sources = smModel->findItems<pqPipelineSource *>(server);
+
   for (source = sources.begin(); source != sources.end(); ++source)
   {
     if (this->isPeaksWorkspace(*source))
@@ -357,6 +383,7 @@ void SplatterPlotView::destroyPeakSources()
       builder->destroy(*source);
     }
   }
+
   this->peaksSource.clear();
 }
 
@@ -376,7 +403,7 @@ void SplatterPlotView::readAndSendCoordinates()
   {
     // Get coordinate type
     int peakViewCoords = vtkSMPropertyHelper(this->origSrc->getProxy(),
-                                             "SpecialCoordinates").GetAsInt();
+                                             MantidQt::API::MdConstants::MantidParaViewSpecialCoordinates).GetAsInt();
     // Make commensurate with vtkPeakMarkerFactory
     peakViewCoords--;
 
@@ -453,8 +480,7 @@ void SplatterPlotView::onRemovePeaksTable()
 
   if (m_peaksFilter)
   {
-    pqObjectBuilder *builder = pqApplicationCore::instance()->getObjectBuilder();
-    builder->destroy(m_peaksFilter);
+    this->destroyFilter(MantidQt::API::MdConstants::MDPeaksFilter);
   }
 }
 
@@ -482,7 +508,7 @@ void SplatterPlotView::createPeaksFilter()
   // Set the peaks workspace name. We need to trigger accept in order to log the workspace in the filter
   try
   {
-    m_peaksFilter = builder->createFilter("filters","MantidParaViewPeaksFilter", this->splatSource);
+    m_peaksFilter = builder->createFilter("filters",MantidQt::API::MdConstants::MantidParaViewPeaksFilter, this->splatSource);
     QObject::connect(m_peaksFilter, SIGNAL(destroyed()),
                      this, SLOT(onPeaksFilterDestroyed()));
 
@@ -490,14 +516,18 @@ void SplatterPlotView::createPeaksFilter()
     updatePeaksFilter(m_peaksFilter);
 
     // Create point representation of the source and set the point size 
-    const double pointSize = 4;
+    const double pointSize = 2;
     pqDataRepresentation *dataRepresentation  = m_peaksFilter->getRepresentation(this->view);
     vtkSMPropertyHelper(dataRepresentation->getProxy(), "Representation").Set("Points");
     vtkSMPropertyHelper(dataRepresentation->getProxy(), "PointSize").Set(pointSize);
     dataRepresentation->getProxy()->UpdateVTKObjects();
 
-    pqPipelineRepresentation *pipelineRepresentation = qobject_cast<pqPipelineRepresentation*>(dataRepresentation);
-    pipelineRepresentation->colorByArray("signal", vtkDataObject::FIELD_ASSOCIATION_CELLS);
+    if (!this->isPeaksWorkspace(this->origSrc))
+    {
+      vtkSMPVRepresentationProxy::SetScalarColoring(dataRepresentation->getProxy(), "signal",
+                                                  vtkDataObject::FIELD_ASSOCIATION_CELLS);
+      dataRepresentation->getProxy()->UpdateVTKObjects();
+    }
     this->resetDisplay();
     this->setVisibilityListener();
     this->renderAll();
@@ -506,7 +536,7 @@ void SplatterPlotView::createPeaksFilter()
     // Destroy peak filter
     if (m_peaksFilter)
     {
-      builder->destroy(m_peaksFilter);
+      this->destroyFilter(MantidQt::API::MdConstants::MDPeaksFilter);
     }
     g_log.warning() << ex.what();
   }
@@ -582,9 +612,9 @@ void SplatterPlotView::setPeakButton(bool state)
  */
 void SplatterPlotView::setPeakSourceFrame(pqPipelineSource* source)
 {
-  int peakViewCoords = vtkSMPropertyHelper(this->origSrc->getProxy(), "SpecialCoordinates").GetAsInt();
+  int peakViewCoords = vtkSMPropertyHelper(this->origSrc->getProxy(), MantidQt::API::MdConstants::MantidParaViewSpecialCoordinates).GetAsInt();
   peakViewCoords--;
-  vtkSMPropertyHelper(source->getProxy(), "Peak Dimensions").Set(peakViewCoords);
+  vtkSMPropertyHelper(source->getProxy(), MantidQt::API::MdConstants::PeakDimensions).Set(peakViewCoords);
 }
 
 /**
@@ -592,9 +622,9 @@ void SplatterPlotView::setPeakSourceFrame(pqPipelineSource* source)
  */
 bool SplatterPlotView::checkIfPeaksWorkspaceIsAlreadyBeingTracked(pqPipelineSource* source) {
   bool isContained = false;
-  std::string sourceName(vtkSMPropertyHelper(source->getProxy(), "WorkspaceName").GetAsString());
+  std::string sourceName(vtkSMPropertyHelper(source->getProxy(), MantidQt::API::MdConstants::WorkspaceName).GetAsString());
   for (QList<QPointer<pqPipelineSource>>::Iterator it = peaksSource.begin(); it != peaksSource.end(); ++it) {
-    std::string trackedName(vtkSMPropertyHelper((*it)->getProxy(), "WorkspaceName").GetAsString());
+    std::string trackedName(vtkSMPropertyHelper((*it)->getProxy(), MantidQt::API::MdConstants::WorkspaceName).GetAsString());
     if ((*it == source) || (sourceName == trackedName)) {
       isContained = true;
       break;
@@ -614,8 +644,7 @@ void SplatterPlotView::updatePeaksFilter(pqPipelineSource* filter) {
 
   // If there are no peaks, then destroy the filter, else update it.
   if (peaksSource.isEmpty()) {
-    pqObjectBuilder* builder = pqApplicationCore::instance()->getObjectBuilder();
-    builder->destroy(filter);
+    this->destroyFilter(MantidQt::API::MdConstants::MDPeaksFilter);
   }
   else {
     std::string workspaceNamesConcatentated = m_peaksTableController->getConcatenatedWorkspaceNames(m_peaksWorkspaceNameDelimiter);
@@ -624,8 +653,8 @@ void SplatterPlotView::updatePeaksFilter(pqPipelineSource* filter) {
       throw std::runtime_error("The peaks viewer does not contain a valid peaks workspace.");
     }
 
-    vtkSMPropertyHelper(filter->getProxy(), "PeaksWorkspace").Set(workspaceNamesConcatentated.c_str());
-    vtkSMPropertyHelper(filter->getProxy(), "Delimiter").Set(m_peaksWorkspaceNameDelimiter.c_str());
+    vtkSMPropertyHelper(filter->getProxy(), MantidQt::API::MdConstants::PeaksWorkspace).Set(workspaceNamesConcatentated.c_str());
+    vtkSMPropertyHelper(filter->getProxy(), MantidQt::API::MdConstants::Delimiter).Set(m_peaksWorkspaceNameDelimiter.c_str());
     emit this->triggerAccept();
     filter->updatePipeline();
     this->resetCamera();
@@ -677,6 +706,7 @@ void SplatterPlotView::destroyFiltersForSplatterPlotView(){
   }
 }
 
+
 } // SimpleGui
 } // Vates
 } // Mantid
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/StandardView.cpp b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/StandardView.cpp
index e9c3809f654d0c5dea4b45b98a827d6c5d59d4bf..429bfe8807ca6f7987d8a53bb42762ef34cdb397 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/StandardView.cpp
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/StandardView.cpp
@@ -1,4 +1,5 @@
 #include "MantidVatesSimpleGuiViewWidgets/StandardView.h"
+#include "MantidVatesSimpleGuiViewWidgets/RebinnedSourcesManager.h"
 // Have to deal with ParaView warnings and Intel compiler the hard way.
 #if defined(__INTEL_COMPILER)
   #pragma warning disable 1170
@@ -17,6 +18,7 @@
 #include <vtkDataObject.h>
 #include <vtkSMPropertyHelper.h>
 #include <vtkSMProxy.h>
+#include <vtkSMPVRepresentationProxy.h>
 
 #if defined(__INTEL_COMPILER)
   #pragma warning enable 1170
@@ -39,9 +41,12 @@ namespace SimpleGui
  * This function sets up the UI components, adds connections for the view's
  * buttons and creates the rendering view.
  * @param parent the parent widget for the standard view
+ * @param rebinnedSourcesManager Pointer to a RebinnedSourcesManager
  */
-  StandardView::StandardView(QWidget *parent) : ViewBase(parent),m_binMDAction(NULL),
+  StandardView::StandardView(QWidget *parent, RebinnedSourcesManager* rebinnedSourcesManager) : ViewBase(parent, rebinnedSourcesManager),
+                                                                 m_binMDAction(NULL),
                                                                  m_sliceMDAction(NULL),
+                                                                 m_cutMDAction(NULL),
                                                                  m_unbinAction(NULL)
 {
   this->ui.setupUi(this);
@@ -76,6 +81,7 @@ StandardView::~StandardView()
 
 void StandardView::setupViewButtons()
 {
+
   // Populate the rebin button
   QMenu* rebinMenu = new QMenu(this->ui.rebinToolButton);
 
@@ -85,21 +91,26 @@ void StandardView::setupViewButtons()
   m_sliceMDAction = new QAction("SliceMD", rebinMenu);
   m_sliceMDAction->setIconVisibleInMenu(false);
 
+  m_cutMDAction = new QAction("CutMD", rebinMenu);
+  m_cutMDAction->setIconVisibleInMenu(false);
 
   m_unbinAction = new QAction("Remove Rebinning", rebinMenu);
   m_unbinAction->setIconVisibleInMenu(false);
 
   rebinMenu->addAction(m_binMDAction);
   rebinMenu->addAction(m_sliceMDAction);
+  rebinMenu->addAction(m_cutMDAction);
   rebinMenu->addAction(m_unbinAction);
 
   this->ui.rebinToolButton->setPopupMode(QToolButton::InstantPopup);
   this->ui.rebinToolButton->setMenu(rebinMenu);
 
   QObject::connect(m_binMDAction, SIGNAL(triggered()),
-                   this, SLOT(onBinMD()), Qt::QueuedConnection);
+                   this, SLOT(onRebin()), Qt::QueuedConnection);
   QObject::connect(m_sliceMDAction, SIGNAL(triggered()),
-                   this, SLOT(onSliceMD()), Qt::QueuedConnection);
+                   this, SLOT(onRebin()), Qt::QueuedConnection);
+  QObject::connect(m_cutMDAction, SIGNAL(triggered()),
+                   this, SLOT(onRebin()), Qt::QueuedConnection);
   // Set the unbinbutton to remove the rebinning on a workspace
   // which was binned in the VSI
   QObject::connect(m_unbinAction, SIGNAL(triggered()),
@@ -110,7 +121,7 @@ void StandardView::setupViewButtons()
 void StandardView::destroyView()
 {
   pqObjectBuilder *builder = pqApplicationCore::instance()->getObjectBuilder();
-  this->destroyFilter(builder, QString("Slice"));
+  this->destroyFilter(QString("Slice"));
   builder->destroy(this->view);
 }
 
@@ -146,7 +157,16 @@ void StandardView::render()
   vtkSMPropertyHelper(drep->getProxy(), "Representation").Set(reptype.toStdString().c_str());
   drep->getProxy()->UpdateVTKObjects();
   this->origRep = qobject_cast<pqPipelineRepresentation*>(drep);
-  this->origRep->colorByArray("signal", vtkDataObject::FIELD_ASSOCIATION_CELLS);
+  if (!this->isPeaksWorkspace(this->origSrc))
+  {
+    vtkSMPVRepresentationProxy::SetScalarColoring(drep->getProxy(), "signal",
+                                                  vtkDataObject::FIELD_ASSOCIATION_CELLS);
+    //drep->getProxy()->UpdateVTKObjects();
+    //vtkSMPVRepresentationProxy::RescaleTransferFunctionToDataRange(drep->getProxy(),
+    //                                                               "signal",
+    //                                                               vtkDataObject::FIELD_ASSOCIATION_CELLS);
+    drep->getProxy()->UpdateVTKObjects();
+  }
 
   this->resetDisplay();
   emit this->triggerAccept();
@@ -214,25 +234,18 @@ void StandardView::closeSubWindows()
 {
 }
 
-/**
- * This function reacts to a destroyed source.
- */
-void StandardView::onSourceDestroyed()
-{
-  //setRebinAndUnbinButtons();
-}
 
 /**
  * Check if the rebin and unbin buttons should be visible
  * Note that for a rebin button to be visible there may be no
- * MDHisto workspaces present, yet temporary MDHisto workspaces are
- * allowed.
+ * MDHisto workspaces present, yet  MDHisto workspaces which result from 
+ * rebinning within the VSI are allowed.
  */
 void StandardView::setRebinAndUnbinButtons()
 {
-  int numberOfTemporaryWorkspaces = 0;
-  int numberOfTrueMDHistoWorkspaces = 0;
-  int numberOfPeakWorkspaces = 0;
+  unsigned int numberOfInternallyRebinnedWorkspaces = 0;
+  unsigned int numberOfTrueMDHistoWorkspaces = 0;
+  unsigned int numberOfPeakWorkspaces = 0;
 
   pqServer *server = pqActiveObjects::instance().activeServer();
   pqServerManagerModel *smModel = pqApplicationCore::instance()->getServerManagerModel();
@@ -240,57 +253,51 @@ void StandardView::setRebinAndUnbinButtons()
 
   for (QList<pqPipelineSource *>::iterator source = sources.begin(); source != sources.end(); ++source)
   {
-    if (isTemporaryWorkspace(*source))
+    if (isInternallyRebinnedWorkspace(*source))
     {
-      numberOfTemporaryWorkspaces++;
+      ++numberOfInternallyRebinnedWorkspaces;
     } else if (isMDHistoWorkspace(*source))
     {
-      numberOfTrueMDHistoWorkspaces++;
+      ++numberOfTrueMDHistoWorkspaces;
     }
     else if (isPeaksWorkspace(*source))
     {
-      numberOfPeakWorkspaces++;
+      ++numberOfPeakWorkspaces;
     }
   }
 
   // If there are any true MDHisto workspaces then the rebin button should be disabled
-  if (numberOfTrueMDHistoWorkspaces > 0 || numberOfPeakWorkspaces > 0)
-  {
-    this->m_binMDAction->setEnabled(false);
-    this->m_sliceMDAction->setEnabled(false);
-  }
-  else 
-  {
-    this->m_binMDAction->setEnabled(true);
-    this->m_sliceMDAction->setEnabled(true);
-  }
+  bool allowRebinning = numberOfTrueMDHistoWorkspaces > 0 || numberOfPeakWorkspaces > 0;
+  this->allowRebinningOptions(allowRebinning);
 
-  // If there are no temporary workspaces the button should be disabled.
-  if (numberOfTemporaryWorkspaces == 0)
-  {
-    this->m_unbinAction->setEnabled(false);
-  }
-  else
-  {
-    this->m_unbinAction->setEnabled(true);
-  }
+  // If there are no internally rebinned workspaces the button should be disabled.
+  allowUnbinOption(numberOfInternallyRebinnedWorkspaces > 0);
 }
 
 
 /**
  * Reacts to the user selecting the BinMD algorithm
  */ 
-void StandardView::onBinMD()
+void StandardView::onRebin()
 {
-  emit rebin("BinMD");
+  if(QAction* action = dynamic_cast<QAction*>(sender())) {
+    emit rebin(action->text().toStdString()); }
 }
 
 /**
- * Reacts to the user selecting the SliceMD algorithm
- */ 
-void StandardView::onSliceMD()
-{
-  emit rebin("SliceMD");
+Disable rebinning options
+*/
+void StandardView::allowRebinningOptions(bool allow) {
+    this->m_binMDAction->setEnabled(allow);
+    this->m_sliceMDAction->setEnabled(allow);
+    this->m_cutMDAction->setEnabled(allow);
+}
+
+/**
+Enable unbin option
+*/
+void StandardView::allowUnbinOption(bool allow) {
+  this->m_unbinAction->setEnabled(allow);
 }
 
 
@@ -303,8 +310,7 @@ void StandardView::activeSourceChangeListener(pqPipelineSource* source)
   // If there is no active source, then we do not allow rebinning
   if (!source)
   {
-    this->m_binMDAction->setEnabled(false);
-    this->m_sliceMDAction->setEnabled(false);
+    this->allowRebinningOptions(false);
     this->m_unbinAction->setEnabled(false);
     return;
   }
@@ -319,26 +325,30 @@ void StandardView::activeSourceChangeListener(pqPipelineSource* source)
     filter = qobject_cast<pqPipelineFilter*>(localSource);
   }
 
-  // Important to first check the temporary source, then for MDEvent source, 
-  // as a temporary source may be an MDEventSource.
+  // Important to first check for an internally rebinned source, then for MDEvent source, 
+  // since the internally rebinned source may be an MDEventSource.
   std::string workspaceType(localSource->getProxy()->GetXMLName());
-  if (isTemporaryWorkspace(localSource))
+
+  // Check if the source is associated with a workspace which was internally rebinned by the VSI.
+  // In this case the user can further rebin or unbin the source.
+  if (isInternallyRebinnedWorkspace(localSource))
   {
-    this->m_binMDAction->setEnabled(true);
-    this->m_sliceMDAction->setEnabled(true);
-    this->m_unbinAction->setEnabled(true);
+    this->allowRebinningOptions(true);
+    this->allowUnbinOption(true);
   }
+  // Check if we are dealing with a MDEvent workspace. In this case we allow rebinning, but 
+  // unbinning will not make a lot of sense.
   else if (workspaceType.find("MDEW Source") != std::string::npos)
   {
-    this->m_binMDAction->setEnabled(true);
-    this->m_sliceMDAction->setEnabled(true);
-    this->m_unbinAction->setEnabled(false);
+    this->allowRebinningOptions(true);
+    this->allowUnbinOption(false);
   }
+  // Otherwise we must be dealing with either a MDHIsto or PeaksWorkspace
+  // which cannot be neither rebinned nor unbinned.
   else
   {
-    this->m_binMDAction->setEnabled(false);
-    this->m_sliceMDAction->setEnabled(false);
-    this->m_unbinAction->setEnabled(false);
+    this->allowRebinningOptions(false);
+    this->allowUnbinOption(false);
   }
 }
 
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/ThreesliceView.cpp b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/ThreesliceView.cpp
index eb900d5857a45a8c86266355cbd6d9bae9621e58..863f40eeec3fa7f42c390045c8d6256bb6564509 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/ThreesliceView.cpp
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/ThreesliceView.cpp
@@ -16,6 +16,7 @@
 #include <pqPipelineSource.h>
 #include <pqPluginManager.h>
 #include <pqRenderView.h>
+#include <pqScalarsToColors.h>
 #include <vtkSMPropertyHelper.h>
 #include <vtkSMProxy.h>
 
@@ -41,35 +42,12 @@ namespace
 }
 
 
-ThreeSliceView::ThreeSliceView(QWidget *parent) : ViewBase(parent)
+ThreeSliceView::ThreeSliceView(QWidget *parent, RebinnedSourcesManager* rebinnedSourcesManager) : ViewBase(parent, rebinnedSourcesManager)
 {
   this->ui.setupUi(this);
-
-  // We need to load the QuadView plugin
-  QString quadViewLibrary;
-#ifdef Q_OS_WIN32
-  // Windows requires the full
-  // path information. The DLL is located in the apropriate executeable path of paraview.
-  const Poco::Path paraviewPath(Mantid::Kernel::ConfigService::Instance().getParaViewPath());
-  Poco::Path quadViewFullPath(paraviewPath, QUADVIEW_LIBRARY.toStdString());
-  quadViewLibrary = quadViewFullPath.toString().c_str();
-#else
-  quadViewLibrary = QUADVIEW_LIBRARY;
-#endif
-
-  // Need to load plugin
-  pqPluginManager* pm = pqApplicationCore::instance()->getPluginManager();
-  QString error;
-  pm->loadExtension(pqActiveObjects::instance().activeServer(),
-                    quadViewLibrary, &error, false);
-
-  g_log.debug() << "Loading QuadView library from " << quadViewLibrary.toStdString() << "\n";
-
   this->mainView = this->createRenderView(this->ui.mainRenderFrame,
-                                          QString("pqQuadView"));
+                                          QString("OrthographicSliceView"));
   pqActiveObjects::instance().setActiveView(this->mainView);
-
-  vtkSMPropertyHelper(this->mainView->getProxy(), "ShowCubeAxes").Set(1);
 }
 
 ThreeSliceView::~ThreeSliceView()
@@ -144,7 +122,7 @@ void ThreeSliceView::correctVisibility()
 */
 void ThreeSliceView::correctColorScaleRange()
 {
-  QPair<double, double> range = this->origRep->getColorFieldRange();
+  QPair<double, double> range = this->origRep->getLookupTable()->getScalarRange();
   emit this->dataRange(range.first, range.second);
 }
 
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/VatesParaViewApplication.cpp b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/VatesParaViewApplication.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..249c3e7f6e7d0e970253f5b9d44bd7079f068be1
--- /dev/null
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/VatesParaViewApplication.cpp
@@ -0,0 +1,134 @@
+#include "PythonThreading.h"
+
+#include "MantidVatesSimpleGuiViewWidgets/VatesParaViewApplication.h"
+#include "MantidKernel/ConfigService.h"
+
+#include "pqPVApplicationCore.h"
+#include "pqInterfaceTracker.h"
+#include "pqStandardPropertyWidgetInterface.h"
+#include "pqStandardViewFrameActionsImplementation.h"
+#include "pqQtMessageHandlerBehavior.h"
+#include "pqDataTimeStepBehavior.h"
+#include "pqSpreadSheetVisibilityBehavior.h"
+#include "pqPipelineContextMenuBehavior.h"
+#include "pqObjectPickingBehavior.h"
+#include "pqDefaultViewBehavior.h"
+#include "pqUndoRedoBehavior.h"
+#include "pqAlwaysConnectedBehavior.h"
+#include "pqCrashRecoveryBehavior.h"
+#include "pqAutoLoadPluginXMLBehavior.h"
+#include "pqVerifyRequiredPluginBehavior.h"
+#include "pqFixPathsInStateFilesBehavior.h"
+#include "pqCommandLineOptionsBehavior.h"
+#include "pqCollaborationBehavior.h"
+#include "pqViewStreamingBehavior.h"
+#include "pqPluginSettingsBehavior.h"
+
+#include <Poco/Path.h>
+
+#include <string>
+
+#include "vtksys/SystemTools.hxx"
+
+namespace Mantid
+{
+  namespace Vates
+  {
+    namespace SimpleGui
+    {
+      VatesParaViewApplication::VatesParaViewApplication() : m_logger("VatesParaViewApplication"), m_behaviorsSetup(false)
+      {
+        // Get the plugin path that we set in the ConfigService.
+        auto & configSvc = Kernel::ConfigService::Instance();
+        // This currently points at the top pvplugins directory and not the subdirectory.
+        // Needs tidying up!!
+        std::string pvPluginPathTop = configSvc.getPVPluginsPath();
+        if (pvPluginPathTop.empty())
+        {
+          throw std::runtime_error("pvplugins.directory key not setup.\nVates plugins will not be available.\n"
+                                   "Further use will cause the program to crash.\nPlease exit and "
+                                   "set this variable.");
+        }
+
+        GlobalInterpreterLock gil;
+        Q_ASSERT(pqApplicationCore::instance()==NULL);
+
+        // Provide ParaView's application core with a path to the running executable
+        int argc = 1;
+        std::string exePath = configSvc.getDirectoryOfExecutable();
+        std::vector<char> argvConversion(exePath.begin(), exePath.end());
+        argvConversion.push_back('\0');
+        char *argv[] = {&argvConversion[0]};
+
+        m_logger.debug("Intialize pqApplicationCore with "+exePath+"\n");
+        // We need to manually set the PV_PLUGIN_PATH because it's
+        // not going to be picked up from the paraview/vtk side otherwise.
+        Poco::Path pluginsDir(pvPluginPathTop, "pvplugins");
+        m_logger.debug("Setting PV_PLUGIN_PATH="+pluginsDir.toString()+"\n");
+        vtksys::SystemTools::PutEnv("PV_PLUGIN_PATH=" + pluginsDir.toString());
+        new pqPVApplicationCore(argc, argv);
+      }
+
+      /**
+       * This function duplicates the nearly identical call in ParaView for their
+       * main program setup. This is necessary for the plugin mode since it does
+       * not have access to the QMainWindow of MantidPlot.
+       */
+      void VatesParaViewApplication::setupParaViewBehaviors()
+      {
+        if (this->m_behaviorsSetup)
+        {
+          return;
+        }
+        this->m_behaviorsSetup = true;
+        // Register ParaView interfaces.
+        pqInterfaceTracker* pgm = pqApplicationCore::instance()->interfaceTracker();
+
+        // * adds support for standard paraview views.
+        pgm->addInterface(new pqStandardPropertyWidgetInterface(pgm));
+
+        pgm->addInterface(new pqStandardViewFrameActionsImplementation(pgm));
+
+        // Load plugins distributed with application.
+        pqApplicationCore::instance()->loadDistributedPlugins();
+
+        // Define application behaviors.
+        new pqQtMessageHandlerBehavior(this);
+        new pqDataTimeStepBehavior(this);
+        new pqSpreadSheetVisibilityBehavior(this);
+        new pqPipelineContextMenuBehavior(this);
+        new pqObjectPickingBehavior(this);
+        new pqDefaultViewBehavior(this);
+        new pqUndoRedoBehavior(this);
+        new pqAlwaysConnectedBehavior(this);
+        new pqCrashRecoveryBehavior(this);
+        new pqAutoLoadPluginXMLBehavior(this);
+        //new pqPluginDockWidgetsBehavior(mainWindow);
+        new pqVerifyRequiredPluginBehavior(this);
+        //new pqPluginActionGroupBehavior(mainWindow);
+        new pqFixPathsInStateFilesBehavior(this);
+        new pqCommandLineOptionsBehavior(this);
+        //new pqPersistentMainWindowStateBehavior(mainWindow);
+        new pqCollaborationBehavior(this);
+        new pqViewStreamingBehavior(this);
+        new pqPluginSettingsBehavior(this);
+      }
+
+      VatesParaViewApplication::~VatesParaViewApplication()
+      {
+
+      }
+
+      VatesParaViewApplication* VatesParaViewApplication::instance()
+      {
+        static QPointer<VatesParaViewApplication> arg;
+        if (arg == NULL)
+        {
+          arg = new VatesParaViewApplication();
+        }
+        return arg;
+      }
+
+    } //SimpleGui
+  } //Vates
+} //Mantid
diff --git a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/ViewBase.cpp b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/ViewBase.cpp
index 17cc2e0c856421f86c463603921acc4d93b06eee..5ffe25bf69ea2ca55dd2bf27afed1559cae75373 100644
--- a/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/ViewBase.cpp
+++ b/Code/Mantid/Vates/VatesSimpleGui/ViewWidgets/src/ViewBase.cpp
@@ -1,5 +1,6 @@
 #include "MantidVatesSimpleGuiViewWidgets/ViewBase.h"
 #include "MantidVatesSimpleGuiViewWidgets/BackgroundRgbProvider.h"
+#include "MantidVatesSimpleGuiViewWidgets/RebinnedSourcesManager.h"
 
 #if defined(__INTEL_COMPILER)
   #pragma warning disable 1170
@@ -10,10 +11,11 @@
 #include <pqAnimationScene.h>
 #include <pqApplicationCore.h>
 #include <pqDataRepresentation.h>
+#include <pqDeleteReaction.h>
 #include <pqObjectBuilder.h>
-#include <pqPipelineSource.h>
 #include <pqPipelineFilter.h>
 #include <pqPipelineRepresentation.h>
+#include <pqPipelineSource.h>
 #include <pqPVApplicationCore.h>
 #include <pqRenderView.h>
 #include <pqScalarsToColors.h>
@@ -33,6 +35,7 @@
 #include <QDebug>
 #include <QHBoxLayout>
 #include <QPointer>
+#include <QSet>
 
 #include <stdexcept>
 
@@ -46,8 +49,10 @@ namespace SimpleGui
 /**
  * Default constructor.
  * @param parent the parent widget for the view
+ * @param rebinnedSourcesManager Pointer to a RebinnedSourcesManager
  */
-ViewBase::ViewBase(QWidget *parent) : QWidget(parent), m_currentColorMapModel(NULL), m_temporaryWorkspaceIdentifier("tempvsi")
+ViewBase::ViewBase(QWidget *parent, RebinnedSourcesManager* rebinnedSourcesManager) : QWidget(parent),
+                                      m_rebinnedSourcesManager(rebinnedSourcesManager), m_currentColorMapModel(NULL), m_internallyRebinnedWorkspaceIdentifier("rebinned_vsi")
 {
 }
 
@@ -86,24 +91,25 @@ pqRenderView* ViewBase::createRenderView(QWidget* widget, QString viewName)
 
 /**
  * This function removes all filters of a given name: i.e. Slice.
- * @param builder the ParaView object builder
  * @param name the class name of the filters to remove
  */
-void ViewBase::destroyFilter(pqObjectBuilder *builder, const QString &name)
+void ViewBase::destroyFilter(const QString &name)
 {
   pqServer *server = pqActiveObjects::instance().activeServer();
   pqServerManagerModel *smModel = pqApplicationCore::instance()->getServerManagerModel();
   QList<pqPipelineSource *> sources;
   QList<pqPipelineSource *>::Iterator source;
   sources = smModel->findItems<pqPipelineSource *>(server);
+  QSet<pqPipelineSource*> toDelete;
   for (source = sources.begin(); source != sources.end(); ++source)
   {
     const QString sourceName = (*source)->getSMName();
     if (sourceName.startsWith(name))
     {
-      builder->destroy(*source);
+    toDelete.insert(*source);
     }
   }
+  pqDeleteReaction::deleteSources(toDelete);
 }
 
 /**
@@ -282,15 +288,17 @@ pqPipelineSource* ViewBase::setPluginSource(QString pluginName, QString wsName)
   pqServer *server = pqActiveObjects::instance().activeServer();
   pqPipelineSource *src = builder->createSource("sources", pluginName,
                                                 server);
+  src->getProxy()->SetAnnotation("MdViewerWidget0", "1");
   vtkSMPropertyHelper(src->getProxy(),
                       "Mantid Workspace Name").Set(wsName.toStdString().c_str());
 
   // Update the source so that it retrieves the data from the Mantid workspace
-  vtkSMSourceProxy *srcProxy = vtkSMSourceProxy::SafeDownCast(src->getProxy());
-  srcProxy->UpdateVTKObjects();
-  srcProxy->Modified();
-  srcProxy->UpdatePipelineInformation();
-  src->updatePipeline();
+  src->getProxy()->UpdateVTKObjects(); // Updates all the proxies
+  src->updatePipeline(); // Updates the pipeline
+  src->setModifiedState(pqProxy::UNMODIFIED); // Just to that the UI state looks consistent with the apply
+
+  // Update the properties, from PV3.98.1 to PV4.3.1, it wasn't updating any longer, so need to force it
+  src->getProxy()->UpdatePropertyInformation();
 
   return src;
 }
@@ -619,10 +627,10 @@ bool ViewBase::isMDHistoWorkspace(pqPipelineSource *src)
 }
 
 /**
- * This function checks if a pqPipelineSource is a temporary workspace.
- * @return true if the source is a temporary workspace;
+ * This function checks if a pqPipelineSource is an internally rebinned workspace.
+ * @return true if the source is an internally rebinned workspace;
  */
-bool ViewBase::isTemporaryWorkspace(pqPipelineSource *src)
+bool ViewBase::isInternallyRebinnedWorkspace(pqPipelineSource *src)
 {
   if (NULL == src)
   {
@@ -636,12 +644,12 @@ bool ViewBase::isTemporaryWorkspace(pqPipelineSource *src)
   {
     wsType = src->getSMName();
   }
-  
+
 
   QString wsName(vtkSMPropertyHelper(src->getProxy(),
                                     "WorkspaceName", true).GetAsString());
 
-  if (wsName.contains(m_temporaryWorkspaceIdentifier))
+  if (wsName.contains(m_internallyRebinnedWorkspaceIdentifier) && m_rebinnedSourcesManager->isRebinnedSourceBeingTracked(src))
   {
     return true;
   }
@@ -759,11 +767,11 @@ bool ViewBase::hasWorkspaceType(const QString &wsTypeName)
 
 /**
  * This function sets the default colors for the background and connects a tracker for changes of the background color by the user.
- * @param viewSwitched If the view was switched or created.
+ * @param useCurrentColorSettings If the view was switched or created.
  */
-void ViewBase::setColorForBackground(bool viewSwitched)
+void ViewBase::setColorForBackground(bool useCurrentColorSettings)
 {
-  backgroundRgbProvider.setBackgroundColor(this->getView(), viewSwitched);
+  backgroundRgbProvider.setBackgroundColor(this->getView(), useCurrentColorSettings);
   backgroundRgbProvider.observe(this->getView());
 }
 
diff --git a/Code/Mantid/docs/CMakeLists.txt b/Code/Mantid/docs/CMakeLists.txt
index 041f2db3e3ad97ea641955e2a9a30bad80ca5162..39c0475338ccf5e325332402859d7a91767ae489 100644
--- a/Code/Mantid/docs/CMakeLists.txt
+++ b/Code/Mantid/docs/CMakeLists.txt
@@ -83,6 +83,21 @@ if ( SPHINX_FOUND )
                            EXCLUDE_FROM_ALL 1)
   endif (DOCS_HTML)
 
+  # LINKCHECK target
+  set ( BUILDER linkcheck )
+  set ( SPHINX_CONF_DIR ${SPHINX_BUILD_DIR}/conf/${BUILDER} )
+  configure_file ( conf.py.in ${SPHINX_CONF_DIR}/conf.py @ONLY )
+  configure_file ( runsphinx.py.in runsphinx_linkcheck.py @ONLY )
+  add_custom_target ( ${TARGET_PREFIX}-linkcheck
+                      COMMAND ${DOCS_RUNNER_EXE} -xq runsphinx_linkcheck.py
+                      DEPENDS Framework MantidPlot MantidQt ${CMAKE_CURRENT_BINARY_DIR}/runsphinx_linkcheck.py ${SPHINX_CONF_DIR}/conf.py
+                      COMMENT "Checking documentation links"
+                      )
+  # Group within VS and exclude from whole build
+  set_target_properties ( ${TARGET_PREFIX}-linkcheck PROPERTIES FOLDER "Documentation"
+                          EXCLUDE_FROM_DEFAULT_BUILD 1
+                          EXCLUDE_FROM_ALL 1)
+
   ###############################################################################
   # Tests ( It would be nice to have this is a test sub directory but the
   #        configure of the runsphinx file doesn't like being in two directories.
diff --git a/Code/Mantid/docs/README.md b/Code/Mantid/docs/README.md
index 393d032b3b2a928f34481aecb7a42d042a300908..48345f2aa1372c4683bf4bc574be6150bf305336 100644
--- a/Code/Mantid/docs/README.md
+++ b/Code/Mantid/docs/README.md
@@ -13,4 +13,4 @@ or `pip`:
 
 This may require admin privileges on some environments.
 
-CMake produces a `docs-html` target that is used to build the documentation. The output files will appear in a `html` sub directory of the main `build/docs` directory.
\ No newline at end of file
+CMake produces a `docs-html` target that is used to build the documentation (only if you set the cmake variable DOCS_HTML=ON). The output files will appear in a `html` sub directory of the main `build/docs` directory.
\ No newline at end of file
diff --git a/Code/Mantid/docs/runsphinx.py.in b/Code/Mantid/docs/runsphinx.py.in
index ced46db8d7ec2251d55758174e5f6791d09f4084..c82b6edd966e733cc18050622114b4bd298159ae 100644
--- a/Code/Mantid/docs/runsphinx.py.in
+++ b/Code/Mantid/docs/runsphinx.py.in
@@ -76,8 +76,12 @@ def main(sysarg):
     # causes Sphinx to fall over. We need to put it back while processing
     # the documentation
     from pygments.lexer import RegexLexer
-    # Reverse monkeypatch using unpatched function stored in mantid_ipython_widget!
-    RegexLexer.get_tokens_unprocessed = RegexLexer.get_tokens_unprocessed_unpatched
+    # Reverse monkeypatch using unpatched function stored in mantid_ipython_widget
+    # if it is available
+    try:
+        RegexLexer.get_tokens_unprocessed = RegexLexer.get_tokens_unprocessed_unpatched
+    except AttributeError:
+        pass
     try:
         return_value = sphinx.main(argv)
     finally:
diff --git a/Code/Mantid/docs/source/algorithms/AbortRemoteJob-v2.rst b/Code/Mantid/docs/source/algorithms/AbortRemoteJob-v2.rst
new file mode 100644
index 0000000000000000000000000000000000000000..193f85ff35b623ba0bb273c96e9d56611810e763
--- /dev/null
+++ b/Code/Mantid/docs/source/algorithms/AbortRemoteJob-v2.rst
@@ -0,0 +1,34 @@
+.. algorithm::
+
+.. summary::
+
+.. alias::
+
+.. properties::
+
+Description
+-----------
+
+Abort (cancel/kill/stop) a job that has been previously submitted to a
+remote compute resource. The job must have been submitted using
+:ref:`algm-SubmitRemoteJob`. And jobs are always submitted within a
+transaction. The transaction must have been created previously with
+:ref:`algm-StartRemoteTransaction`.
+
+For more details on remote algorithms when using the Mantid web
+service remote job submission API, see the `remote job submission API
+docs <http://www.mantidproject.org/Remote_Job_Submission_API>`_.
+
+Previous Versions
+-----------------
+
+Version 1
+#########
+
+Version 1 aborts jobs using the `Mantid remote job submission API
+<http://www.mantidproject.org/Remote_Job_Submission_API>`_. This is
+still supported as one of the variants of Versions 2 and above, when
+the compute resource uses the Mantid remote job submission API as job
+manager (underlying remote job scheduling mechanism).
+
+.. categories::
diff --git a/Code/Mantid/docs/source/algorithms/AlignAndFocusPowder-v1.rst b/Code/Mantid/docs/source/algorithms/AlignAndFocusPowder-v1.rst
index 2477b9d64b38c005874a08b7ef7830fa646f5dd0..23e9685ffb8274010a9e2c5a21207441b0552c02 100644
--- a/Code/Mantid/docs/source/algorithms/AlignAndFocusPowder-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/AlignAndFocusPowder-v1.rst
@@ -42,7 +42,13 @@ Usage
 
 **Example: A simple Powgen example**
 
-The files needed for this example are not present in our standard usage data download due to their size.  They can however be downloaded using these links: `PG3_9830_event.nxs <https://github.com/mantidproject/systemtests/blob/master/Data/PG3_9830_event.nxs?raw=true>`_ and `pg3_mantid_det.cal <https://github.com/mantidproject/mantid/raw/master/Test/AutoTestData/pg3_mantid_det.cal>`_.
+The files needed for this example are not present in our standard usage data
+download due to their size.  They can however be downloaded using these links:
+`PG3_9830_event.nxs <https://github.com/mantidproject/systemtests/blob/master/Data/PG3_9830_event.nxs?raw=true>`_
+and
+`pg3_mantid_det.cal <http://198.74.56.37/ftp/external-data/MD5/e2b281817b76eadbc26a0a2617477e97>`_.
+
+You will have to rename :literal:`pg3_mantid_det.cal` manually, as its name in the link above is a list of random characters.
 
 .. code-block:: python
     
diff --git a/Code/Mantid/docs/source/algorithms/ApplyCalibration-v1.rst b/Code/Mantid/docs/source/algorithms/ApplyCalibration-v1.rst
index a2bbaf17f7739413fab03d372aba98cc84b71317..db2a0ec53e04363e14394862dcf0ad28b30487f9 100644
--- a/Code/Mantid/docs/source/algorithms/ApplyCalibration-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/ApplyCalibration-v1.rst
@@ -15,8 +15,7 @@ updated as absolute positions and so this update can be repeated.
 The PositionTable must have columns *Detector ID* and *Detector
 Position*. The entries of the *Detector ID* column are integer referring
 to the Detector ID and the enties of the *Detector Position* are
-`V3Ds <http://www.mantidproject.org/V3D>`_ referring to the position of the detector whose ID is in
-same row.
+`V3Ds <../api/python/mantid/kernel/V3D.html>`__ referring to the position of the detector whose ID is in same row.
 
 This algorithm is not appropriate for rectangular detectors and won't move them.
 
diff --git a/Code/Mantid/docs/source/algorithms/Authenticate-v2.rst b/Code/Mantid/docs/source/algorithms/Authenticate-v2.rst
new file mode 100644
index 0000000000000000000000000000000000000000..a48fd17d891942b630247f7d1fd1b5de33a20bad
--- /dev/null
+++ b/Code/Mantid/docs/source/algorithms/Authenticate-v2.rst
@@ -0,0 +1,45 @@
+.. algorithm::
+
+.. summary::
+
+.. alias::
+
+.. properties::
+
+Description
+-----------
+
+Authenticate to the remote compute resource. This must be executed
+before calling any other remote algorithms. The authentication method
+and outcome of ths algorithm is dependent on the particular
+implementation (job manager underlying the algorithm). But typically,
+if the authentication is successfull, a cookie is received that is
+stored internally and re-used for all subsequent interactions with the
+compute resource.
+
+In the simplest use case of remote algorithms, once you authenticate
+with this algorithm, you can create a transaction with
+:ref:`algm-StartRemoteTransaction`. Then you can submit jobs (with
+:ref:`algm-SubmitRemoteJob`, query the status of jobs (with
+:ref:`algm-QueryAllRemoteJobs` and :ref:`algm-QueryRemoteJob`), upload
+files (with :ref:`algm-UploadRemoteFile`) or download files (with
+:ref:`algm-QueryRemoteFile` and :ref:`algm-DownloadRemoteFile`).
+
+For specific details on remote algorithms when using the Mantid web
+service remote job submission API, see the `remote job submission API
+docs <http://www.mantidproject.org/Remote_Job_Submission_API>`_.
+
+Previous Versions
+-----------------
+
+Version 1
+#########
+
+Version 1 authenticates to a Mantid web service using the `Mantid
+remote job submission API
+<http://www.mantidproject.org/Remote_Job_Submission_API>`_. This is
+still supported as one of the variants of Versions 2 and above, when
+the compute resource uses the Mantid remote job submission API as job
+manager (underlying remote job scheduling mechanism).
+
+.. categories::
diff --git a/Code/Mantid/docs/source/algorithms/ClearUB-v1.rst b/Code/Mantid/docs/source/algorithms/ClearUB-v1.rst
index 418a5b87a596c73f976945097bb3cfe8f92d13dc..49fb6389f3ab3b529e60bd0bf534037310e44535 100644
--- a/Code/Mantid/docs/source/algorithms/ClearUB-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/ClearUB-v1.rst
@@ -10,7 +10,38 @@ Description
 -----------
 
 Clears the OrientedLattice of each ExperimentInfo attached to the intput
-:ref:`Workspace <Workspace>`. Works with both single ExperimentInfos and
+`Workspace <http://www.mantidproject.org/Workspace>`_. Works with both single ExperimentInfos and
 MultipleExperimentInfo instances.
 
+Usage 
+-----
+
+.. testcode:: ExClearUB
+
+   # create a workspace (or you can load one)
+   ws=CreateSingleValuedWorkspace(5)
+
+   #set a UB matrix using the vector along k_i as 1,1,0, and the 0,0,1 vector in the horizontal plane
+   SetUB(ws,a=5,b=6,c=7,alpha=90, beta=90, gamma=90, u="1,1,0", v="0,0,1")
+
+   #check that we do have a UB matrix
+   from numpy import *
+   mat=array(ws.sample().getOrientedLattice().getUB())
+   print "UB matrix size", mat.size 
+
+   ClearUB(ws)
+
+   #check that it removed UB matrix & orientated lattice
+   if( ws.sample().hasOrientedLattice() ):
+	print "ClearUB has not removed the orientated lattice."
+   else:
+	print "ClearUB has removed the oriented lattice."
+
+Output:
+
+.. testoutput:: ExClearUB
+
+   UB matrix size 9
+   ClearUB has removed the oriented lattice.
+
 .. categories::
diff --git a/Code/Mantid/docs/source/algorithms/CloneWorkspace-v1.rst b/Code/Mantid/docs/source/algorithms/CloneWorkspace-v1.rst
index 7f6ccb5b8cc17fbce1bdbdae358087296d57b128..f708b5aa2a5a0332b10614a4cedfa529533cc912 100644
--- a/Code/Mantid/docs/source/algorithms/CloneWorkspace-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/CloneWorkspace-v1.rst
@@ -14,6 +14,6 @@ workspace. It maintains events if the input is an
 :ref:`EventWorkspace <EventWorkspace>`. It will call CloneMDWorkspace for a
 `MDEventWorkspace <http://www.mantidproject.org/MDEventWorkspace>`_ or a
 :ref:`MDHistoWorkspace <MDHistoWorkspace>`. It can also clone a
-`PeaksWorkspace <http://www.mantidproject.org/PeaksWorkspace>`_.
+:ref:`PeaksWorkspace <PeaksWorkspace>`.
 
 .. categories::
diff --git a/Code/Mantid/docs/source/algorithms/ConvertToDetectorFaceMD-v1.rst b/Code/Mantid/docs/source/algorithms/ConvertToDetectorFaceMD-v1.rst
index 7dbf4e39211ae398cab4152e7c087de78dabfe14..51007f3ee26607e605cd7c3c106557c5578736f2 100644
--- a/Code/Mantid/docs/source/algorithms/ConvertToDetectorFaceMD-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/ConvertToDetectorFaceMD-v1.rst
@@ -14,7 +14,7 @@ converts it into a `MDEventWorkspace <http://www.mantidproject.org/MDEventWorksp
 viewed in the `SliceViewer <http://www.mantidproject.org/SliceViewer>`_.
 
 The algorithm currently only works for instruments with
-`RectangularDetectors <http://www.mantidproject.org/InstrumentDefinitionFile#Creating_Rectangular_Area_Detectors>`_. The coordinates of the
+:ref:`rectangular detectors <Creating Rectangular Area Detectors>`. The coordinates of the
 output workspace are:
 
 -  Pixel X coordinate (integer starting at 0)
@@ -43,9 +43,9 @@ screenshot for example:
 BankNumbers Parameter
 #####################
 
-If your instrument has several `RectangularDetectors <http://www.mantidproject.org/InstrumentDefinitionFile#Creating_Rectangular_Area_Detectors>`_, you can use the
+If your instrument has several :ref:`rectangular detectors <Creating Rectangular Area Detectors>`, you can use the
 *BankNumbers* property to specify which one(s) to convert. The algorithm
-looks for `RectangularDetectors <http://www.mantidproject.org/InstrumentDefinitionFile#Creating_Rectangular_Area_Detectors>`_ with the name 'bankXX' where XX is the
+looks for :ref:`rectangular detectors <Creating Rectangular Area Detectors>` with the name 'bankXX' where XX is the
 bank number.
 
 If you specify more than one bank number, then the algorithm will create
diff --git a/Code/Mantid/docs/source/algorithms/ConvertToDiffractionMDWorkspace-v2.rst b/Code/Mantid/docs/source/algorithms/ConvertToDiffractionMDWorkspace-v2.rst
index 3527b1f8684d230faa5f50bd86b639181b59c872..829317c03af0d85d06e9ee6628c60c60c5aceeba 100644
--- a/Code/Mantid/docs/source/algorithms/ConvertToDiffractionMDWorkspace-v2.rst
+++ b/Code/Mantid/docs/source/algorithms/ConvertToDiffractionMDWorkspace-v2.rst
@@ -9,8 +9,8 @@
 Description
 -----------
 
-The algorithm converts from a `MatrixWorkspace <http://mantidproject.org/MatrixWorkspace>`__ (in
-any input units) into `MDWorkspace <http://mantidproject.org/MDWorkspace>`__ containing 
+The algorithm converts from a :ref:`MatrixWorkspace <MatrixWorkspace>` (in
+any input units) into a :ref:`MDWorkspace <MDWorkspace>` containing
 3D events in reciprocal space.
 
 The calculations apply only to elastic diffraction experiments. The
@@ -18,21 +18,21 @@ conversion can be done either to Q-space in the lab or sample frame, or
 to HKL of the crystal.
 
 Version 2 of the algorithm is the wrapper around :ref:`algm-ConvertToMD` algorithm, used for
-diffraction workflow and for supporting the interface of the previous specialized version of this 
+diffraction workflow and for supporting the interface of the previous specialized version of this
 algorithm.  Old specialized version of this algorithm also exists.
 
-See the :ref:`algm-ConvertToDiffractionMDWorkspace-v1` for details of the old and  :ref:`algm-ConvertToMD` for this algorithms implementations. 
- 
-The main difference between the results produced by the version one and two of this algorithm 
-is the type of the workspace, produced by default. 
-Version one is producing `MDLeanEvent<3> <http://www.mantidproject.org/MDWorkspace#Description%20of%20MDWorkspace>`__-s workspace 
-and this version generates `MDEvent<3> <http://www.mantidproject.org/MDWorkspace#Description%20of%20MDWorkspace>`__-s workspace.
+See the :ref:`algm-ConvertToDiffractionMDWorkspace-v1` for details of the old and  :ref:`algm-ConvertToMD` for this algorithms implementations.
 
-To obtain a workspace containing `MDLeanEvent<3> <http://www.mantidproject.org/MDWorkspace#Description%20of%20MDWorkspace>`__-s, 
-and fine-tune the output workspace properties, 
+The main difference between the results produced by the version one and two of this algorithm
+is the type of the workspace, produced by default.
+Version one is producing :ref:`MDLeanEvent\<3\> <MDWorkspace>`-s workspace
+and this version generates :ref:`MDEvent\<3\> <MDWorkspace>`-s workspace.
+
+To obtain a workspace containing :ref:`MDLeanEvent\<3\> <MDWorkspace>`-s,
+and fine-tune the output workspace properties,
 one has to create OutputWorkspace using :ref:`algm-CreateMDWorkspace` algorithm first.
 
- 
+
 
 Types of Conversion
 ###################
@@ -63,7 +63,7 @@ This correction is also done by the
 :ref:`algm-AnvredCorrection` algorithm, and will be set to
 false if that algorithm has been run on the input workspace.
 
-Usage 
+Usage
 
 **Example - Convert re-binned MARI 2D workspace to 3D MD workspace for further analysis/merging with data at different temperatures :**
 
@@ -76,7 +76,7 @@ Usage
 
    # A way to look at these results as a text:
    print "Resulting MD workspace has {0} events and {1} dimensions".format(md.getNEvents(),md.getNumDims())
-   print "Workspace Type is: ",md.id()   
+   print "Workspace Type is: ",md.id()
 
 **Output:**
 
diff --git a/Code/Mantid/docs/source/algorithms/ConvertUnitsUsingDetectorTable-v1.rst b/Code/Mantid/docs/source/algorithms/ConvertUnitsUsingDetectorTable-v1.rst
new file mode 100644
index 0000000000000000000000000000000000000000..3512511edb838b5dc60fe9a5bf634284b8ab5811
--- /dev/null
+++ b/Code/Mantid/docs/source/algorithms/ConvertUnitsUsingDetectorTable-v1.rst
@@ -0,0 +1,68 @@
+
+.. algorithm::
+
+.. summary::
+
+.. alias::
+
+.. properties::
+
+Description
+-----------
+
+This algorithm functions in the same basic way as :ref:`algm-ConvertUnits` but 
+instead of reading the geometric parameters from the instrument, it uses values 
+that are specified in a `TableWorkspace <http://www.mantidproject.org/TableWorkspace>`__
+
+Restrictions on the input workspace
+###################################
+
+-  Naturally, the X values must have a unit set, and that unit must be
+   known to the `Unit Factory <http://www.mantidproject.org/Units>`__.
+-  Only histograms, not point data, can be handled at present.
+-  The algorithm will also fail if the source-sample distance cannot be
+   calculated (i.e. the :ref:`instrument <instrument>` has not been
+   properly defined).
+
+Available units
+---------------
+
+The units currently available to this algorithm are listed
+`here <http://www.mantidproject.org/Units>`__, along with equations specifying exactly how the
+conversions are done.
+
+Usage
+-----
+
+**Example - Convert to wavelength using parameters from a table**
+
+.. testcode:: ConvertUnitsUsingDetectorTableExample
+
+   # Create a host workspace
+   ws = CreateSampleWorkspace("Histogram",NumBanks=1,BankPixelWidth=1)
+   # Create a TableWorkspace to hold the detector parameters
+   detpars = CreateEmptyTableWorkspace()
+   detpars.addColumn("int", "spectra")
+   detpars.addColumn("double", "l1")
+   detpars.addColumn("double", "l2")
+   detpars.addColumn("double", "twotheta")
+   detpars.addColumn("double", "efixed")
+   detpars.addColumn("int", "emode")
+
+   # Add the parameters
+   detpars.addRow([1, 10.0, 5.0, 90.0, 0.0, 0])
+
+   wsOut = ConvertUnitsUsingDetectorTable(ws,Target="Wavelength",DetectorParameters=detpars)
+
+   print "Input",  ws.readX(0)[ws.blocksize()-1]
+   print "Output",  wsOut.readX(0)[wsOut.blocksize()-1]
+
+Output:
+
+.. testoutput:: ConvertUnitsUsingDetectorTableExample
+
+   Input 19800.0
+   Output 5.22196485301
+
+.. categories::
+
diff --git a/Code/Mantid/docs/source/algorithms/CopySample-v1.rst b/Code/Mantid/docs/source/algorithms/CopySample-v1.rst
index 985341b459c643b8047b704f95c37060f32af1fd..742d6c44c64a92acd119758c751ea05cc88bd135 100644
--- a/Code/Mantid/docs/source/algorithms/CopySample-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/CopySample-v1.rst
@@ -25,8 +25,10 @@ One can copy the orientation matrix only. To do this, select both
 CopyLattice and CopyOrientationOnly. If only CopyOrientationOnly is
 true, the algorithm will throw an error.
 
-A common use for this algorithm is for single crystal measurements. Finding the UB matrix occurs on
-a `PeaksWorkspace <http://www.mantidproject.org/PeaksWorkspace>`_. In order to convertthe data to HKL space, one needs to copy the oriented lattice to the individual data workspaces.
+A common use for this algorithm is for single crystal measurements.
+Finding the UB matrix occurs on a :ref:`PeaksWorkspace <PeaksWorkspace>`.
+In order to convertthe data to HKL space, one needs to copy the oriented lattice
+to the individual data workspaces.
 
 Usage
 -----
diff --git a/Code/Mantid/docs/source/algorithms/CreateGroupingWorkspace-v1.rst b/Code/Mantid/docs/source/algorithms/CreateGroupingWorkspace-v1.rst
index 29873ac41d9480a9faa0d6e15328642dc14efeee..7057dee151f963eaee0fbf75eb227054e3cfdf5b 100644
--- a/Code/Mantid/docs/source/algorithms/CreateGroupingWorkspace-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/CreateGroupingWorkspace-v1.rst
@@ -9,7 +9,7 @@
 Description
 -----------
 
-A `GroupingWorkspace <http://www.mantidproject.org/GroupingWorkspace>`_ is a simple workspace with
+A GroupingWorkspace is a simple workspace with
 one value per detector pixel; this value corresponds to the group number
 that will be used when focussing or summing another workspace.
 
diff --git a/Code/Mantid/docs/source/algorithms/CreateMD-v1.rst b/Code/Mantid/docs/source/algorithms/CreateMD-v1.rst
index a54a350697b331d310c2bef58b9ee8b9b7716b6e..eb53bd2beb965178f3382b416d3eda2cf9267fb6 100644
--- a/Code/Mantid/docs/source/algorithms/CreateMD-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/CreateMD-v1.rst
@@ -21,10 +21,14 @@ Goniometer Settings
 
 If goniometer settings have been provided then these will be applied to the input workspace(s). For multiple input workspaces, you will need to provide goniometer settings (*Psi*, *Gl*, *Gs*) as vectors where each element of the vector corresponds to the workspace in the order listed in *InputWorkspaces*. You do not need to provide the goniometer settings at all. If you run :ref:`algm-SetGoniometer` individually on the input workspace prior to running CreateMD, then those settings will not be overwritten by CreateMD.
 
+EFix
+#######
+The EFix value may be provided for input workspaces. Specifying a single value, will ensure that that value is applied to all input DataSources. EFix can also be provided as an array provided that the array is the same length as the DeataSources, in this case, the EFix values will be matched to the DataSources based on index. EFix has units of meV.
+
 Merging Individually Converted Runs
 #####################################
 
-If a sequence of input workspaces are provided then these are individually processed as above, and are merged together via :ref:`algm-MergeMD`. Intermediate workspaces are not kept.
+If a sequence of input workspaces are provided, and *InPlace* is False, then these are individually processed as above, and are merged together via :ref:`algm-MergeMD`. Intermediate workspaces are not kept. If *InPlace* is applied conversion and merging are done in the same step. This requires less memory overhead, but may be slower.
 
 Additional Information
 #######################
@@ -78,13 +82,12 @@ Output
    for i in range(1, 5):
        current_ws = CreateSimulationWorkspace(Instrument='MAR', BinParams=[-3,1,3], UnitX='DeltaE', OutputWorkspace='input_ws_' + str(i))
        input_runs.append(current_ws.name())
-       AddSampleLog(Workspace=current_ws,LogName='Ei',LogText='3.0',LogType='Number')
        psi.append(float(5 * i))
        gl.append(0.0)
        gs.append(0.0)
     
    # Convert and merge
-   new_merged = CreateMD(input_runs, Emode='Direct', Alatt=[1.4165, 1.4165,1.4165], Angdeg=[ 90, 90, 90], u=[1, 0, 0,], v=[0,1,0], Psi=psi, Gl=gl, Gs=gs)
+   new_merged = CreateMD(input_runs, Emode='Direct', Alatt=[1.4165, 1.4165,1.4165], Angdeg=[ 90, 90, 90], u=[1, 0, 0,], v=[0,1,0], Psi=psi, Gl=gl, Gs=gs, EFix=3.0)
 
    # Show dimensionality and dimension names
    ndims = new_merged.getNumDims()
@@ -102,4 +105,40 @@ Output
    [0,0,L]
    DeltaE
 
+**Multi Conversion Example InPlace**
+##########################################
+
+.. testcode:: MultiConversionInPlace
+
+   # Create multiple runs 
+   input_runs = list()
+   psi = list()
+   gs = list()
+   gl = list()
+   for i in range(1, 5):
+       current_ws = CreateSimulationWorkspace(Instrument='MAR', BinParams=[-3,1,3], UnitX='DeltaE', OutputWorkspace='input_ws_' + str(i))
+       input_runs.append(current_ws.name())
+       psi.append(float(5 * i))
+       gl.append(0.0)
+       gs.append(0.0)
+    
+   # Convert and merge. ConversionToMD done in place.
+   new_merged = CreateMD(input_runs, Emode='Direct', Alatt=[1.4165, 1.4165,1.4165], Angdeg=[ 90, 90, 90], u=[1, 0, 0,], v=[0,1,0], Psi=psi, Gl=gl, Gs=gs, EFix=3.0, InPlace=True)
+
+   # Show dimensionality and dimension names
+   ndims = new_merged.getNumDims()
+   for i in range(ndims):
+       dim = new_merged.getDimension(i)
+       print dim.getName()
+
+Output
+^^^^^^
+
+.. testoutput:: MultiConversionInPlace
+
+   [H,0,0]
+   [0,K,0]
+   [0,0,L]
+   DeltaE
+
 .. categories::
diff --git a/Code/Mantid/docs/source/algorithms/CreatePeaksWorkspace-v1.rst b/Code/Mantid/docs/source/algorithms/CreatePeaksWorkspace-v1.rst
index 9749bacfed0fa26da72a6082a6bf792e7b82fbb3..4c92ed66857ff3b7ae30fef36724d7774f7454c2 100644
--- a/Code/Mantid/docs/source/algorithms/CreatePeaksWorkspace-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/CreatePeaksWorkspace-v1.rst
@@ -9,12 +9,12 @@
 Description
 -----------
 
-Create an empty `PeaksWorkspace <http://www.mantidproject.org/PeaksWorkspace>`_. Use
+Create an empty :ref:`PeaksWorkspace <PeaksWorkspace>`. Use
 :ref:`algm-LoadIsawPeaks` or :ref:`algm-FindPeaksMD` to
 create a peaks workspace with peaks.
 
 This workspace can serve as a starting point for modifying the
-`PeaksWorkspace <http://www.mantidproject.org/PeaksWorkspace>`_, using the GUI or python scripting,
+:ref:`PeaksWorkspace <PeaksWorkspace>`, using the GUI or python scripting,
 for example.
 
 Usage
diff --git a/Code/Mantid/docs/source/algorithms/CutMD-v1.rst b/Code/Mantid/docs/source/algorithms/CutMD-v1.rst
index cfafd64216f57e3ae6ff03e28e0090d2e103b19a..98a4ea6d220acfcd280efbf0d60f9277ec26f3c0 100644
--- a/Code/Mantid/docs/source/algorithms/CutMD-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/CutMD-v1.rst
@@ -10,9 +10,7 @@ Description
 -----------
 
 This algorithm performs slicing of multiDimensional data according to a chosen
-projection, and binning choice. The algorithm uses :ref:`algm-BinMD` or
-:ref:`algm-SliceMD` to achieve the binning of the data. The choice of child
-algorithm used for the slicing is controlled by the NoPix option.
+projection, limits and binning steps. 
 
 The synax is similar to that used by `Horace <http://horace.isis.rl.ac.uk/Manipulating_and_extracting_data_from_SQW_files_and_objects#cut_sqw>`__.
 
@@ -23,6 +21,19 @@ all then be processed sequentially with the same options. The only requirement
 is that the same number of output workspaces are also given so that CutMD knows
 what to call each output workspace created.
 
+MDEventWorkspaces
+~~~~~~~~~~~~~~~~~~~
+
+For input of type :ref:`MDEventWorkspace <MDWorkspace>` the algorithm uses :ref:`algm-BinMD` or
+:ref:`algm-SliceMD` to achieve the binning of the data. The choice of child
+algorithm used for slicing in this case is controlled by the NoPix option. 
+
+MDHistoWorkspaces
+~~~~~~~~~~~~~~~~~~~
+
+If the input is an :ref:`MDHistoWorkspace <MDHistoWorkspace>` :ref:`algm-BinMD` and :ref:`algm-SliceMD` are not made available as they needto get hold of the original MDEvents associated with an :ref:`MDEventWorkspace <MDWorkspace>` in order to perform the rebinning. As this information is missing from the MDHistoWorkspace images, those operations are forbidden. Instead, a limited subset of the operations are allowed, and are performed via :ref:`algm-IntegrateMDHistoWorkspace`. In this case, the Projection and NoPix properties are ignored. See :ref:`algm-IntegrateMDHistoWorkspace` for how the binning parameters are used.
+
+
 Creating Projections
 ~~~~~~~~~~~~~~~~~~~~
 
@@ -127,5 +138,27 @@ Output:
    number of dimensions not integrated 3
    min dE 5.0
    max dE -5.0
+   
+**Example - CutMD on MDHistoWorkspace:**
 
+.. testcode:: ExampleMDHisto
+
+   signal  = [1.0] * 100;
+   error=[1.0] * 100;
+   # Create Histo workspace
+   histo_ws=CreateMDHistoWorkspace(Dimensionality=2,Extents=[-10,10,-10,10],SignalInput=signal ,ErrorInput=error, NumberOfBins=[10,10], Names='X,Y', Units='Q,Q')
+              
+   # Cut the MDHistoWorkspace to give a single bin containing half the data              
+   cut= CutMD(InputWorkspace=histo_ws, PBins=[[-10, 10], [-5, 5]]) 
+
+   print 'Total signal in input = %0.2f' %  sum(signal)
+   print 'Half the volume should give half the signal = %0.2f' % cut.getSignalArray()
+
+Output:
+
+.. testoutput:: ExampleMDHisto
+
+   Total signal in input = 100.00
+   Half the volume should give half the signal = 50.00
+   
 .. categories::
diff --git a/Code/Mantid/docs/source/algorithms/DetectorDiagnostic-v1.rst b/Code/Mantid/docs/source/algorithms/DetectorDiagnostic-v1.rst
index 5c846fe4a65e744f4c0b946c13067518a5a4098f..06532c07b8818df7f7fe52791800edc713954472 100644
--- a/Code/Mantid/docs/source/algorithms/DetectorDiagnostic-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/DetectorDiagnostic-v1.rst
@@ -23,4 +23,27 @@ tested with :ref:`algm-FindDetectorsOutsideLimits`. The background workspace is
 through :ref:`algm-MedianDetectorTest`. A processed sample workspace can be given
 to perform and :ref:`algm-CreatePSDBleedMask` will be run on it.
 
+Workflow
+########
+
+Parameters for the child algorithms are not shown due to the sheer number.
+They are passed onto child algorithms that under the same name, except
+
+* LowThreshold and HighThresold are not passed onto :ref:`algm-FindDetectorsOutsideLimits`, but are set as 1.0e-10 and 1.0e100 respectively.
+
+* LowOutLier, HighOutlier and ExcludeZeroesFromMedian are not passed onto :ref:`algm-MedianDetectorTest`, but are set as 0.0, 1.0e100 and true respectively.
+
+* DetVanRatioVariation is passed onto :ref:`algm-DetectorEfficiencyVariation` as Variation.
+
+* SampleBkgLowAcceptanceFactor, SampleBkgHighAcceptanceFactor, SampleBkgSignificanceTest and SampleCorrectForSolidAngle are passed onto :ref:`algm-MedianDetectorTest` as LowThreshold, HighThreshold, SignicanceTest and CorrectForSolidAngle respectively.
+
+Numerous uses of :ref:`algm-MaskDetectors` are not shown and can be taken be be executed whenever appropriate. 
+Also the output property NumberOfFailures from the executed child algorithms are added together 
+to form the NumberOfFailures output by the main algorithm.
+
+
+.. diagram:: DetectorDiagnostic-v1_wkflw.dot
+
+
+
 .. categories::
diff --git a/Code/Mantid/docs/source/algorithms/DownloadFile-v1.rst b/Code/Mantid/docs/source/algorithms/DownloadFile-v1.rst
index 5f0407d72a2f2ba272ca214638667321eaeb3a81..50f20501d822604589b12de75fe4d845be068e28 100644
--- a/Code/Mantid/docs/source/algorithms/DownloadFile-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/DownloadFile-v1.rst
@@ -11,8 +11,8 @@ Description
 -----------
 
 This is a simple algorithm that will download the contents of a url address to a file.
-It can support http:// and https:// based urls, and if the method is not supplied then http:// will be assumed.
-For example: If the address is www.mantidproject.org, then this will be adjusted to http://www.mantidproject.org.
+It can support :literal:`http://` and :literal:`https://` based urls, and if the method is not supplied then :literal:`http://` will be assumed.
+For example: If the address is :literal:`www.mantidproject.org`, then this will be adjusted to :literal:`http://www.mantidproject.org`.
 
 
 Usage
diff --git a/Code/Mantid/docs/source/algorithms/DownloadRemoteFile-v2.rst b/Code/Mantid/docs/source/algorithms/DownloadRemoteFile-v2.rst
new file mode 100644
index 0000000000000000000000000000000000000000..7aa0d0022b01dcd68232132e2ac1f0a0f6efb81f
--- /dev/null
+++ b/Code/Mantid/docs/source/algorithms/DownloadRemoteFile-v2.rst
@@ -0,0 +1,34 @@
+.. algorithm::
+
+.. summary::
+
+.. alias::
+
+.. properties::
+
+Description
+-----------
+
+Download a file from a remote compute resource. Files are available
+for transactions, and you can retrieve the list of available files
+with :ref:`algm-QueryRemoteFile`. See
+:ref:`algm-StartRemoteTransaction` for how to start (create) a
+newtransaction.
+
+For specific details on remote algorithms when using the Mantid web
+service remote job submission API, see the `remote job submission API
+docs <http://www.mantidproject.org/Remote_Job_Submission_API>`_.
+
+Previous Versions
+-----------------
+
+Version 1
+#########
+
+Version 1 downloads files using the `Mantid remote job submission API
+<http://www.mantidproject.org/Remote_Job_Submission_API>`_. This is
+still supported as one of the variants of Versions 2 and above, when
+the compute resource uses the Mantid remote job submission API as job
+manager (underlying remote job scheduling mechanism).
+
+.. categories::
diff --git a/Code/Mantid/docs/source/algorithms/ExtractSpectra-v1.rst b/Code/Mantid/docs/source/algorithms/ExtractSpectra-v1.rst
new file mode 100644
index 0000000000000000000000000000000000000000..bc3ad6b17db86383971839ce1cc14d7d4e19fa52
--- /dev/null
+++ b/Code/Mantid/docs/source/algorithms/ExtractSpectra-v1.rst
@@ -0,0 +1,45 @@
+.. algorithm::
+
+.. summary::
+
+.. alias::
+
+.. properties::
+
+Description
+-----------
+
+Extracts a number of spectra from a MatrixWorkspace and puts them into a new workspace.
+Optionally it can cut the number of bins (x values). See the :ref:`algm-CropWorkspace`
+algorithm for more details on how it works for ragged workspaces and workspaces with
+common bin boundaries.
+
+
+Usage
+-----
+
+**Example - ExtractSpectra**
+
+.. testcode:: ExtractSpectraExample
+
+    # Create an input workspace
+    ws = CreateSampleWorkspace()
+    print 'Input workspace has %s bins' % ws.blocksize()
+    print 'Input workspace has %s spectra' % ws.getNumberHistograms()
+
+    # Extract spectra 1,3 and 5 and crop the x-vector to interval 200 <= x <= 1300
+    cropped = ExtractSpectra(ws,200,1300,SpectrumList=[1,3,5])
+    print 'Output workspace has %s bins' % cropped.blocksize()
+    print 'Output workspace has %s spectra' % cropped.getNumberHistograms()
+
+Output:
+
+.. testoutput:: ExtractSpectraExample
+
+    Input workspace has 100 bins
+    Input workspace has 200 spectra
+    Output workspace has 5 bins
+    Output workspace has 3 spectra
+
+.. categories::
+
diff --git a/Code/Mantid/docs/source/algorithms/FindClusterFaces-v1.rst b/Code/Mantid/docs/source/algorithms/FindClusterFaces-v1.rst
index 51028b3910ebdd5bb3ba45157445e27cc4fcd491..cf5c1d3d03db4d4acfb797f55016b58307cc75bc 100644
--- a/Code/Mantid/docs/source/algorithms/FindClusterFaces-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/FindClusterFaces-v1.rst
@@ -19,7 +19,7 @@ which contains all the cluster edge faces required to draw the outer
 edge of all clusters within the workspace.
 
 You may optionally provide a FilterWorkspace, which is a
-`PeaksWorkspace <http://www.mantidproject.org/PeaksWorkspace>`_. If provided, the Peak locations are
+:ref:`PeaksWorkspace <PeaksWorkspace>`. If provided, the Peak locations are
 projected onto the InputWorkspace and the center locations are used to
 restrict the output to only include the clusters that are the union
 between the peak locations and the image clusters.
diff --git a/Code/Mantid/docs/source/algorithms/FindPeaksMD-v1.rst b/Code/Mantid/docs/source/algorithms/FindPeaksMD-v1.rst
index c3aa69ab50c5ec0cc0f63f7d72924f3cba8235c2..6f085274443e5144848c4ea056f4b5bf50fe067a 100644
--- a/Code/Mantid/docs/source/algorithms/FindPeaksMD-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/FindPeaksMD-v1.rst
@@ -34,7 +34,7 @@ The algorithm proceeds in this way:
 -  This is repeated until we find up to MaxPeaks peaks.
 
 Each peak created is placed in the output
-`PeaksWorkspace <http://www.mantidproject.org/PeaksWorkspace>`_, which can be a new workspace or
+:ref:`PeaksWorkspace <PeaksWorkspace>`, which can be a new workspace or
 replace the old one.
 
 This algorithm works on a :ref:`MDHistoWorkspace <MDHistoWorkspace>`
@@ -44,13 +44,13 @@ is not accessible. It may give better results on
 :ref:`Workspace2D <Workspace2D>`'s that were converted to
 :ref:`MDWorkspaces <MDWorkspace>`.
 
-   
+
 Usage
 ------
 
 **Example - IntegratePeaks:**
 
-The code iteslef works but disabled from doc tests as takes too long to complete. User should provide its own 
+The code iteslef works but disabled from doc tests as takes too long to complete. User should provide its own
 event nexus file instead of **TOPAZ_3132_event.nxs** used within this example. The original **TOPAZ_3132_event.nxs**
 file is availible in `Mantid system tests repository <https://github.com/mantidproject/systemtests/tree/master/Data/TOPAZ_3132_event.nxs>`_.
 
@@ -88,7 +88,7 @@ file is availible in `Mantid system tests repository <https://github.com/mantidp
    # build peak workspace necessary for IntegrateEllipsoids algorithm to work
    ConvertToMD(InputWorkspace='TOPAZ_3132_event',QDimensions='Q3D',dEAnalysisMode='Elastic',Q3DFrames='Q_sample',LorentzCorrection='1',OutputWorkspace='TOPAZ_3132_md',\
    MinValues='-25,-25,-25',MaxValues='25,25,25',SplitInto='2',SplitThreshold='50',MaxRecursionDepth='13',MinRecursionDepth='7')
-   peaks=FindPeaksMD(InputWorkspace='TOPAZ_3132_md',PeakDistanceThreshold='0.37680',MaxPeaks='50',DensityThresholdFactor='100',OutputWorkspace='TOPAZ_3132_peaks')   
+   peaks=FindPeaksMD(InputWorkspace='TOPAZ_3132_md',PeakDistanceThreshold='0.37680',MaxPeaks='50',DensityThresholdFactor='100',OutputWorkspace='TOPAZ_3132_peaks')
 
    # print 10 rows of table workspace
    print_tableWS(peaks,10)
diff --git a/Code/Mantid/docs/source/algorithms/Fit-v1.rst b/Code/Mantid/docs/source/algorithms/Fit-v1.rst
index 121c1e461b54067a724be88ca20eb596b0b57a62..25b0315a012d9b0818b0210dde62b059198bd1c7 100644
--- a/Code/Mantid/docs/source/algorithms/Fit-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/Fit-v1.rst
@@ -32,14 +32,12 @@ Overview
 This is a generic algorithm for fitting data in a Workspace with a
 function. The workspace must have the type supported by the algorithm.
 Currently supported types are: :ref:`MatrixWorkspace <MatrixWorkspace>` for
-fitting with a `IFunction1D <http://www.mantidproject.org/IFunction1D>`_ and
-`IMDWorkspace <http://www.mantidproject.org/IMDWorkspace>`_ for fitting with
-`IFunctionMD <http://www.mantidproject.org/IFunctionMD>`_. After Function and InputWorkspace
-properties are set the algorithm may decide that it needs more
-information from the caller to locate the fitting data. For example, if
-a spectrum in a MatrixWorkspace is to be fit with a 1D function it will
-need to know at least the index of that spectrum. To request this
-information Fit dynamically creates relevant properties which the caller
+fitting with a IFunction1D and :ref:`MDWorkspace <MDWorkspace>` for fitting with
+IFunctionMD. After Function and InputWorkspace properties are set the algorithm
+may decide that it needs more information from the caller to locate the fitting
+data. For example, if a spectrum in a MatrixWorkspace is to be fit with a 1D
+function it will need to know at least the index of that spectrum. To request
+this information Fit dynamically creates relevant properties which the caller
 can set. Note that the dynamic properties depend both on the workspace
 and the function. For example, the data in a MatrixWorkspace can be fit
 with a 2D function. In this case all spectra will be used in the fit and
@@ -48,7 +46,7 @@ set before any other.
 
 The function and the initial values for its parameters are set with the
 Function property. A function can be simple or composite. A `simple
-function <../fitfunctions/categories/Functions.html>`__ has a name registered with Mantid
+function <../fitfunctions/categories/FitFunctions.html>`__ has a name registered with Mantid
 framework. The Fit algorithm creates an instance of a function by this
 name. A composite function is an arithmetic sum of two or more functions
 (simple or composite). Each function has a number of named parameters,
@@ -74,7 +72,7 @@ To use a simple function for a fit set its name and initial parameter
 values using the Function property. This property is a comma separated
 list of name=value pairs. The name of the first name=value pairs must be
 "name" and it must be set equal to the name of one of a `simple
-function <../fitfunctions/categories/Functions.html>`__. This name=value pair is followed
+function <../fitfunctions/categories/FitFunctions.html>`__. This name=value pair is followed
 by name=value pairs specifying values for the parameters of this
 function. If a parameter is not set in Function it will be given its
 default value defined by the function. All names are case sensitive. For
@@ -96,7 +94,7 @@ are created when the Formula attribute is set. It is important that
 Formula is defined before initializing the parameters.
 
 A list of the available simple functions can be found
-`here <../fitfunctions/categories/Functions.html>`__.
+`here <../fitfunctions/categories/FitFunctions.html>`__.
 
 Setting a composite function
 ############################
@@ -107,7 +105,7 @@ the Function property. Each simple function definition must be separated
 by a semicolon ';'. For example fitting two Gaussians on a linear
 background might look like this::
 
-   Function: "name=LinearBackground, A0=0.3; 
+   Function: "name=LinearBackground, A0=0.3;
               name=Gaussian, PeakCentre=4.6, Height=10, Sigma=0.5;
               name=Gaussian, PeakCentre=7.6, Height=8, Sigma=0.5"
 
@@ -207,10 +205,12 @@ Examples
 This example shows a simple fit to a Gaussian function. The algorithm
 properties are:
 
-| ``InputWorkspace:  Test``
-| ``WorkspaceIndex:  0``
-| ``Function:        name=Gaussian, PeakCentre=4, Height=1.3, Sigma=0.5``
-| ``Output:          res``
+::
+
+    InputWorkspace:  Test
+    WorkspaceIndex:  0
+    Function:        name=Gaussian, PeakCentre=4, Height=1.3, Sigma=0.5
+    Output:          res
 
 .. figure:: /images/GaussianFit.jpg
    :alt: GaussianFit.jpg
@@ -221,11 +221,13 @@ properties are:
 
 The next example shows a fit of the same data but with a tie.
 
-| ``InputWorkspace:  Test``
-| ``WorkspaceIndex:  0``
-| ``Function:        name=Gaussian, PeakCentre=4, Height=1.3, Sigma=0.5``
-| ``Ties:            Sigma=Height/2``
-| ``Output:          res``
+::
+
+    InputWorkspace:  Test
+    WorkspaceIndex:  0
+    Function:        name=Gaussian, PeakCentre=4, Height=1.3, Sigma=0.5
+    Ties:            Sigma=Height/2
+    Output:          res
 
 .. figure:: /images/GaussianFit_Ties.jpg
    :alt: GaussianFit_Ties.jpg
@@ -238,12 +240,14 @@ This example shows a fit of two overlapping Gaussians on a linear
 background. Here we create a composite function with a LinearBackground
 and two Gaussians:
 
-| ``InputWorkspace:  Test``
-| ``WorkspaceIndex:  0``
-| ``Function:        name=LinearBackground,A0=1;``
-| ``                 name=Gaussian,PeakCentre=4,Height=1.5, Sigma=0.5;``
-| ``                 name=Gaussian,PeakCentre=6,Height=4, Sigma=0.5 ``
-| ``Output:          res``
+::
+
+    InputWorkspace:  Test
+    WorkspaceIndex:  0
+    Function:        name=LinearBackground,A0=1;
+                     name=Gaussian,PeakCentre=4,Height=1.5, Sigma=0.5;
+                     name=Gaussian,PeakCentre=6,Height=4, Sigma=0.5
+    Output:          res
 
 .. figure:: /images/Gaussian2Fit.jpg
    :alt: Gaussian2Fit.jpg
@@ -255,13 +259,15 @@ and two Gaussians:
 This example repeats the previous one but with the Sigmas of the two
 Gaussians tied:
 
-| ``InputWorkspace:  Test``
-| ``WorkspaceIndex:  0``
-| ``Function:        name=LinearBackground,A0=1;``
-| ``                 name=Gaussian,PeakCentre=4,Height=1.5, Sigma=0.5;``
-| ``                 name=Gaussian,PeakCentre=6,Height=4, Sigma=0.5 ``
-| ``Ties:            f2.Sigma = f1.Sigma``
-| ``Output:          res``
+::
+
+    InputWorkspace:  Test
+    WorkspaceIndex:  0
+    Function:        name=LinearBackground,A0=1;
+                     name=Gaussian,PeakCentre=4,Height=1.5, Sigma=0.5;
+                     name=Gaussian,PeakCentre=6,Height=4, Sigma=0.5
+    Ties:            f2.Sigma = f1.Sigma
+    Output:          res
 
 .. figure:: /images/Gaussian2Fit_Ties.jpg
    :alt: Gaussian2Fit_Ties.jpg
diff --git a/Code/Mantid/docs/source/algorithms/GoniometerAnglesFromPhiRotation-v1.rst b/Code/Mantid/docs/source/algorithms/GoniometerAnglesFromPhiRotation-v1.rst
index 1a17ffce4ad04ed6751432be3539e3c1f800f1eb..24b309ad6f68459b2a17a7cc024a94f978d2191c 100644
--- a/Code/Mantid/docs/source/algorithms/GoniometerAnglesFromPhiRotation-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/GoniometerAnglesFromPhiRotation-v1.rst
@@ -17,4 +17,30 @@ only in their phi rotation.
 If the phi angles are known, this algorithm attempts to find the common
 chi and omega rotations.
 
+Usage
+-----
+
+.. include:: ../usagedata-note.txt
+
+.. testcode:: exGoniometerAnglesFromPhiRotation 
+
+   # Load Peaks found in SXD23767.raw 
+   ws1 =Load(Filename='SXD23767.peaks')
+   ws2 = ws1.clone()
+
+   #Set orientated lattice
+   ublist = [-0.06452276,  0.2478114,  -0.23742194, 0.29161678, -0.00914316, -0.12523779, 0.06958942, -0.1802702,  -0.14649001]
+   SetUB(Workspace=ws1,UB=ublist)
+
+   # Run Algorithm 
+   result = GoniometerAnglesFromPhiRotation(ws1,ws2,Tolerance=0.5,MIND=0,MAXD=2)
+
+   print "Chi: %.1f, Omega: %.1f, Indexed: %i, AvErrIndex: %.4f AvErrAll: %.4f" % (  result[0], result[1], result[2], result[3], result[4] )
+
+Output:
+
+.. testoutput:: exGoniometerAnglesFromPhiRotation
+
+   Chi: 90.0, Omega: 90.0, Indexed: 300, AvErrIndex: 0.2114 AvErrAll: 0.2114
+
 .. categories::
diff --git a/Code/Mantid/docs/source/algorithms/GroupDetectors-v1.rst b/Code/Mantid/docs/source/algorithms/GroupDetectors-v1.rst
index 54ab66eda1d7da80e5711f4e2ba84686d87cbb0a..5d300deff4c8eeeae048689034ef38b15262928b 100644
--- a/Code/Mantid/docs/source/algorithms/GroupDetectors-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/GroupDetectors-v1.rst
@@ -59,7 +59,7 @@ An example of an input file follows::
  1
  64
  1 2 3 4 5 6 7 8 9 10
- 11 12 13 14 15 16 17 18 19 20`
+ 11 12 13 14 15 16 17 18 19 20
  21 22 23 24 25 26 27 28 29 30
  31 32 33 34 35 36 37 38 39 40
  41 42 43 44 45 46 47 48 49 50
diff --git a/Code/Mantid/docs/source/algorithms/ISISIndirectEnergyTransfer-v1.rst b/Code/Mantid/docs/source/algorithms/ISISIndirectEnergyTransfer-v1.rst
new file mode 100644
index 0000000000000000000000000000000000000000..5f295ba1884841e02812a51158544e47785d683c
--- /dev/null
+++ b/Code/Mantid/docs/source/algorithms/ISISIndirectEnergyTransfer-v1.rst
@@ -0,0 +1,42 @@
+.. algorithm::
+
+.. summary::
+
+.. alias::
+
+.. properties::
+
+Description
+-----------
+
+Performs a reduction from raw time of flight to energy transfer for an inelastic
+indirect geometry instrument at ISIS.
+
+Usage
+-----
+
+.. include:: ../usagedata-note.txt
+
+**Example - IRIS energy conversion**
+
+.. testcode:: ExIRISReduction
+
+   ISISIndirectEnergyTransfer(InputFiles='IRS21360.raw',
+                              OutputWorkspace='IndirectReductions',
+                              Instrument='IRIS',
+                              Analyser='graphite',
+                              Reflection='002',
+                              SpectraRange=[3, 53])
+
+   reduction_workspace_names = mtd['IndirectReductions'].getNames()
+
+   for workspace_name in reduction_workspace_names:
+      print workspace_name
+
+Output:
+
+.. testoutput:: ExIRISReduction
+
+   IRS21360_graphite002_red
+
+.. categories::
diff --git a/Code/Mantid/docs/source/algorithms/IndexPeaks-v1.rst b/Code/Mantid/docs/source/algorithms/IndexPeaks-v1.rst
index 8f7f901158a2ee9decd3133f6c47654253b24227..ad807f0ed0c0a29b6975e736dd61ab4fb2e7bc80 100644
--- a/Code/Mantid/docs/source/algorithms/IndexPeaks-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/IndexPeaks-v1.rst
@@ -25,4 +25,31 @@ from an integer will have its (h,k,l) set to (0,0,0). The calculated
 Miller indices can either be rounded to the nearest integer value, or
 can be left as decimal fractions.
 
+Usage
+-----
+
+**Example - a simple example of IndexPeaks**
+
+.. include:: ../usagedata-note.txt
+
+.. testcode:: ExIndexPeaksSimple
+
+   # Load Peaks found in SXD23767.raw 
+   Load(Filename='SXD23767.peaks',OutputWorkspace='peaks_qLab')
+
+   #Set orientated lattice
+   ubMatrix = [-0.06452276,  0.2478114,  -0.23742194, 0.29161678, -0.00914316, -0.12523779, 0.06958942, -0.1802702,  -0.14649001]
+   SetUB('peaks_qLab',UB=ubMatrix)
+
+   # Run Algorithm 
+   indexed =IndexPeaks(PeaksWorkspace='peaks_qLab',Tolerance=0.12,RoundHKLs=1)
+
+   print "Number of Indexed Peaks: ", indexed[0]
+
+Output:
+
+.. testoutput:: ExIndexPeaksSimple
+
+   Number of Indexed Peaks:  147
+
 .. categories::
diff --git a/Code/Mantid/docs/source/algorithms/IndexSXPeaks-v1.rst b/Code/Mantid/docs/source/algorithms/IndexSXPeaks-v1.rst
index aebe294d52343bee07cbde5f0de5c7b41d757793..682bdd0bc92ab135d2c9b675f6aea222cdb6bf82 100644
--- a/Code/Mantid/docs/source/algorithms/IndexSXPeaks-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/IndexSXPeaks-v1.rst
@@ -9,19 +9,18 @@
 Description
 -----------
 
-Given a `PeaksWorkspace <http://www.mantidproject.org/PeaksWorkspace>`_ and a set of
-lattice parameters, attempts to tag each peak with a HKL value by comparing
-d-spacings between potential HKL matches and the peaks as well as angles between Q
-vectors.
+Given a :ref:`PeaksWorkspace <PeaksWorkspace>` and a set of lattice parameters,
+attempts to tag each peak with a HKL value by comparing d-spacings between
+potential HKL matches and the peaks as well as angles between Q vectors.
 
 Usage Notes
 -----------
 
 This algorithm does not generate a UB Matrix, it will only index peaks.
-Run :ref:`CalculateUMatrix <algm-CalculateUMatrix>`
-algorithm after executing this algorithm in order
-to attach a UB Matrix onto the sample. The :ref:`CopySample <algm-CopySample>`
-algorithm will allow this UB Matrix to be transfered between workspaces.
+Run :ref:`CalculateUMatrix <algm-CalculateUMatrix>` algorithm after executing
+this algorithm in order to attach a UB Matrix onto the sample. The
+:ref:`CopySample <algm-CopySample>` algorithm will allow this UB Matrix to be
+transfered between workspaces.
 
 Usage
 -----
diff --git a/Code/Mantid/docs/source/algorithms/InelasticIndirectReduction-v1.rst b/Code/Mantid/docs/source/algorithms/InelasticIndirectReduction-v1.rst
deleted file mode 100644
index f5290faa11a9e24551c43df04819679e35995818..0000000000000000000000000000000000000000
--- a/Code/Mantid/docs/source/algorithms/InelasticIndirectReduction-v1.rst
+++ /dev/null
@@ -1,42 +0,0 @@
-.. algorithm::
-
-.. summary::
-
-.. alias::
-
-.. properties::
-
-Description
------------
-
-Performs a reduction for an inelastic indirect geometry instrument.
-
-Usage
------
-
-.. include:: ../usagedata-note.txt
-
-**Example - IRIS energy conversion:**
-
-.. testcode:: ExIRISReduction
-
-   InelasticIndirectReduction(InputFiles='IRS21360.raw',
-      OutputWorkspace='IndirectReductions',
-      Instrument='IRIS',
-      Analyser='graphite',
-      Reflection='002',
-      DetectorRange=[3, 53],
-      SaveFormats=['nxs'])
-
-   reduction_workspace_names = mtd['IndirectReductions'].getNames()
-
-   for workspace_name in reduction_workspace_names:
-      print workspace_name
-
-Output:
-
-.. testoutput:: ExIRISReduction
-
-   irs21360_graphite002_red
-
-.. categories::
diff --git a/Code/Mantid/docs/source/algorithms/IntegrateEllipsoids-v1.rst b/Code/Mantid/docs/source/algorithms/IntegrateEllipsoids-v1.rst
index 831d0c6d5d858af5fb5ce90a6b224ede544d19e6..28bbc9f39371d863c08494577e5b5af3edea3ffe 100644
--- a/Code/Mantid/docs/source/algorithms/IntegrateEllipsoids-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/IntegrateEllipsoids-v1.rst
@@ -14,7 +14,8 @@ Overview and similar algorithms
 
 This algorithm will integrate disjoint single crystal Bragg peaks by
 summing the number of raw or weighted events in a 3D ellipsoidal peak region in
-reciprocal space and subtracting an estimate of the background obtained
+reciprocal space (See *IntegrateInHKL* option for integrating in HKL) 
+and subtracting an estimate of the background obtained
 from an ellipsoidal shell. In some ways it is similar to the
 :ref:`algm-IntegratePeaksMD` algorithm. In particular the size parameters to
 this algorithm are also specified in inverse Angstroms and the
@@ -91,6 +92,13 @@ Explanation of Inputs
    :math:`0 < PeakSize \leq BackgroundInnerSize` and 
    :math:`BackgroundInnerSize < BackgroundOuterSize \leq RegionRadius`
 
+-  If the *IntegrateInHKL* option is selected, then HKL space is used for
+   the integration instead of reciprocal space.  This option may be useful
+   for large unit cells where the radius of integration needs to be very different
+   for peaks at low Q and high Q.  With this option the *PeakSize*, 
+   *BackgroundInnerSize* and *BackgroundOuterSize* are specified in HKL and they
+   just need to be smaller than 0.5.
+	
 -  The integrated intensities will be set in the specified
    *OutputWorkspace*. If this is different from the input *PeaksWorkspace*,
    the input peaks workspace will be copied to the *OutputWorkspace*
diff --git a/Code/Mantid/docs/source/algorithms/IntegrateMDHistoWorkspace-v1.rst b/Code/Mantid/docs/source/algorithms/IntegrateMDHistoWorkspace-v1.rst
new file mode 100644
index 0000000000000000000000000000000000000000..06bac0efb53609183d103dbbb53bee59e5400941
--- /dev/null
+++ b/Code/Mantid/docs/source/algorithms/IntegrateMDHistoWorkspace-v1.rst
@@ -0,0 +1,109 @@
+
+.. algorithm::
+
+.. summary::
+
+.. alias::
+
+.. properties::
+
+Description
+-----------
+
+Provides limited integration of a :ref:`MDHistoWorkspace <MDHistoWorkspace>` in n-dimensions. Integration is always axis-aligned. Dimensions can only be integrated out, but no finer rebinning is permitted. Dimensions that do not require further rebinning will be left intact provided that the the binning parameters for those dimensions are not specified. For dimensions that are integrated, limits should be provided to give the range of the data to keep.
+
+Binning
+~~~~~~~
+
+The *P1Bin* corresponds to the first dimension of the MDHistoWorkspace, *P2Bin* to the second and so on. *P1Bin=[-1, 1]* indicates that we will integrate this dimension between -1 and 1. *P1Bins=[]* indicates that the shape of this dimension should be unchanged from the input. *P1Bins=[-1,0,1]* is a special case, the zero indicates that the same bin width as the input dimension would be used, but the minimum and maximum will also be used to crop the dimension. In this latter form, the limits may be expanded to ensure that there is no partial bins in the non-integrated dimension (see warning messages).
+
+Weights 
+~~~~~~~
+
+The algorithm works by creating the *OutputWorkspace* in the correct shape. Each bin in the OutputWorkspace is treated in turn. For each bin in the OutputWorkspace, we find those bins in the *InputWorkspace* that overlap and therefore could contribute to the OutputBin. For any contributing bin, we calculate the fraction overlap and treat this a weighting factor. For each contributing bin *Signal*, and :math:`Error^{2}`, and *Number of Events* values are extracted and multiplied by the  weight. These values are summed for all contributing input bins before being assigned to the corresponding output bin. For plotting the *OutputWorkspace*, it is important to select the Number of Events normalization option to correctly account for the weights.
+
+.. figure:: /images/PreIntegrateMD.png
+   :alt: PreIntegrateMD.png
+   :width: 400px
+   :align: center
+   
+   Integration Input. 3D.
+   
+.. figure:: /images/IntegrateMD.png
+   :alt: IntegrateMD.png
+   :width: 400px
+   :align: center
+   
+   Integration Output. 2nd and 3rd dimensions integrated out. 
+   
+
+Usage
+-----
+
+**Example - IntegrateMDHistoWorkspace simple cut**
+
+.. testcode:: IntegrateMDHistoWorkspaceExampleSimpleCut
+
+   mdws = CreateMDWorkspace(Dimensions=3, Extents=[-10,10,-10,10,-10,10], Names='A,B,C',Units='U,U,U')
+   FakeMDEventData(InputWorkspace=mdws, PeakParams=[100000,-5,0,0,1])
+   FakeMDEventData(InputWorkspace=mdws, PeakParams=[100000,0,0,0,1])
+   FakeMDEventData(InputWorkspace=mdws, PeakParams=[100000,5,0,0,1])
+   #Histogram to give 3 unintegrated dimensions
+   high_d_cut =CutMD(InputWorkspace=mdws, P1Bin=[-10, 0.1, 10], P2Bin=[-10, 0.1, 10], P3Bin=[-10, 0.1, 10], NoPix=True)
+   #Integrate out 2 dimensions
+   low_d_cut =IntegrateMDHistoWorkspace(InputWorkspace=high_d_cut, P1Bin=[], P2Bin=[-2,2], P3Bin=[-5,5])
+
+   non_integrated_dims = low_d_cut.getNonIntegratedDimensions()
+   print 'Number of non integrated dimensions after integration are %i'  % len(non_integrated_dims)
+   for dim in non_integrated_dims:
+       print 'Non integrated dimension is %s' % dim.getName()
+       print 'Limits are from %0.2f to %0.2f' % (dim.getMinimum(), dim.getMaximum())
+
+Output:
+
+.. testoutput:: IntegrateMDHistoWorkspaceExampleSimpleCut
+
+  Number of non integrated dimensions after integration are 1
+  Non integrated dimension is ['zeta', 0, 0]
+  Limits are from -10.00 to 10.00
+
+**Example - IntegrateMDHistoWorkspace line cut**
+
+Similar to the simple cut in the previous example, but for the non-integrated dimension limits may be provided and the step size is copied across from the input dimension.
+maximum and minimum limits may need to be adjusted to ensure no partial binning in the non-integrated dimension.
+
+.. testcode:: IntegrateMDHistoWorkspaceExampleLineCut
+
+   mdws = CreateMDWorkspace(Dimensions=3, Extents=[-10,10,-10,10,-10,10], Names='A,B,C',Units='U,U,U')
+   FakeMDEventData(InputWorkspace=mdws, PeakParams=[100000,-5,0,0,1])
+   FakeMDEventData(InputWorkspace=mdws, PeakParams=[100000,0,0,0,1])
+   FakeMDEventData(InputWorkspace=mdws, PeakParams=[100000,5,0,0,1])
+   #Histogram to give 3 unintegrated dimensions
+   high_d_cut =CutMD(InputWorkspace=mdws, P1Bin=[-10, 0.1, 10], P2Bin=[-10, 0.1, 10], P3Bin=[-10, 0.1, 10], NoPix=True)
+   #Integrate out 2 dimensions
+   copy_key = 0
+         
+   low_d_cut=IntegrateMDHistoWorkspace(InputWorkspace=high_d_cut,P1Bin=[-9.48,copy_key,9.01], P2Bin=[-2,2], P3Bin=[-5,5])
+
+   dim = high_d_cut.getDimension(0)
+   print 'Input bin width is %0.2f' % float((dim.getMaximum() - dim.getMinimum())/dim.getNBins())
+
+   non_integrated_dims = low_d_cut.getNonIntegratedDimensions()
+   print 'Number of non integrated dimensions after integration are %i'  % len(non_integrated_dims)
+   for dim in non_integrated_dims:
+       print 'Non integrated dimension is %s' % dim.getName()
+       print 'Limits are from %0.2f to %0.2f' % (dim.getMinimum(), dim.getMaximum())
+       print 'Output bin width is %0.2f' % float((dim.getMaximum() - dim.getMinimum() )/dim.getNBins())  
+
+Output:
+
+.. testoutput:: IntegrateMDHistoWorkspaceExampleLineCut 
+
+  Input bin width is 0.10
+  Number of non integrated dimensions after integration are 1
+  Non integrated dimension is ['zeta', 0, 0]
+  Limits are from -9.50 to 9.10
+  Output bin width is 0.10
+  
+.. categories::
+
diff --git a/Code/Mantid/docs/source/algorithms/IntegratePeaksHybrid-v1.rst b/Code/Mantid/docs/source/algorithms/IntegratePeaksHybrid-v1.rst
index 5b8097dd6b8ac99580b10c9c0821ad035fcec62e..d72de7af49c15bb076eb30119459cc15d56da7e0 100644
--- a/Code/Mantid/docs/source/algorithms/IntegratePeaksHybrid-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/IntegratePeaksHybrid-v1.rst
@@ -15,8 +15,8 @@ The NumberOfBins and BackgroundOuterRadius are global to all Peaks. The actual b
 Integrates arbitary shaped single crystal peaks defined on an
 :ref:`MDHistoWorkspace <MDHistoWorkspace>` using connected component
 analysis to determine regions of interest around each peak of the
-`PeaksWorkspace <http://www.mantidproject.org/PeaksWorkspace>`_. The output is an integrated
-`PeaksWorkspace <http://www.mantidproject.org/PeaksWorkspace>`_ as well as a group of images :ref:`WorkspaceGroup <WorkspaceGroup>` of :ref:`MDWorkspaces <MDWorkspace>`  containing the
+:ref:`PeaksWorkspace <PeaksWorkspace>`. The output is an integrated
+:ref:`PeaksWorkspace <PeaksWorkspace>` as well as a group of images :ref:`WorkspaceGroup <WorkspaceGroup>` of :ref:`MDWorkspaces <MDWorkspace>`  containing the
 labels assigned to each cluster for diagnostic and visualisation
 purposes.
 
@@ -48,7 +48,7 @@ the detector/TOF space is no longer accessible.
 No Cluster Corresponding to Peak
 ################################
 
-This is because the input `PeaksWorkspace <http://www.mantidproject.org/PeaksWorkspace>`_ has peaks
+This is because the input :ref:`PeaksWorkspace <PeaksWorkspace>` has peaks
 that do not align with peaks in the image. The error could either be on
 the side of the input PeaksWorkspace (spurious peaks), or of the
 :ref:`MDHistoWorkspace <MDHistoWorkspace>` generated as part of processing.
diff --git a/Code/Mantid/docs/source/algorithms/IntegratePeaksUsingClusters-v1.rst b/Code/Mantid/docs/source/algorithms/IntegratePeaksUsingClusters-v1.rst
index 8cd1fce12292e732969121cbe658a2b18298231c..1d6e1510eee73f3194a6807d7c07bdddd26b87a4 100644
--- a/Code/Mantid/docs/source/algorithms/IntegratePeaksUsingClusters-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/IntegratePeaksUsingClusters-v1.rst
@@ -12,8 +12,8 @@ Description
 Integrates arbitary shaped single crystal peaks defined on an
 :ref:`MDHistoWorkspace <MDHistoWorkspace>` using connected component
 analysis to determine regions of interest around each peak of the
-`PeaksWorkspace <http://www.mantidproject.org/PeaksWorkspace>`_. The output is an integrated
-`PeaksWorkspace <http://www.mantidproject.org/PeaksWorkspace>`_ as well as an image containing the
+:ref:`PeaksWorkspace <PeaksWorkspace>`. The output is an integrated
+:ref:`PeaksWorkspace <PeaksWorkspace>` as well as an image containing the
 labels assigned to each cluster for diagnostic and visualisation
 purposes.
 
@@ -69,7 +69,7 @@ the detector/TOF space is no longer accessible.
 No Cluster Corresponding to Peak
 ################################
 
-This is because the input `PeaksWorkspace <http://www.mantidproject.org/PeaksWorkspace>`_ has peaks
+This is because the input :ref:`PeaksWorkspace <PeaksWorkspace>` has peaks
 that do not align with peaks in the image. The error could either be on
 the side of the input PeaksWorkspace (spurious peaks), or of the
 :ref:`MDHistoWorkspace <MDHistoWorkspace>` generated as part of processing.
diff --git a/Code/Mantid/docs/source/algorithms/LRScalingFactors-v1.rst b/Code/Mantid/docs/source/algorithms/LRScalingFactors-v1.rst
new file mode 100644
index 0000000000000000000000000000000000000000..d0089c67d3bedc2d7de3245a320de6ec61f0bcb7
--- /dev/null
+++ b/Code/Mantid/docs/source/algorithms/LRScalingFactors-v1.rst
@@ -0,0 +1,41 @@
+.. algorithm::
+
+.. summary::
+
+.. alias::
+
+.. properties::
+
+Description
+-----------
+
+Used in the Liquids Reflectometer reduction at the SNS, this algorithm
+computes the absolute scaling factors for the data sets that we are going to stitch 
+together.
+
+The algorithm runs through a sequence of direct beam data sets
+to extract scaling factors. The method was developed by J. Ankner (ORNL).
+
+As we loop through, we find matching data sets with the only
+difference between the two is an attenuator.
+The ratio of those matching data sets allows use to rescale
+a direct beam run taken with a larger number of attenuators
+to a standard data set taken with tighter slit settings and
+no attenuators.
+
+The normalization run for a data set taken in a given slit setting
+configuration can then be expressed in terms of the standard 0-attenuator
+data set with:
+   D_i = F_i D_0
+
+  Here's an example of runs and how they are related to F.
+
+        run: 55889, att: 0, s1: 0.26, s2: 0.26
+        run: 55890, att: 1, s1: 0.26, s2: 0.26
+        run: 55891, att: 1, s1: 0.33, s2: 0.26 --> F = 55891 / 55890
+        run: 55892, att: 1, s1: 0.45, s2: 0.26 --> F = 55892 / 55890
+        run: 55895, att: 1, s1: 0.81, s2: 0.26
+        run: 55896, att: 2, s1: 0.81, s2: 0.26
+        run: 55897, att: 2, s1: 1.05, s2: 0.35 --> F = 55897 / 55896 * 55895 / 55890
+
+.. categories::
diff --git a/Code/Mantid/docs/source/algorithms/LRSubtractAverageBackground-v1.rst b/Code/Mantid/docs/source/algorithms/LRSubtractAverageBackground-v1.rst
new file mode 100644
index 0000000000000000000000000000000000000000..9256c1b11db04fbfddb92c3b9b464315effcd090
--- /dev/null
+++ b/Code/Mantid/docs/source/algorithms/LRSubtractAverageBackground-v1.rst
@@ -0,0 +1,15 @@
+.. algorithm::
+
+.. summary::
+
+.. alias::
+
+.. properties::
+
+Description
+-----------
+
+Used in the Liquids Reflectometer reduction at the SNS, this algorithm
+compute and subtracts the background from the reflectivity peak. 
+
+.. categories::
diff --git a/Code/Mantid/docs/source/algorithms/LoadAscii-v2.rst b/Code/Mantid/docs/source/algorithms/LoadAscii-v2.rst
index 0592f231dc32bfb44b282f34805c39e989839f94..f03e99398fa040e4b6801da95934db324f6add27 100644
--- a/Code/Mantid/docs/source/algorithms/LoadAscii-v2.rst
+++ b/Code/Mantid/docs/source/algorithms/LoadAscii-v2.rst
@@ -14,7 +14,7 @@ stores it in a `Workspace2D <http://www.mantidproject.org/Workspace2D>`_ as data
 the file must be organized in columns separated by commas, tabs, spaces,
 colons or semicolons. Only one separator type can be used throughout the
 file; use the "Separator" property to tell the algorithm which to use.
-The algorithm `SaveAscii2 <http://www.mantidproject.org/SaveAscii2>`_ is normally able to produce
+The algorithm :ref:`SaveAscii2 <algm-SaveAscii2-v2>` is normally able to produce
 such a file.
 
 The format must be:
diff --git a/Code/Mantid/docs/source/algorithms/LoadFITS-v1.rst b/Code/Mantid/docs/source/algorithms/LoadFITS-v1.rst
index dfeae5b13f7f708ab961b2d2f3ac96cdc33508b7..11ebc6c5768f5fda89884c1650fbecc31e1691b1 100644
--- a/Code/Mantid/docs/source/algorithms/LoadFITS-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/LoadFITS-v1.rst
@@ -20,13 +20,35 @@ property. The workspaces included in the group are named with the same
 name and an appendix _1, _2, etc., incremented sequentially as new
 files are loaded with the same OutputWorkspace property.
 
-The current implementation of this algorithm only supports 2D files
-(FITS images with two axes), and it should in principle be able to
-load FITS files from different sources.
+The way image pixels are loaded into the resulting workspaces depends
+on the porperty LoadAsRectImg. If it is set as false, one spectrum
+will be created for every image pixel. Otherwise, one spectrum will be
+created for every image row.
+
+When LoadAsRectImg is true, the workspaces created by this algorithm
+contain one spectrum per row (and one bin per column). The first
+spectrum corresponds to the first (topmost) row and the last spectrum
+corresponds to the last (bottom) column. With this type of workspace
+you can display the image with a "color fill plot" or plot2D.
+
+When LoadAsRectImg is false, the workspaces created by this algorithm
+contain one spectrum per pixel. The first spectrum corresponds to the
+top-left corner and the last spectrum to the bottom-right corner. The
+image pixels are assigned to spectra row by row, i.e., the first
+spectra correspond to the first or topmost row, the next spectra
+correspond to the next rows, going from top down, until finally the
+last spectra correspond to the last or bottom row.
+
 
-The workspaces created by this algorithm contain one spectrum per
-pixel. The first spectrum correspond to the top-left corner and the
-last spectrum to the bottom-right corner.
+The current implementation of this algorithm only supports 2D files
+(FITS images with two axes). With this condition, in principle this
+algorithm should be able to load any standard FITS file, and also
+those who do not deviate too much from the standard. See below an
+explanation of the minimum set of basic standard header entries that
+this algorithm requires (those should be present in any FITS file), So
+far, the algorithm has been tested with files produced by the cameras
+used for the IMAT instrument at ISIS, and Starlight Xpress CCD cameras
+used for calibration of other instruments at ISIS.
 
 FITS header entries
 ###################
@@ -53,9 +75,50 @@ This algorithm uses one child algorithm:
 Usage
 -----
 
-**Example**
+Example 1: loading one spectrum per image row
+#############################################
+
+.. testcode:: LoadFITS1SpectrumPerRow
+
+
+    ws_name = 'FITSimgs'
+    wsg = LoadFITS(Filename='FITS_small_01.fits', LoadAsRectImg=1, OutputWorkspace=ws_name)
+    ws = wsg.getItem(0)
+
+    # A couple of standard FITS header entries
+    bpp_log = 'BITPIX'
+    try:
+        log = ws.getRun().getLogData(bpp_log).value
+        print "Bits per pixel: %s" % int(log)
+    except RuntimeError:
+        print "Could not find the keyword '%s' in this FITS file" % bpp_log
+
+    axis1_log = 'NAXIS1'
+    axis2_log = 'NAXIS2'
+    try:
+        log1 = ws.getRun().getLogData(axis1_log).value
+        log2 = ws.getRun().getLogData(axis2_log).value
+        print "FITS image size: %s x %s pixels" % (int(log1), int(log2))
+        print "Number of spectra in the output workspace: %d" % ws.getNumberHistograms()
+    except RuntimeError:
+        print "Could not find the keywords '%s' and '%s' in this FITS file" % (axis1_log, axis2_log)
+
+.. testcleanup:: LoadFITS1SpectrumPerRow
+
+    DeleteWorkspace(ws_name)
+
+Output:
+
+.. testoutput:: LoadFITS1SpectrumPerRow
+
+   Bits per pixel: 16
+   FITS image size: 512 x 512 pixels
+   Number of spectra in the output workspace: 512
+
+Example 2: loading one spectrum per pixel
+#########################################
 
-.. testcode:: LoadFITS
+.. testcode:: LoadFITSManySpectra
 
     ws_name = 'FITSws'
     wsg = LoadFITS(Filename='FITS_small_01.fits', OutputWorkspace=ws_name)
@@ -79,13 +142,13 @@ Usage
     except RuntimeError:
         print "Could not find the keywords '%s' and '%s' in this FITS file" % (axis1_log, axis2_log)
 
-.. testcleanup:: LoadFITS
+.. testcleanup:: LoadFITSManySpectra
 
     DeleteWorkspace(ws_name)
 
 Output:
 
-.. testoutput:: LoadFITS
+.. testoutput:: LoadFITSManySpectra
 
    Bits per pixel: 16
    FITS image size: 512 x 512 pixels
diff --git a/Code/Mantid/docs/source/algorithms/LoadLiveData-v1.rst b/Code/Mantid/docs/source/algorithms/LoadLiveData-v1.rst
index 771161dfa44ee055ff9e8fb1412e0c77d19158c5..d0e2ce5260f95db0bc15bfac5223e09dd90a1fc2 100644
--- a/Code/Mantid/docs/source/algorithms/LoadLiveData-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/LoadLiveData-v1.rst
@@ -22,7 +22,7 @@ Data Processing
 ###############
 
 -  Each time LoadLiveData is called, a chunk of data is loaded from the
-   `LiveListener <http://www.mantidproject.org/LiveListener>`_.
+   live listener.
 
    -  This consists of all the data collected since the previous call.
    -  The data is saved in a temporary :ref:`workspace <workspace>`.
diff --git a/Code/Mantid/docs/source/algorithms/LoadMappingTable-v1.rst b/Code/Mantid/docs/source/algorithms/LoadMappingTable-v1.rst
index 65b4a90d83d20a3eabc57b404a45cd385b5b407d..cabd520bab8bfb1d4cd2016a487d460c2293c691 100644
--- a/Code/Mantid/docs/source/algorithms/LoadMappingTable-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/LoadMappingTable-v1.rst
@@ -9,14 +9,12 @@
 Description
 -----------
 
-Loads the mapping table between spectra and `IDetector <http://www.mantidproject.org/IDetector>`__
-from a RAW file. It fills the
-`SpectraToDetectorMap <http://www.mantidproject.org/SpectraToDetectorMap>`__ object contained in a
-:ref:`workspace <workspace>`. This algorithm will fail if the
-:ref:`workspace <workspace>` does not already point to a full
-:ref:`instrument <instrument>` :ref:`geometry <geometry>` (which usually means
-it must be run after
-:ref:`algm-LoadInstrument`/:ref:`algm-LoadInstrumentFromRaw`).
+Loads the mapping table between spectra and detectors from a RAW file. It fills
+the spectra to detector map object contained in a :ref:`workspace <workspace>`.
+This algorithm will fail if the :ref:`workspace <workspace>` does not already
+point to a full :ref:`instrument <instrument>` :ref:`geometry <geometry>` (which
+usually means it must be run after :ref:`algm-LoadInstrument` or
+:ref:`algm-LoadInstrumentFromRaw`).
 
 The association is one to many, i.e. a spectrum can have one or many
 detectors contributing to it. Alternatively the same spectrum can
diff --git a/Code/Mantid/docs/source/algorithms/LoadRaw-v3.rst b/Code/Mantid/docs/source/algorithms/LoadRaw-v3.rst
index 9abe2f9085aee0d9cc6bedc89a35155084ba1bbb..8cb305cfedf75087f718e74f1e13575bbec6b5a2 100644
--- a/Code/Mantid/docs/source/algorithms/LoadRaw-v3.rst
+++ b/Code/Mantid/docs/source/algorithms/LoadRaw-v3.rst
@@ -9,7 +9,7 @@
 Description
 -----------
 
-The LoadRaw algorithm stores data from the `RAW <http://www.mantidproject.org/Raw File>`__ file in a
+The LoadRaw algorithm stores data from the :ref:`RAW file <RAW File>` in a
 `Workspace2D <http://www.mantidproject.org/Workspace2D>`__, which will naturally contain histogram
 data with each spectrum going into a separate histogram. The time bin
 boundaries (X values) will be common to all histograms and will have
@@ -21,7 +21,7 @@ be set to be the square root of the number of counts in the bin.
 Optional properties
 ###################
 
-If only a portion of the data in the `RAW <http://www.mantidproject.org/Raw File>`__ file is
+If only a portion of the data in the :ref:`RAW file <RAW File>` is
 required, then the optional 'spectrum' properties can be set before
 execution of the algorithm. Prior to loading of the data the values
 provided are checked and the algorithm will fail if they are found to be
@@ -35,7 +35,7 @@ and the different periods will be output as separate workspaces, which
 after the first one will have the period number appended (e.g.
 OutputWorkspace\_period). Each workspace will share the same
 `Instrument <http://www.mantidproject.org/Instrument>`__, SpectraToDetectorMap and
-`Sample <http://www.mantidproject.org/Sample>`__ objects. If the optional 'spectrum' properties are
+`sample objects <../api/python/mantid/api/Sample.html>`__. If the optional 'spectrum' properties are
 set for a multiperiod dataset, then they will ignored.
 
 If PeriodList property isn't empty then only periods listed there will be
@@ -60,7 +60,7 @@ aspects of the output `Workspace <http://www.mantidproject.org/Workspace>`__:
    `Instrument <http://www.mantidproject.org/Instrument>`__.
 -  :ref:`algm-LoadLog` - Will look for any log files in the same
    directory as the RAW file and load their data into the workspace's
-   `Sample <http://www.mantidproject.org/Sample>`__ object.
+   `sample objects <../api/python/mantid/api/Sample.html>`__.
 
 Previous Versions
 -----------------
diff --git a/Code/Mantid/docs/source/algorithms/MDHistoToWorkspace2D-v1.rst b/Code/Mantid/docs/source/algorithms/MDHistoToWorkspace2D-v1.rst
index 121113f45560a924aa65008815dffabc574412d8..77c80845485fcb83dd65c84eefe07a3d6816820f 100644
--- a/Code/Mantid/docs/source/algorithms/MDHistoToWorkspace2D-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/MDHistoToWorkspace2D-v1.rst
@@ -19,4 +19,30 @@ This tool is useful as many algorithms in Mantid only apply to
 Workspace2D. After conversion with MDHistoToWorkspace2D such algorithms
 can also be applied to MD data.
 
+Usage
+-----
+
+**Example - Flatten a small workspace:**
+
+.. testcode:: ExMDHistoToWorkspace2D
+
+   # Create input workspace
+   CreateMDWorkspace(Dimensions=3, Extents='-10,10,-10,10,-10,10', Names='A,B,C', Units='U,U,U', OutputWorkspace='demo')
+   FakeMDEventData(InputWorkspace='demo', PeakParams='32,0,0,0,1')
+   input = BinMD(InputWorkspace='demo', AlignedDim0='A,-2,2,4', AlignedDim1='B,-2,2,4', AlignedDim2='C,-2,2,4')
+
+   # Run the algorithm 
+   output = MDHistoToWorkspace2D(InputWorkspace='input')
+
+   # print 6th group of 4 bins in both input and output workspaces
+   print "part of MD workspace",input.getSignalArray()[1,1]
+   print "corresponding part of 2D workspace",output.dataY(5) 
+
+Output:
+
+.. testoutput:: ExMDHistoToWorkspace2D
+
+   part of MD workspace [ 0.  4.  5.  0.]
+   corresponding part of 2D workspace [ 0.  4.  5.  0.]
+
 .. categories::
diff --git a/Code/Mantid/docs/source/algorithms/MaskDetectors-v1.rst b/Code/Mantid/docs/source/algorithms/MaskDetectors-v1.rst
index 4f0fc656a5cec665cb14ba4dc04d84d3ce61ec7a..856d5913457b81275d9528920120bd15d5aba70c 100644
--- a/Code/Mantid/docs/source/algorithms/MaskDetectors-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/MaskDetectors-v1.rst
@@ -10,7 +10,7 @@ Description
 -----------
 
 This algorithm will flag the detectors listed as
-masked(\ `IDetector <http://www.mantidproject.org/IDetector>`__::isMasked() method) and will zero the
+masked(IDetector::isMasked() method) and will zero the
 data in the spectra for MatrixWorkspaces related to those detectors.  For PeaksWorkspaces, only the 
 detectors listed are masked and the mask must be specified by a DetectorList or MaskedWorkspace.
 
@@ -32,10 +32,9 @@ will be masked in Workspace.
 Mask Detectors According to Masking Workspace
 #############################################
 
-If the input MaskedWorkspace is a `MaskWorkspace <http://www.mantidproject.org/MaskWorkspace>`__
-object, i.e., masking workspace, then the algorithm will mask
-Workspace's detector according to the histogram data of the
-SpecialWorkspace2D object
+If the input MaskedWorkspace is a MaskWorkspace object, i.e., masking workspace,
+then the algorithm will mask Workspace's detector according to the histogram
+data of the SpecialWorkspace2D object.
 
 Definition of Mask
 ##################
@@ -58,9 +57,9 @@ mask detectors, including
 -  Workspace indices
 -  Spectra
 -  Detectors
--  `MaskWorkspace <http://www.mantidproject.org/MaskWorkspace>`__
+-  MaskWorkspace
 -  General :ref:`MatrixWorkspace <MatrixWorkspace>` other than
-   `MaskWorkspace <http://www.mantidproject.org/MaskWorkspace>`__ (In this case, the mask will be
+   MaskWorkspace (In this case, the mask will be
    extracted from this workspace)
 
 Rules
@@ -70,13 +69,13 @@ Here are the rules for input information for masking
 
 1. At least one of the inputs must be specified.
 2. Workspace indices and Spectra cannot be given at the same time.
-3. `MaskWorkspace <http://www.mantidproject.org/MaskWorkspace>`__  and general :ref:`MatrixWorkspace <MatrixWorkspace>` cannot be given at the same time.
+3. MaskWorkspace  and general :ref:`MatrixWorkspace <MatrixWorkspace>` cannot be given at the same time.
 4. When a general :ref:`MatrixWorkspace <MatrixWorkspace>` is specified, then all detectors in a spectrum are treated as masked if the effective detector of that spectrum is masked.
 5. The masks specified from
 
    a) workspace indices/spectra
    b) detectors
-   c) `MaskWorkspace <http://www.mantidproject.org/MaskWorkspace>`__ /general :ref:`MatrixWorkspace <MatrixWorkspace>` will be combined by the *plus* operation.
+   c) MaskWorkspace /general :ref:`MatrixWorkspace <MatrixWorkspace>` will be combined by the *plus* operation.
 
 Operations Involved in Masking
 ##############################
@@ -91,8 +90,8 @@ Implementation
 
 In the plan, the workflow to mask detectors should be
 
-1. Convert input detectors, workspace indices or spectra, and general :ref:`MatrixWorkspace <MatrixWorkspace>` to a `MaskWorkspace <http://www.mantidproject.org/MaskWorkspace>`__.
-2. Mask detectors according to `MaskWorkspace <http://www.mantidproject.org/MaskWorkspace>`__.
+1. Convert input detectors, workspace indices or spectra, and general :ref:`MatrixWorkspace <MatrixWorkspace>` to a MaskWorkspace.
+2. Mask detectors according to MaskWorkspace.
 3. Clear data on all spectra, which have at least one detector that is masked.
 
 Concern
diff --git a/Code/Mantid/docs/source/algorithms/NormaliseByCurrent-v1.rst b/Code/Mantid/docs/source/algorithms/NormaliseByCurrent-v1.rst
index 7b30052e09534709ff684010187aba65cbd2569b..36166d1e969525558798af3afba1a6c5751b094d 100644
--- a/Code/Mantid/docs/source/algorithms/NormaliseByCurrent-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/NormaliseByCurrent-v1.rst
@@ -11,8 +11,8 @@ Description
 
 Normalises a workspace according to the good proton charge figure taken
 from the Input Workspace log data, which is stored in the workspace's
-`Sample <http://www.mantidproject.org/Sample>`_ object). Every data point (and its error) is divided
-by that number.
+`sample objects <../api/python/mantid/api/Sample.html>`__). Every data point
+(and its error) is divided by that number.
 
 ISIS Calculation Details
 ------------------------
diff --git a/Code/Mantid/docs/source/algorithms/OSIRISDiffractionReduction-v1.rst b/Code/Mantid/docs/source/algorithms/OSIRISDiffractionReduction-v1.rst
index 91bd9bb7e12d08d5a2bb7559ce60542f418a50e1..4456ab8957d185311c0022698d6d6cdba697d116 100644
--- a/Code/Mantid/docs/source/algorithms/OSIRISDiffractionReduction-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/OSIRISDiffractionReduction-v1.rst
@@ -13,10 +13,7 @@ Source Code
 -----------
 
 The source code for the Python Algorithm may be viewed at:
-`OSIRISDiffractionReduction.py <http://trac.mantidproject.org/mantid/browser/trunk/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py>`__
-
-The source code for the reducer class which is used may be viewed at:
-`osiris\_diffraction\_reducer.py <http://trac.mantidproject.org/mantid/browser/trunk/Code/Mantid/scripts/Inelastic/osiris_diffraction_reducer.py>`__
+`OSIRISDiffractionReduction.py <https://github.com/mantidproject/mantid/blob/master/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py>`__
 
 Usage
 -----
diff --git a/Code/Mantid/docs/source/algorithms/PawleyFit-v1.rst b/Code/Mantid/docs/source/algorithms/PawleyFit-v1.rst
index 3e59022cd0409c6da999672d5aa8503719eaad40..10d3a337014519b8edd00c1508306cb42586a9c5 100644
--- a/Code/Mantid/docs/source/algorithms/PawleyFit-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/PawleyFit-v1.rst
@@ -41,10 +41,10 @@ For the usage example there is a calculated, theoretical diffraction pattern (in
     # Find peaks in the spectrum
     si_peaks = PoldiPeakSearch(si_spectrum)
 
-    # Index the peaks, will generate a workspace named 'Indexed_Si'
+    # Index the peaks, will generate a workspace named 'si_peaks_indexed_Si'
     indexed = PoldiIndexKnownCompounds(si_peaks, CompoundWorkspaces='Si')
 
-    si_peaks_indexed = AnalysisDataService.retrieve('Indexed_Si')
+    si_peaks_indexed = AnalysisDataService.retrieve('si_peaks_indexed_Si')
 
     # 3 peaks have two possibilities for indexing, because their d-values are identical
     print "The number of peaks that were indexed:", si_peaks_indexed.rowCount()
diff --git a/Code/Mantid/docs/source/algorithms/PoldiCreatePeaksFromFile-v1.rst b/Code/Mantid/docs/source/algorithms/PoldiCreatePeaksFromFile-v1.rst
index a25b5e8d3f8b3607adb6f579a7aab1a8662d6fa6..e0733b7db2c4f1f1bd81fbb2e8b2f400410c97d8 100644
--- a/Code/Mantid/docs/source/algorithms/PoldiCreatePeaksFromFile-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/PoldiCreatePeaksFromFile-v1.rst
@@ -46,12 +46,18 @@ block shows how such a file would look when there are two compounds:
 Note that only the atoms in the asymmetric unit need to be specified, the space group is used to generate all
 equivalent atoms. This information is used to determine systematic absences, while the space group is also used by
 some POLDI algorithms to obtain the point group to get reflection multiplicities and more. Anything that follows the
-`#`-character is considered a comment and is ignored by the parser to allow documentation of the crystal structures
+``#``-character is considered a comment and is ignored by the parser to allow documentation of the crystal structures
 if necessary.
 
 The algorithm will always produce a WorkspaceGroup which contains as many peak tables as compounds specified in the
 file.
 
+Required
+--------
+
+This algorithm requires python package ``pyparsing``, available at the `python package index <https://pypi.python.org/pypi/pyparsing>`_
+or through the operating system's package manager. If the package is not present, this algorithm will not be available.
+
 Usage
 -----
 
@@ -59,7 +65,7 @@ Usage
 
 The following usage example takes up the file showed above and passes it to the algorithm.
 
-.. testcode::
+.. code-block:: python
 
     # Create two tables with expected peaks directly from a file
     compounds = PoldiCreatePeaksFromFile('PoldiCrystalFileExample.dat', LatticeSpacingMin=0.7)
@@ -74,14 +80,10 @@ The following usage example takes up the file showed above and passes it to the
 
 The script produces a WorkspaceGroup which contains a table with reflections for each compound in the file:
 
-.. testoutput::
+.. code-block:: python
 
     Number of loaded compounds: 2
     Compound 1: Iron_FCC has 11 reflections in the resolution range.
     Compound 2: Iron_BCC has 8 reflections in the resolution range.
 
-.. testcleanup::
-
-    DeleteWorkspace('compounds')
-
 .. categories::
diff --git a/Code/Mantid/docs/source/algorithms/PoldiDataAnalysis-v1.rst b/Code/Mantid/docs/source/algorithms/PoldiDataAnalysis-v1.rst
new file mode 100644
index 0000000000000000000000000000000000000000..783213d115b6eb9858f003d05374c81eb9e63c64
--- /dev/null
+++ b/Code/Mantid/docs/source/algorithms/PoldiDataAnalysis-v1.rst
@@ -0,0 +1,74 @@
+.. algorithm::
+
+.. summary::
+
+.. alias::
+
+.. properties::
+
+Description
+-----------
+
+This algorithm performs all necessary steps for a complete analysis of POLDI data, combining all algorithms that are
+specific to POLDI. In detail, it performs these steps on the supplied data:
+
+1. :ref:`algm-PoldiAutoCorrelation`
+2. :ref:`algm-PoldiPeakSearch`
+3. :ref:`algm-PoldiFitPeaks1D`
+4. :ref:`algm-PoldiIndexKnownCompounds`
+5. :ref:`algm-PoldiFitPeaks2D`
+6. :ref:`algm-PoldiAnalyseResiduals`
+
+Finally, the calculated diffractogram and the residuals are added together and all three spectra are plotted to give
+an impression of the result. If the `MultipleRuns` option is activated, steps 2 - 6 are repeated, but instead of
+using the initial correlation spectrum, the sum or calculated and residuals is used. Because this is usually much
+smoother than the initial correlation spectrum, additional peaks can be found there sometimes. The 2D-fit is still
+performed with the original data.
+
+The actual output is a WorkspaceGroup with content that varies a bit depending on the input parameters. If
+`PawleyFit` was active, it contains refined cell parameters. For the `ExpectedPeaks` parameter, a WorkpsaceGroup may
+be given (this is necessary when multiple phases are present in a sample).
+
+Usage
+-----
+
+.. include:: ../usagedata-note.txt
+
+The algorithm requires relatively little input and can be run like this:
+
+.. testcode::
+
+    import numpy as np
+
+    # Load POLDI data
+    PoldiLoadRuns(2013, 6903, 6904, 2, OutputWorkspace='poldi', MaskBadDetectors=False)
+
+    # Create Silicon peaks
+    PoldiCreatePeaksFromCell(SpaceGroup='F d -3 m', Atoms='Si 0 0 0 1.0 0.01', a=5.431,
+                             LatticeSpacingMin=0.7,
+                             OutputWorkspace='Si')
+
+    PoldiDataAnalysis(InputWorkspace='poldi_data_6904',
+                      ExpectedPeaks='Si', PawleyFit=True,
+                      MaximumPeakNumber=8,
+                      PlotResult=False,
+                      OutputWorkspace='result')
+
+    # Take a look at the refined cell:
+
+    cell = AnalysisDataService.retrieve('poldi_data_6904_cell_refined')
+
+    cell_a = np.round(cell.cell(0, 1), 5)
+    cell_a_error = np.round(cell.cell(0, 2), 5)
+
+    print "Refined lattice parameter a =", cell_a, "+/-", cell_a_error
+
+This will print the following output:
+
+.. testoutput::
+
+    Refined lattice parameter a = 5.43126 +/- 5e-05
+
+If PlotResult is changed to True, a plot of the spectrum and the residuals is created as described above.
+
+.. categories::
diff --git a/Code/Mantid/docs/source/algorithms/PoldiFitPeaks2D-v1.rst b/Code/Mantid/docs/source/algorithms/PoldiFitPeaks2D-v1.rst
index 374e32c6fd36c56d482851862222cf5cbe5a237d..176af936e6c4d86a6ea5d7d4f357387a801ec9b8 100644
--- a/Code/Mantid/docs/source/algorithms/PoldiFitPeaks2D-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/PoldiFitPeaks2D-v1.rst
@@ -13,7 +13,9 @@ PoldiFitPeaks2D is an algorithm that can be used to fit a set of individual peak
 
 The 1D-peak intensities need to be integral intensities, so the peaks are integrated if necessary. If there is no profile information supplied in the peak table (:ref:`algm-PoldiFitPeaks1D` adds this automatically), it's possible to supply a profile function as parameter to this algorithm. If a profile function name is present in the peak table, the one supplied in the parameters has priority.
 
-There are two modes for performing the fit. In the default mode, all peak profiles are fitted independently using the same function that is used for integration. The other possibility is to perform a Pawley-type fit, where peak positions are calculated using lattice parameters and Miller indices (see :ref:`algm-PawleyFit` for a more general explanation of the method). This mode is controlled by the PawleyFit parameter, if it is activated, InitialCell and CrystalSystem need to be specified as well. For these fits, an additional table will be created which contains the refined lattice parameters. Please note that the peaks need to be indexed to use this mode (:ref:`algm-PoldiCreatePeaksFromCell`, :ref:`algm-PoldiIndexKnownCompounds`).
+There are two modes for performing the fit. In the default mode, all peak profiles are fitted independently using the same function that is used for integration. The other possibility is to perform a Pawley-type fit, where peak positions are calculated using lattice parameters and Miller indices (see :ref:`algm-PawleyFit` for a more general explanation of the method). This mode is controlled by the PawleyFit parameter. For these fits, an additional table will be created which contains the refined lattice parameters. Please note that the peaks need to be indexed to use this mode (using :ref:`algm-PoldiCreatePeaksFromCell` and :ref:`algm-PoldiIndexKnownCompounds`).
+
+Alternatively, if the peaks have been indexed using a different method, the log values `UnitCell` and `CrystalSystem` must be set on the table workspace using :ref:`algm-AddSampleLog`. `UnitCell` must contain a string with 6 numbers that define a unit cell, with lengths in :math:`\mathrm{\AA{}}` and angles in degree (for example `5.4 5.4 5.4 90 90 90`), whereas `CrystalSystem` must be one of the seven crystal systems (for example `Cubic`).
 
 PoldiFitPeaks2D can also be used to calculate a theoretical 2D pattern from a set of peaks by limiting the iterations to 0.
 
@@ -130,15 +132,13 @@ The following example shows an example for refinement of lattice parameters usin
                                        CompoundWorkspaces = "si_peaks")
 
     # Only consider the first 8 peaks
-    DeleteTableRows("indexed_si_peaks", "8-30")
+    DeleteTableRows("peaks_refined_6904_indexed_si_peaks", "8-30")
 
     # Fit a unit cell.
     PoldiFitPeaks2D(InputWorkspace="truncated_data_6904",
-                             PoldiPeakWorkspace="indexed_si_peaks",
+                             PoldiPeakWorkspace="peaks_refined_6904_indexed_si_peaks",
                              OutputWorkspace="fitted_6904",
                              PawleyFit = True,
-                             InitialCell = "5.431 5.431 5.431 90 90 90",
-                             CrystalSystem = "Cubic",
                              MaximumIterations=100,
                              RefinedPoldiPeakWorkspace="peaks_fit_2d_6904",
                              Calculated1DSpectrum="simulated_1d_6904",
@@ -156,6 +156,6 @@ The refined lattice parameter is printed at the end:
 
 .. testoutput:: ExSilicon2DPawley
 
-    Refined lattice parameter a = 5.43126 +/- 5e-05
+    Refined lattice parameter a = 5.43125 +/- 4e-05
 
 .. categories::
diff --git a/Code/Mantid/docs/source/algorithms/PoldiIndexKnownCompounds-v1.rst b/Code/Mantid/docs/source/algorithms/PoldiIndexKnownCompounds-v1.rst
index 9f7c6fd6b9ab5786e76f0737bdcc9bebc872e9b2..2adc8e6f22ae2c2d64ff9a3ed3a9c99322d6032c 100644
--- a/Code/Mantid/docs/source/algorithms/PoldiIndexKnownCompounds-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/PoldiIndexKnownCompounds-v1.rst
@@ -57,15 +57,15 @@ The following example extracts peaks from the correlation spectrum of a Silicon
                                     ScatteringContributions="1.0",
                                     OutputWorkspace="Indexed")
 
-    print "Indexed_Si contains", mtd['Indexed_Si'].rowCount(), "indexed peaks."
-    print "Number of unindexed peaks:", mtd['Unindexed_peaks_refined_6904'].rowCount()
+    print "Indexed_Si contains", mtd['peaks_refined_6904_indexed_Si'].rowCount(), "indexed peaks."
+    print "Number of unindexed peaks:", mtd['peaks_refined_6904_unindexed'].rowCount()
 
 Output:
 
 .. testoutput:: PoldiIndexKnownCompoundsExample
 
     Indexed_Si contains 13 indexed peaks.
-    Number of unindexed peaks: 1
+    Number of unindexed peaks: 0
 
 .. categories::
 
diff --git a/Code/Mantid/docs/source/algorithms/PoldiLoadRuns-v1.rst b/Code/Mantid/docs/source/algorithms/PoldiLoadRuns-v1.rst
index 1c2403e82a87b8eb9d56cdd820ff30753a0284eb..bf30126aa373657bb697a11dec8f1851c535172a 100644
--- a/Code/Mantid/docs/source/algorithms/PoldiLoadRuns-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/PoldiLoadRuns-v1.rst
@@ -9,7 +9,11 @@
 Description
 -----------
 
-This algorithm makes it easier to load POLDI data. Besides importing the raw data (:ref:`algm-LoadSINQ`), it performs the otherwise manually performed steps of instrument loading (:ref:`algm-LoadInstrument`), truncation (:ref:`algm-PoldiTruncateData`). To make the algorithm more useful, it is possible to load data from multiple runs by specifying a range. In many cases, data files need to be merged in a systematic manner, which is also covered by this algorithm. For this purpose there is a parameter that specifies how the files of the specified range should be merged. The data files are named following the scheme `group_data_run`, where `group` is the name specified in `OutputWorkspace` and `run` is the run number and placed into a WorkspaceGroup with the name given in `OutputWorkspace`.
+This algorithm makes it easier to load POLDI data. Besides importing the raw data (:ref:`algm-LoadSINQ`), it performsthe otherwise manually performed steps of instrument loading (:ref:`algm-LoadInstrument`), truncation (:ref:`algm-PoldiTruncateData`). To make the algorithm more useful, it is possible to load data from multiple runs by specifying a range. In many cases, data files need to be merged in a systematic manner, which is also covered by this algorithm. For this purpose there is a parameter that specifies how the files of the specified range should be merged. The data files are named following the scheme `group_data_run`, where `group` is the name specified in `OutputWorkspace` and `run` is the run number and placed into a WorkspaceGroup with the name given in `OutputWorkspace`.
+
+By default, detectors that show unusually large integrated intensities are excluded if the pass a certain threshold
+with respect to the median of integrated intensities in all detectors. The threshold can be adjusted using an
+additional parameter. Detectors that are masked in the instrument definition are always masked.
 
 The data loaded in this way can be used directly for further processing with :ref:`algm-PoldiAutoCorrelation`.
 
diff --git a/Code/Mantid/docs/source/algorithms/PoldiPeakSummary-v1.rst b/Code/Mantid/docs/source/algorithms/PoldiPeakSummary-v1.rst
index 9c60215ef13c882af4c3550e25cfdac6cf096fc8..a50525cd4f72752b909e4d170a8911d9e8a92a9f 100644
--- a/Code/Mantid/docs/source/algorithms/PoldiPeakSummary-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/PoldiPeakSummary-v1.rst
@@ -44,7 +44,7 @@ Output:
 
 .. testoutput:: PoldiPeakSummaryExample
 
-    Number of refined peaks: 14
+    Number of refined peaks: 13
     Number of columns that describe a peak: 6
 
 .. categories::
diff --git a/Code/Mantid/docs/source/algorithms/PredictPeaks-v1.rst b/Code/Mantid/docs/source/algorithms/PredictPeaks-v1.rst
index 4939a4386a203d8ec8666fdd901154a674e16f7d..68d41a026f2824917818fe915e4ee7d13df6bfe5 100644
--- a/Code/Mantid/docs/source/algorithms/PredictPeaks-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/PredictPeaks-v1.rst
@@ -11,7 +11,7 @@ Description
 
 This algorithm will predict the position of single-crystal diffraction
 peaks (both in detector position/TOF and Q-space) and create an output
-`PeaksWorkspace <http://www.mantidproject.org/PeaksWorkspace>`_ containing the result.
+:ref:`PeaksWorkspace <PeaksWorkspace>` containing the result.
 
 This algorithm uses the InputWorkspace to determine the instrument in
 use, as well as the UB Matrix and Unit Cell of the sample used. You can
diff --git a/Code/Mantid/docs/source/algorithms/QueryAllRemoteJobs-v2.rst b/Code/Mantid/docs/source/algorithms/QueryAllRemoteJobs-v2.rst
new file mode 100644
index 0000000000000000000000000000000000000000..221906803072143613347629ffb7f66e1fd940de
--- /dev/null
+++ b/Code/Mantid/docs/source/algorithms/QueryAllRemoteJobs-v2.rst
@@ -0,0 +1,36 @@
+.. algorithm::
+
+.. summary::
+
+.. alias::
+
+.. properties::
+
+Description
+-----------
+
+Query information status for all the jobs available on the (remote)
+compute resource. In principle this includes all the jobs submitted,
+but in some cases (implementation dependent) the compute resource may
+not report anything about old finished jobs. Note that the output
+properties are all arrays. There will be one element for each job that
+was reported by the compute resource.
+
+For specific details on remote algorithms when using the Mantid web
+service remote job submission API, see the `remote job submission API
+docs <http://www.mantidproject.org/Remote_Job_Submission_API>`_.
+
+Previous Versions
+-----------------
+
+Version 1
+#########
+
+Version 1 queries the status of jobs using the `Mantid remote job
+submission API
+<http://www.mantidproject.org/Remote_Job_Submission_API>`_. This is
+still supported as one of the variants of Versions 2 and above, when
+the compute resource uses the Mantid remote job submission API as job
+manager (underlying remote job scheduling mechanism).
+
+.. categories::
diff --git a/Code/Mantid/docs/source/algorithms/QueryRemoteFile-v2.rst b/Code/Mantid/docs/source/algorithms/QueryRemoteFile-v2.rst
new file mode 100644
index 0000000000000000000000000000000000000000..786b875b6f7c3294fb9028901da6701fee00a4ed
--- /dev/null
+++ b/Code/Mantid/docs/source/algorithms/QueryRemoteFile-v2.rst
@@ -0,0 +1,33 @@
+.. algorithm::
+
+.. summary::
+
+.. alias::
+
+.. properties::
+
+Description
+-----------
+
+Get a list of the files associated with the specified transaction on
+the (remote) compute resource. The transaction must have been created
+previously with :ref:`algm-StartRemoteTransaction`.
+
+For specific details on remote algorithms when using the Mantid web
+service remote job submission API, see the `remote job submission API
+docs <http://www.mantidproject.org/Remote_Job_Submission_API>`_.
+
+Previous Versions
+-----------------
+
+Version 1
+#########
+
+Version 1 queries the list of files using the `Mantid remote job
+submission API
+<http://www.mantidproject.org/Remote_Job_Submission_API>`_. This is
+still supported as one of the variants of Versions 2 and above, when
+the compute resource uses the Mantid remote job submission API as job
+manager (underlying remote job scheduling mechanism).
+
+.. categories::
diff --git a/Code/Mantid/docs/source/algorithms/QueryRemoteJob-v2.rst b/Code/Mantid/docs/source/algorithms/QueryRemoteJob-v2.rst
new file mode 100644
index 0000000000000000000000000000000000000000..2dd887d226d75d1ff170619039d39d8b0d67c20e
--- /dev/null
+++ b/Code/Mantid/docs/source/algorithms/QueryRemoteJob-v2.rst
@@ -0,0 +1,33 @@
+.. algorithm::
+
+.. summary::
+
+.. alias::
+
+.. properties::
+
+Description
+-----------
+
+Query information for a particular job (identified by its ID)
+submitted to the (remote) compute resource given in the
+properties. Jobs are submitted with :ref:`algm-SubmitRemoteJob`.
+
+For specific details on remote algorithms when using the Mantid web
+service remote job submission API, see the `remote job submission API
+docs <http://www.mantidproject.org/Remote_Job_Submission_API>`_.
+
+Previous Versions
+-----------------
+
+Version 1
+#########
+
+Version 1 queries the status of jobs using the `Mantid remote job
+submission API
+<http://www.mantidproject.org/Remote_Job_Submission_API>`_. This is
+still supported as one of the variants of Versions 2 and above, when
+the compute resource uses the Mantid remote job submission API as job
+manager (underlying remote job scheduling mechanism).
+
+.. categories::
diff --git a/Code/Mantid/docs/source/algorithms/RemoveMaskedSpectra-v1.rst b/Code/Mantid/docs/source/algorithms/RemoveMaskedSpectra-v1.rst
new file mode 100644
index 0000000000000000000000000000000000000000..c5047c684fb86aee6178895c370496f47716ad6a
--- /dev/null
+++ b/Code/Mantid/docs/source/algorithms/RemoveMaskedSpectra-v1.rst
@@ -0,0 +1,43 @@
+.. algorithm::
+
+.. summary::
+
+.. alias::
+
+.. properties::
+
+Description
+-----------
+
+Removes all masked spectra from a workspace and stores all unmasked ones in the output workspace.
+The mask is taken either from the optional MaskedWorkspace property or from the input workspace
+if it is the only input. The MaskedWorkspace property can either be a masked MatrixWorkspace or
+a specialised MaskWorkspace.
+
+
+Usage
+-----
+
+**Example - RemoveMaskedSpectra**
+
+.. testcode:: RemoveMaskedSpectraExample
+
+    # Create a workspace
+    ws = CreateSampleWorkspace()
+    # Mask some detectors
+    MaskDetectors(ws,SpectraList=[10,20,30,40,50])
+    print 'Input workspace has %s spectra' % ws.getNumberHistograms()
+
+    # Removed the 5 masked spectra
+    removed = RemoveMaskedSpectra(ws)
+    print 'Output workspace has %s spectra' % removed.getNumberHistograms()
+
+Output:
+
+.. testoutput:: RemoveMaskedSpectraExample
+
+    Input workspace has 200 spectra
+    Output workspace has 195 spectra
+
+.. categories::
+
diff --git a/Code/Mantid/docs/source/algorithms/ResizeRectangularDetector-v1.rst b/Code/Mantid/docs/source/algorithms/ResizeRectangularDetector-v1.rst
index 456bbfc064c99135f7524af01f1a93a516bbd861..811b74db817b12046ef0a42400a40d9cc896e165 100644
--- a/Code/Mantid/docs/source/algorithms/ResizeRectangularDetector-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/ResizeRectangularDetector-v1.rst
@@ -10,17 +10,17 @@ Description
 -----------
 
 This algorithm will resize a
-`RectangularDetector <http://www.mantidproject.org/RectangularDetector>`_ by applying X and Y
+:ref:`RectangularDetector <RectangularDetector>` by applying X and Y
 scaling factors. Each pixel's position will be modifed relative to the
 0,0 point of the detector by these factors. Typically, a
 RectangularDetector is constructed around its center, so this would
 scale the detector around its center.
 
-This only works on `RectangularDetectors <http://www.mantidproject.org/RectangularDetector>`_. Banks
+This only works on :ref:`RectangularDetectors <RectangularDetector>`. Banks
 formed by e.g. tubes cannot be scaled in this way.
 
 Internally, this sets the "scalex" and "scaley" parameters on the
-`RectangularDetector <http://www.mantidproject.org/RectangularDetector>`_. Note that the scaling is
+:ref:`RectangularDetector <RectangularDetector>`. Note that the scaling is
 relative to the original size, and is not cumulative: that is, if you
 Resize \* 2 and again \* 3, your final detector is 3 times larger than
 the original, not 6 times.
diff --git a/Code/Mantid/docs/source/algorithms/SANSWideAngleCorrection-v1.rst b/Code/Mantid/docs/source/algorithms/SANSWideAngleCorrection-v1.rst
index 9a29f27bee79633b55ad0ec53220998a555640c8..12a5b938f6ff0b67f46a542dd957b74702a28d9c 100644
--- a/Code/Mantid/docs/source/algorithms/SANSWideAngleCorrection-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/SANSWideAngleCorrection-v1.rst
@@ -36,8 +36,7 @@ into the sample, its total transmission is then:
 and :math:`x = d`.
 
 Hammouda, gives an approximate result for the integral, see page 208 of
-`http://www.ncnr.nist.gov/staff/hammouda/the\_SANS\_toolbox.pdf SANS
-toolbox <http://www.ncnr.nist.gov/staff/hammouda/the_SANS_toolbox.pdf SANS toolbox>`__:
+`SANS toolbox <http://www.ncnr.nist.gov/staff/hammouda/the_SANS_toolbox.pdf>`__:
 
 :math:`T^{'} = \frac{T_0(T_0^A - 1)}{A \ln(T_0)}`
 
diff --git a/Code/Mantid/docs/source/algorithms/SaveAscii-v2.rst b/Code/Mantid/docs/source/algorithms/SaveAscii-v2.rst
index f66cbedd67c27f277fcf9c158875cf304a5fea8b..edc34add1b358d2298ac76e0a4cbbdd40d7dc799 100644
--- a/Code/Mantid/docs/source/algorithms/SaveAscii-v2.rst
+++ b/Code/Mantid/docs/source/algorithms/SaveAscii-v2.rst
@@ -9,12 +9,16 @@
 Description
 -----------
 
-The workspace data are stored in the file in columns: the first column contains the X-values, followed by pairs of Y and E values. Columns are separated by commas. The resulting file can normally be loaded into a workspace by the :ref:`algm-LoadAscii` algorithm.
+The workspace data are stored in the file in columns: the first column contains
+the X-values, followed by pairs of Y and E values. Columns are separated by
+commas. The resulting file can normally be loaded into a workspace by the
+:ref:`algm-LoadAscii` algorithm.
 
 Limitations
 ###########
 
-The algorithm assumes that the workspace has common X values for all spectra (i.e. is not a `ragged workspace <Ragged Workspace>`__). Only the X values from the first spectrum in the workspace are saved out.
+The algorithm assumes that the workspace has common X values for all spectra
+(i.e. is not a `ragged workspace <Ragged Workspace>`__).
 
 Usage
 -----
diff --git a/Code/Mantid/docs/source/algorithms/SaveLauenorm-v1.rst b/Code/Mantid/docs/source/algorithms/SaveLauenorm-v1.rst
index 70a0dc39bbd75f8dc77816b8481b28b7f38d279f..47b87ce1e87ddb2c57d00f07fe0d0275cce479ed 100644
--- a/Code/Mantid/docs/source/algorithms/SaveLauenorm-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/SaveLauenorm-v1.rst
@@ -21,7 +21,7 @@ Unit 23     LAUE003
 
 Continuing
 
-From: http://www.ccp4.ac.uk/cvs/viewvc.cgi/laue/doc/lauenorm.ptx?diff_format=s&revision=1.1.1.1&view=markup
+From: http://www.ccp4.ac.uk/newsletters/newsletter36/10_laue.html
 
 Usage
 -----
diff --git a/Code/Mantid/docs/source/algorithms/SaveMD-v1.rst b/Code/Mantid/docs/source/algorithms/SaveMD-v1.rst
index 2f58ba31b373adcbff21435dabc55257441931fe..ec5c6809b7d5a5623dfa7cdfae2ab7f78b5c9c62 100644
--- a/Code/Mantid/docs/source/algorithms/SaveMD-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/SaveMD-v1.rst
@@ -30,7 +30,7 @@ Usage
                                 Extents='-1,1,-1,1', NumberOfBins='3,3', Names='A,B', Units='U,T')
     import os
     savefile = os.path.join(config["default.savedirectory"], "mdhws.nxs")
-    SaveMD(ws, Filename=savefile)
+    SaveMD(ws, Filename=savefile, Version=1)
     print "File created:", os.path.exists(savefile)
 
 Output:
diff --git a/Code/Mantid/docs/source/algorithms/SaveMD-v2.rst b/Code/Mantid/docs/source/algorithms/SaveMD-v2.rst
new file mode 100644
index 0000000000000000000000000000000000000000..2f58ba31b373adcbff21435dabc55257441931fe
--- /dev/null
+++ b/Code/Mantid/docs/source/algorithms/SaveMD-v2.rst
@@ -0,0 +1,47 @@
+.. algorithm::
+
+.. summary::
+
+.. alias::
+
+.. properties::
+
+Description
+-----------
+
+Save an `MDEventWorkspace <http://www.mantidproject.org/MDEventWorkspace>`_ or a
+:ref:`MDHistoWorkspace <MDHistoWorkspace>` to a .nxs file. The
+workspace's current box structure and entire list of events is
+preserved. The resulting file can be loaded via :ref:`LoadMD <algm-LoadMD>`.
+
+If you specify MakeFileBacked, then this will turn an in-memory
+workspace to a file-backed one. Memory will be released as it is written
+to disk.
+
+If you specify UpdateFileBackEnd, then any changes (e.g. events added
+using the PlusMD algorithm) will be saved to the file back-end.
+
+Usage
+-----
+
+.. testcode:: DoIt
+
+    ws = CreateMDHistoWorkspace(SignalInput='1,2,3,4,5,6,7,8,9', ErrorInput='1,1,1,1,1,1,1,1,1', Dimensionality='2',
+                                Extents='-1,1,-1,1', NumberOfBins='3,3', Names='A,B', Units='U,T')
+    import os
+    savefile = os.path.join(config["default.savedirectory"], "mdhws.nxs")
+    SaveMD(ws, Filename=savefile)
+    print "File created:", os.path.exists(savefile)
+
+Output:
+
+.. testoutput:: DoIt
+
+    File created: True
+
+.. testcleanup:: DoIt
+
+    import os
+    os.remove(savefile)
+
+.. categories::
diff --git a/Code/Mantid/docs/source/algorithms/SaveMask-v1.rst b/Code/Mantid/docs/source/algorithms/SaveMask-v1.rst
index a210bec480e05dce4f3924ece16b57a5d294e3bc..9a1e229a56d3770a53be54471040b52b2079f966 100644
--- a/Code/Mantid/docs/source/algorithms/SaveMask-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/SaveMask-v1.rst
@@ -17,14 +17,14 @@ file. This algorithm has previously been renamed from SaveDetectorMasks.
 
 There are two types of mask workspace that can serve as input.
 
-1. `MaskWorkspace <http://www.mantidproject.org/MaskWorkspace>`__
-##################################################################
+1. MaskWorkspace
+################
 
 In this case, :ref:`algm-SaveMask` will read Y values to determine
 which detectors are masked;
 
-2. A non-\ `MaskWorkspace <http://www.mantidproject.org/MaskWorkspace>`__ :ref:`MatrixWorkspace <MatrixWorkspace>` containing :ref:`Instrument <Instrument>`
-################################################################################################################################################################################################################
+2. A non-MaskWorkspace :ref:`MatrixWorkspace <MatrixWorkspace>` containing :ref:`Instrument <Instrument>`
+#########################################################################################################
 
 In this case, :ref:`algm-SaveMask` will scan through all detectors to
 determine which are masked.
diff --git a/Code/Mantid/docs/source/algorithms/SaveNXTomo-v1.rst b/Code/Mantid/docs/source/algorithms/SaveNXTomo-v1.rst
new file mode 100644
index 0000000000000000000000000000000000000000..f68f0d1a0dc32def01c1652efdf52e0b526bcf7b
--- /dev/null
+++ b/Code/Mantid/docs/source/algorithms/SaveNXTomo-v1.rst
@@ -0,0 +1,57 @@
+.. algorithm::
+
+.. summary::
+
+.. alias::
+
+.. properties::
+
+Description
+-----------
+
+Save one or more workspaces (of type :ref:`Workspace2D <Workspace2D>`)
+into a NeXus NXtomo file (NeXus application definition format). When
+the input workspace given is a :ref:`Workspace2D <Workspace2D>`, that
+single workspace is written to the output NXTomo file. When the input
+workspace is a :ref:`WorkspaceGroup <WorkspaceGroup>` (as LoadFITS
+produces), all the :ref:`Workspace2D <Workspace2D>` workspaces
+included in the group will be written to the output file.
+
+This algorithm has been designed to save workspaces such as those
+containing data from FITS images that the algorithm
+:ref:`algm-LoadFITS` produces. Workspaces with a different structure
+and/or without the logs included in FITS image workspaces may not be
+saved properly (it may not make sense to save them into NXTomo files)
+or may produce errors in this algorithm.
+
+Depending on the value given to the property *OverwriteFile* it will
+create a new NXTomo file and add into it the data from the input
+workspace, or it will append the data such that a sequence of calls to
+this algorithm can cumulatively add new image files into a same output
+NXTomo file. Possible uses of this algorithm include writing NXTomo
+files with stacks of images to be used as inputs to tomographic
+reconstruction tools.
+
+.. note: not including a doc test because this requires loading and
+   saving files. This class is decently tested for now in its unit
+   test. A fake-workspace based example would be confusing to users,
+   unless we add a 'CreateFITSLikeWorkspace' helper which seems an
+   overkill.
+
+.. code-block:: python
+
+   # Usually you'll save image data loaded from FITS files
+   LoadFITS('example1.fits', OutputWorkspace='reconstruction')
+   LoadFITS('example2.fits', OutputWorkspace='reconstruction')
+   # Write NXTomo file with data from 2 images
+   SaveNXTomo(InputWorkspaces='reconstruction', Filename='input_rec')
+
+**NOTE:** this algorithm is currently subject to changes and
+extensions, as new functionality for imaging and tomographic
+reconstruction is integrated in Mantid. At the moment it uses the
+NXTomo file format specified in the `NeXus NXTomo application
+definition
+<http://download.nexusformat.org/sphinx/classes/applications/NXtomo.html>`__,
+but extensions and/or different variants might be added in the future.
+
+.. categories::
diff --git a/Code/Mantid/docs/source/algorithms/SaveToSNSHistogramNexus-v1.rst b/Code/Mantid/docs/source/algorithms/SaveToSNSHistogramNexus-v1.rst
index f13075877b956326e99cc651fa428ba70d39b0f9..c51e60c94c82c8bcbdeed9ce4fc03a5f3754e1c1 100644
--- a/Code/Mantid/docs/source/algorithms/SaveToSNSHistogramNexus-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/SaveToSNSHistogramNexus-v1.rst
@@ -15,7 +15,7 @@ workspace contains. The histograms do not need to be the same size (in
 number of bins), but the number of pixels needs to be the same.
 
 In addition, this only works for instruments that use
-`RectangularDetectors <http://www.mantidproject.org/RectangularDetector>`__ (SNAP, TOPAZ, POWGEN, for
+:ref:`RectangularDetectors <RectangularDetector>` (SNAP, TOPAZ, POWGEN, for
 example); in addition, the name in the instrument definition file must
 match the name in the NXS file.
 
diff --git a/Code/Mantid/docs/source/algorithms/SetSpecialCoordinates-v1.rst b/Code/Mantid/docs/source/algorithms/SetSpecialCoordinates-v1.rst
index d218db752e69743c08f25a25b098d259928ea202..ab7004a3f69e89673350ec8af55a410869efa8d2 100644
--- a/Code/Mantid/docs/source/algorithms/SetSpecialCoordinates-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/SetSpecialCoordinates-v1.rst
@@ -12,7 +12,7 @@ Description
 `MDEventWorkspaces <http://www.mantidproject.org/MDEventWorkspace>`_ and
 :ref:`MDHistoWorkspaces <MDHistoWorkspace>` can be used with any type of
 coordinate system. On the other hand
-`PeaksWorkspaces <http://www.mantidproject.org/PeaksWorkspace>`_ may be plotted either in QLab,
+:ref:`PeaksWorkspaces <PeaksWorkspace>` may be plotted either in QLab,
 QSample or HKL. There is an inherent link between a PeaksWorkspace and a
 MDWorkspace in that an MDWorkspace may utilise the same coordinate
 systems as the PeaksWorkspaces. For example, workspaces created via
diff --git a/Code/Mantid/docs/source/algorithms/ShowPeakHKLOffsets-v1.rst b/Code/Mantid/docs/source/algorithms/ShowPeakHKLOffsets-v1.rst
index 733e88cfe39efb5d491a7c15a997094c56d418ca..846af13dc132b67a4979c59d0e518c0c649d0288 100644
--- a/Code/Mantid/docs/source/algorithms/ShowPeakHKLOffsets-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/ShowPeakHKLOffsets-v1.rst
@@ -17,4 +17,42 @@ The maximum of these offsets is also included.
 Histograms, scatterplots, etc. of this data can be used to detect
 problems.
 
+Usage
+-----
+
+**Example - Run LoadprofResolution for both TableWorkspace and workspace with MUSR Instrument**
+
+.. include:: ../usagedata-note.txt
+
+.. testcode:: ExShowHKLOffsetsSimple
+
+   #
+   # Load Peaks found in SXD23767.raw 
+   #
+   Load(Filename='SXD23767.peaks',OutputWorkspace='peaks_qLab')
+
+   #Set orientated lattice
+   ublist = [-0.06452276,  0.2478114,  -0.23742194, 0.29161678, -0.00914316, -0.12523779, 0.06958942, -0.1802702,  -0.14649001]
+   SetUB('peaks_qLab',UB=ublist)
+
+   # Run Algorithm 
+   table = ShowPeakHKLOffsets('peaks_qLab')
+
+   #Print part of first four rows
+   for i in [0,1,2,3]:
+      row = table.row(i)
+      #print row
+      print "{H offset from int: %.3f, K offset from int: %.3f, L offset from int: %.3f }" % ( row["H offset from int"],  row["K offset from int"], row["L offset from int"])
+
+
+Output:
+
+.. testoutput:: ExShowHKLOffsetsSimple
+
+   {H offset from int: -0.003, K offset from int: 0.012, L offset from int: 0.063 }
+   {H offset from int: -0.220, K offset from int: 0.431, L offset from int: -0.193 }
+   {H offset from int: -0.105, K offset from int: -0.066, L offset from int: -0.232 }
+   {H offset from int: 0.174, K offset from int: 0.095, L offset from int: 0.440 }
+
+
 .. categories::
diff --git a/Code/Mantid/docs/source/algorithms/SliceMDHisto-v1.rst b/Code/Mantid/docs/source/algorithms/SliceMDHisto-v1.rst
index 0931de499dd0ed0e9fe137236cab3e52638b9177..e9e5528f9b00d1645da5b07b2a400c9606b089c9 100644
--- a/Code/Mantid/docs/source/algorithms/SliceMDHisto-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/SliceMDHisto-v1.rst
@@ -9,7 +9,7 @@
 Description
 -----------
 
-SliceMDHisto extracts a hyperslab of data from a MDHistoWorkspace. Beyond 
+SliceMDHisto extracts a hyperslab of data from a :ref:`MDHistoWorkspace <MDHistoWorkspace>`. Beyond 
 the usual input and output workspace parameters, the start and end of the
 hyperslabs dimensions are required. Both  as comma separated lists with an 
 entry for each dimension of the MDHistoWorkspace. 
@@ -19,6 +19,8 @@ Running SliceMDHisto with parameters Start= 20,20,20 and End= 50,50,100
 will copy all the data between x: 20-50, y: 20-50, z:20-100 into the 
 result MDHistoWorkspace with dimensions 30,30,80.
 
+For a more up-to-date way of performing slices on a :ref:`MDHistoWorkspace <MDHistoWorkspace>` this see :ref:`algm-IntegrateMDHistoWorkspace`
+
 Usage
 -----
 
diff --git a/Code/Mantid/docs/source/algorithms/SmoothNeighbours-v1.rst b/Code/Mantid/docs/source/algorithms/SmoothNeighbours-v1.rst
index a307527efc8c2a1c6059323d2528978577f89cd6..72dec695dd5dea739343dbffebb8726434d390cc 100644
--- a/Code/Mantid/docs/source/algorithms/SmoothNeighbours-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/SmoothNeighbours-v1.rst
@@ -35,7 +35,7 @@ For Instruments With Rectangular Detectors
 ##########################################
 
 The algorithm looks through the `Instrument <http://mantidproject.org/Instrument>`__ to find all
-the `RectangularDetectors <http://mantidproject.org/RectangularDetector>`__ defined. For each
+the :ref:`RectangularDetectors <RectangularDetector>` defined. For each
 pixel in each detector, the AdjX\*AdjY neighboring spectra are summed
 together and saved in the output workspace.
 
diff --git a/Code/Mantid/docs/source/algorithms/SortXAxis-v1.rst b/Code/Mantid/docs/source/algorithms/SortXAxis-v1.rst
index da6bc94738d7bfeef220d18d79c5c25022c9d38a..d6d1ed5be5e1a8c321e88f3f92e642add1682f2c 100644
--- a/Code/Mantid/docs/source/algorithms/SortXAxis-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/SortXAxis-v1.rst
@@ -17,6 +17,6 @@ passing to this algorithm.
 
 This algorithm is for use with small workspaces loaded. It is
 particularly suitable for reformatting workspaces loaded via
-`LoadASCII <http://www.mantidproject.org/LoadASCII>`_. Input workspaces must be a distribution.
+:ref:`LoadAscii <algm-LoadAscii>`. Input workspaces must be a distribution.
 
 .. categories::
diff --git a/Code/Mantid/docs/source/algorithms/StartRemoteTransaction-v2.rst b/Code/Mantid/docs/source/algorithms/StartRemoteTransaction-v2.rst
new file mode 100644
index 0000000000000000000000000000000000000000..bb589517c9988366170bd3d6815102c98a80401f
--- /dev/null
+++ b/Code/Mantid/docs/source/algorithms/StartRemoteTransaction-v2.rst
@@ -0,0 +1,42 @@
+.. algorithm::
+
+.. summary::
+
+.. alias::
+
+.. properties::
+
+Description
+-----------
+
+Start a (new) transaction on a remote compute resource. You need to
+start a transaction before submitting jobs with
+:ref:`algm-StartRemoteTransaction`, and or uploading or downloading
+files with :ref:`algm-UploadRemoteFile` and
+:ref:`algm-DownloadRemoteFile`. The concept of transaction is
+described in the `Mantid remote job submission API docs
+<http://www.mantidproject.org/Remote_Job_Submission_API>`. Note that
+(depending on the implementation of this algorithm) the environment,
+and files and jobs available are specific to a transaction.
+
+Transactions created with this algorithm can be cancelled or killed
+with the algorithm :ref:`algm-StopRemoteTransaction`.
+
+For more specific details on remote algorithms when using the Mantid
+web service remote job submission API, see the `remote job submission
+API docs <http://www.mantidproject.org/Remote_Job_Submission_API>`_.
+
+Previous Versions
+-----------------
+
+Version 1
+#########
+
+Version 1 creates transactions using the Start action of the `Mantid
+remote job submission API
+<http://www.mantidproject.org/Remote_Job_Submission_API>`_. This is
+still supported as one of the variants of Versions 2 and above, when
+the compute resource uses the Mantid remote job submission API as job
+manager (underlying remote job scheduling mechanism).
+
+.. categories::
diff --git a/Code/Mantid/docs/source/algorithms/StepScan-v1.rst b/Code/Mantid/docs/source/algorithms/StepScan-v1.rst
index 0608bdec5b6f6c96aab6923437821048ea9a5071..2ee63b11aaed1fdc4801745a8bc2d90d40b4741b 100644
--- a/Code/Mantid/docs/source/algorithms/StepScan-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/StepScan-v1.rst
@@ -12,7 +12,6 @@ Description
 This algorithm is for producing rocking curves from alignment scan runs.
 It is for use only with ADARA-style SNS datasets as it requires the
 'scan\_index' log variable.
-
 The algorithm optionally uses the :ref:`algm-MaskDetectors`
 and/or :ref:`algm-FilterByXValue` algorithms to restrict the
 region of data included. **N.B. If these options are used, then this
@@ -22,5 +21,17 @@ The :ref:`algm-SumEventsByLogValue` algorithm is then
 called, with 'scan\_index' as the log to sum against. The row of the
 resulting table pertaining to scan\_index=0 (which indicates 'not a scan
 point') is then removed.
+ 
+Before then it will call other algorithms as shown in the flowchart,
+if the relevent inputs have been set.
+:ref:`algm-MaskDetectors` will be called if a MaskWorkspace is supplied.
+If either Xmin or Xmax or both are supplied, 
+then :ref:`algm-FilterByXValue` algorithm is run to restrict the
+region of data included and if RangeUnit is not TOF,
+:ref:`algm-ConvertUnits` is run beforehand.  
+
+If necessary, the imput workspace is cloned, to save it from being modified.
+
+.. image:: ../images/StepScanWorkflow.png
 
 .. categories::
diff --git a/Code/Mantid/docs/source/algorithms/StopRemoteTransaction-v2.rst b/Code/Mantid/docs/source/algorithms/StopRemoteTransaction-v2.rst
new file mode 100644
index 0000000000000000000000000000000000000000..de620dca8a796f5232c3137c45c5dcce45f83869
--- /dev/null
+++ b/Code/Mantid/docs/source/algorithms/StopRemoteTransaction-v2.rst
@@ -0,0 +1,33 @@
+.. algorithm::
+
+.. summary::
+
+.. alias::
+
+.. properties::
+
+Description
+-----------
+
+Stop a transaction on a (remote) compute resource. The transaction
+must have been created previously with
+:ref:`algm-StartRemoteTransaction`.
+
+For more details on remote algorithms when using the Mantid web
+service remote job submission API, see the `remote job submission API
+docs <http://www.mantidproject.org/Remote_Job_Submission_API>`_.
+
+Previous Versions
+-----------------
+
+Version 1
+#########
+
+Version 1 stops transactions using the Stop action of the `Mantid
+remote job submission API
+<http://www.mantidproject.org/Remote_Job_Submission_API>`_. This is
+still supported as one of the variants of Versions 2 and above, when
+the compute resource uses the Mantid remote job submission API as job
+manager (underlying remote job scheduling mechanism).
+
+.. categories::
diff --git a/Code/Mantid/docs/source/algorithms/SubmitRemoteJob-v2.rst b/Code/Mantid/docs/source/algorithms/SubmitRemoteJob-v2.rst
new file mode 100644
index 0000000000000000000000000000000000000000..0ce06a6cc6b2d116520dc00b22fa835e034bc7eb
--- /dev/null
+++ b/Code/Mantid/docs/source/algorithms/SubmitRemoteJob-v2.rst
@@ -0,0 +1,43 @@
+.. algorithm::
+
+.. summary::
+
+.. alias::
+
+.. properties::
+
+Description
+-----------
+
+Submit a job to be executed on the specified (remote) compute
+resource. After this, you can query the status of this job or all the
+jobs using the algorithms :ref:`algm-QueryRemoteJob` and
+:ref:`algm-QueryAllRemoteJobs`, respectively. Jobs submitted with this
+algorithm can be cancelled/killed/aborted with the algorithm
+:ref:`algm-AbortRemoteJob`.
+
+Note that the script and script parameters properties are used in an
+implementation dependent way. For example, if using the Mantid web
+service job submission API, the script parameters properties is used
+to provide the actual content of a python script to run. For other
+variants (underlying job schedulers), such as Platform LSF, the
+parameters property is used for different application specific command
+line options.  For more details on remote algorithms when using the
+Mantid web service remote job submission API, see the `remote job
+submission API docs
+<http://www.mantidproject.org/Remote_Job_Submission_API>`_.
+
+Previous Versions
+-----------------
+
+Version 1
+#########
+
+Version 1 uses different input properties (PythonScript) and submits
+jobs using the `Mantid remote job submission API
+<http://www.mantidproject.org/Remote_Job_Submission_API>`_. This is
+still supported as one of the variants of Versions 2 and above, when
+the compute resource uses the Mantid remote job submission API as job
+manager (underlying remote job scheduling mechanism).
+
+.. categories::
diff --git a/Code/Mantid/docs/source/algorithms/SumNeighbours-v1.rst b/Code/Mantid/docs/source/algorithms/SumNeighbours-v1.rst
index 2571fcc140ae3caab80c933dcd1b20139bbacf80..47fec64482672fc7bd16985097cbd0374d505c24 100644
--- a/Code/Mantid/docs/source/algorithms/SumNeighbours-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/SumNeighbours-v1.rst
@@ -10,7 +10,7 @@ Description
 -----------
 
 The algorithm looks through the :ref:`Instrument <Instrument>` to find all
-the `RectangularDetectors <http://www.mantidproject.org/RectangularDetector>`__ defined. For each
+the :ref:`RectangularDetectors <RectangularDetector>` defined. For each
 detector, the SumX\*SumY neighboring event lists are summed together and
 saved in the output workspace as a single spectrum. Therefore, the
 output workspace will have 1/(SumX\*SumY) \* the original number of
diff --git a/Code/Mantid/docs/source/algorithms/ThresholdMD-v1.rst b/Code/Mantid/docs/source/algorithms/ThresholdMD-v1.rst
index 71042e4a8fa59fc2a70f19d1af9af39ec901c0d1..95528b2803d488fa3498b942ec393604cf08a78c 100644
--- a/Code/Mantid/docs/source/algorithms/ThresholdMD-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/ThresholdMD-v1.rst
@@ -9,7 +9,71 @@
 Description
 -----------
 
-Threshold an MDHistoWorkspace to overwrite values below or above the
-defined threshold.
+This algorithm applies a simple linear transformation to a
+:ref:`MDWorkspace <MDWorkspace>` or
+:ref:`MDHistoWorkspace <MDHistoWorkspace>`. This could be used, for
+example, to scale the Energy dimension to different units.
+
+Each coordinate is tranformed so that :math:`x'_d = (x_d * s_d) + o_d`
+where:
+
+-  d : index of the dimension, from 0 to the number of dimensions
+-  s : value of the Scaling parameter
+-  o : value of the Offset parameter.
+
+You can specify either a single value for Scaling and Offset, in which
+case the same m\_scaling or m\_offset are applied to each dimension; or
+you can specify a list with one entry for each dimension.
+
+Notes
+#####
+
+The relationship between the workspace and the original
+:ref:`MDWorkspace <MDWorkspace>`, for example when the MDHistoWorkspace is
+the result of :ref:`algm-BinMD`, is lost. This means that you cannot
+re-bin a transformed :ref:`MDHistoWorkspace <MDHistoWorkspace>`.
+
+No units are not modified by this algorithm.
+
+Performance Notes
+#################
+
+-  Performing the operation in-place (input=output) is always faster
+   because the first step of the algorithm if NOT in-place is to clone
+   the original workspace.
+-  For :ref:`MDHistoWorkspaces <MDHistoWorkspace>` done in-place,
+   TransformMD is very quick (no data is modified, just the
+   coordinates).
+-  For :ref:`MDWorkspaces <MDWorkspace>`, every event's coordinates gets
+   modified, so this may take a while for large workspaces.
+-  For file-backed :ref:`MDWorkspaces <MDWorkspace>`, you will find much
+   better performance if you perform the change in-place (input=output),
+   because the data gets written out to disk twice otherwise.
+
+Usage
+-----
+
+**Example - Threshold a small workspace:**
+
+.. testcode:: ExThresholdMD
+
+   # Create input workspace
+   CreateMDWorkspace(Dimensions=3, Extents='-10,10,-10,10,-10,10', Names='A,B,C', Units='U,U,U', OutputWorkspace='demo')
+   FakeMDEventData(InputWorkspace='demo', PeakParams='32,0,0,0,1')
+   threshold_input = BinMD(InputWorkspace='demo', AlignedDim0='A,-2,2,4', AlignedDim1='B,-2,2,4', AlignedDim2='C,-2,2,4')
+
+   # Run the algorithm to set all values greater than 4 to zero
+   threshold_output = ThresholdMD(InputWorkspace='threshold_input', Condition='Greater Than', ReferenceValue=4)
+
+   # Print selection before and after
+   print "selected bins before threshold greater than 4",threshold_input.getSignalArray()[1,1]
+   print "same bins after threshold greater than 4",threshold_output.getSignalArray()[1,1]
+
+Output:
+
+.. testoutput:: ExThresholdMD
+
+   selected bins before threshold greater than 4 [ 0.  4.  5.  0.]
+   same bins after threshold greater than 4 [ 0.  4.  0.  0.]
 
 .. categories::
diff --git a/Code/Mantid/docs/source/algorithms/UploadRemoteFile-v2.rst b/Code/Mantid/docs/source/algorithms/UploadRemoteFile-v2.rst
new file mode 100644
index 0000000000000000000000000000000000000000..adb2ffa4433579f269aadb5d596ecd820dff7cb2
--- /dev/null
+++ b/Code/Mantid/docs/source/algorithms/UploadRemoteFile-v2.rst
@@ -0,0 +1,37 @@
+.. algorithm::
+
+.. summary::
+
+.. alias::
+
+.. properties::
+
+Description
+-----------
+
+Transfers/uploads a file to the specified (remote) compute
+resource. Presumably, the file is a script or input data
+necessary to run a job on the remote compute resource.
+
+The destination directory depends on the specified transaction ID, and
+its interpretation (absolute or relative to a job or transaction
+environment) is implementation dependent.  See
+:ref:`algm-StartRemoteTransaction` for how to start a transaction.
+
+For more details on remote algorithms when using the Mantid web
+service remote job submission API, see the `remote job submission API
+docs <http://www.mantidproject.org/Remote_Job_Submission_API>`_.
+
+Previous Versions
+-----------------
+
+Version 1
+#########
+
+Version 1 transfers files using the `Mantid remote job submission API
+<http://www.mantidproject.org/Remote_Job_Submission_API>`_. This is
+still supported as one of the variants of Versions 2 and above, when
+the compute resource uses the Mantid remote job submission API as job
+manager (underlying remote job scheduling mechanism).
+
+.. categories::
diff --git a/Code/Mantid/docs/source/algorithms/VisionLoadDetectorTable-v1.rst b/Code/Mantid/docs/source/algorithms/VisionLoadDetectorTable-v1.rst
new file mode 100644
index 0000000000000000000000000000000000000000..05723a89f42dd80092fb70962ff67f6574c5eafc
--- /dev/null
+++ b/Code/Mantid/docs/source/algorithms/VisionLoadDetectorTable-v1.rst
@@ -0,0 +1,21 @@
+.. algorithm::
+
+.. summary::
+
+.. alias::
+
+.. properties::
+
+Description
+-----------
+
+This algorithm is used to load the detector parameters for VISION
+from a CSV file into a TableWorkspace.
+
+.. Note::
+
+        Do not use this algortithm, it is just for VISION commissioning
+
+
+.. categories::
+
diff --git a/Code/Mantid/docs/source/api/python/changes.rst b/Code/Mantid/docs/source/api/python/changes.rst
index e0ea796f4417cf81e70d58b69abc9109893b42d0..4827b55cbd1d70cffca91580f71c5065c322b275 100644
--- a/Code/Mantid/docs/source/api/python/changes.rst
+++ b/Code/Mantid/docs/source/api/python/changes.rst
@@ -7,7 +7,7 @@
 .. note::
 
    This page is intended for those users who have used Python in Mantid v1.x. For
-   new users, see the `getting started guides <http://www.mantidproject.org/Main_Page#Getting_Started>`_.
+   new users, see the `getting started guides <http://www.mantidproject.org/Main_Page>`_.
    	
 After feedback from the usage of Python within Mantid it was decided that 
 some changes to the API would be helpful to make general usage simpler. Unfortunately,
@@ -89,7 +89,7 @@ Changes
 * The *qti* module no longer exists. All user scripts should simply use the *mantidplot* module which contains
   all of the *qti* functionality but adds protection against crashes from closed windows.
 
-* There have also been changes with Python algorithm syntax. For this it will be most beneficial to read the new tutorial `here <http://www.mantidproject.org/Python_Algorithms_Documentation/>`_. 
+* There have also been changes with Python algorithm syntax. For this it will be most beneficial to read the new tutorial `here <http://www.mantidproject.org/Intoduction_to_PythonAlgorithms`_.
 
 Automatic Migration
 -------------------
diff --git a/Code/Mantid/docs/source/api/python/index.rst b/Code/Mantid/docs/source/api/python/index.rst
index ba45b9030ec576c463003caa06c4dc23d67292ba..67f9e1700ff883f792dd773843cce42412b75d6b 100644
--- a/Code/Mantid/docs/source/api/python/index.rst
+++ b/Code/Mantid/docs/source/api/python/index.rst
@@ -6,7 +6,7 @@
 
 The following pages document the Python bindings to the Mantid C++ libraries.
 
-If you are new to Python in Mantid then we advise first looking at our `Mantid training courses <http://www.mantidproject.org/Main_Page#Getting_Started>`_.
+If you are new to Python in Mantid then we advise first looking at our `Mantid training courses <http://www.mantidproject.org/Main_Page>`_.
 
 Reference
 ---------
@@ -24,13 +24,13 @@ Changes between version 1.0 and 2.0 of the API are described :ref:`here <pythona
 
    changes
 
-Future plotting interface
--------------------------
+Matplotlib-like plotting interface
+----------------------------------
 
 .. toctree::
    :maxdepth: 1
 
-   mantidplot.future.pyplot <mantidplot/future/pyplot/index>
+   mantidplot.pyplot <mantidplot/pyplot/index>
 
 Techniques
 ----------
@@ -38,4 +38,4 @@ Techniques
 .. toctree::
    :maxdepth: 1
 
-   techniques/calibration
\ No newline at end of file
+   techniques/calibration
diff --git a/Code/Mantid/docs/source/api/python/mantidplot/future/index.rst b/Code/Mantid/docs/source/api/python/mantidplot/future/index.rst
deleted file mode 100644
index b2b6083bd4f9f3e5d2d06b20b074092bd18c6a68..0000000000000000000000000000000000000000
--- a/Code/Mantid/docs/source/api/python/mantidplot/future/index.rst
+++ /dev/null
@@ -1,15 +0,0 @@
-============================================
- :mod:`mantidplot.future` --- future imports
-============================================
-
-.. module:: mantidplot.future
-
-This module includes future imports.
-
-Submodules
-##########
-
-.. toctree::
-   :maxdepth: 1
-
-   pyplot/index
diff --git a/Code/Mantid/docs/source/api/python/mantidplot/future/pyplot/index.rst b/Code/Mantid/docs/source/api/python/mantidplot/future/pyplot/index.rst
deleted file mode 100644
index c54b9646e1d76df862f5d9d5ce7636ba6d000a76..0000000000000000000000000000000000000000
--- a/Code/Mantid/docs/source/api/python/mantidplot/future/pyplot/index.rst
+++ /dev/null
@@ -1,15 +0,0 @@
-=================================================
- :mod:`future.pyplot` --- Future plotting package
-=================================================
-
-New plotting interface
-----------------------
-
-This package provides a simple command line interface to the Mantid
-plotting functionality, resembling matplotlib and its pyplot package
-(http://matplotlib.org). The module is subject to changes and it is
-provided as a 'future' import. Feedback is very much welcome!
-
-.. automodule:: pymantidplot.future.pyplot
-   :members:
-   :show-inheritance:
diff --git a/Code/Mantid/docs/source/api/python/mantidplot/index.rst b/Code/Mantid/docs/source/api/python/mantidplot/index.rst
index ad217305f362da992e0244291d9d458a7949e1d3..31b5f9d120165ea27a353a7a7c40f5132cb6a394 100644
--- a/Code/Mantid/docs/source/api/python/mantidplot/index.rst
+++ b/Code/Mantid/docs/source/api/python/mantidplot/index.rst
@@ -79,4 +79,4 @@ Submodules
 .. toctree::
    :maxdepth: 1
 
-   future/index
+   pyplot/index
diff --git a/Code/Mantid/docs/source/api/python/mantidplot/pyplot/index.rst b/Code/Mantid/docs/source/api/python/mantidplot/pyplot/index.rst
new file mode 100644
index 0000000000000000000000000000000000000000..824d782aa05e6b6b660935b266beaf008c64d629
--- /dev/null
+++ b/Code/Mantid/docs/source/api/python/mantidplot/pyplot/index.rst
@@ -0,0 +1,15 @@
+===================================================
+ :mod:`pyplot` --- Matplotlib-like plotting package
+===================================================
+
+New plotting interface
+----------------------
+
+This package provides a simple command line interface to the Mantid
+plotting functionality, resembling matplotlib and its pyplot package
+(http://matplotlib.org). The module is subject to changes and feedback
+is very much welcome!
+
+.. automodule:: pymantidplot.pyplot
+   :members:
+   :show-inheritance:
diff --git a/Code/Mantid/docs/source/concepts/FABADA.rst b/Code/Mantid/docs/source/concepts/FABADA.rst
index 2f46108209462f4d0c99b0223b068f54c180720b..3c783a848f3a610ec90bcfce8c0e1fddd5998cde 100644
--- a/Code/Mantid/docs/source/concepts/FABADA.rst
+++ b/Code/Mantid/docs/source/concepts/FABADA.rst
@@ -43,28 +43,44 @@ JumpAcceptanceRate
 FABADA Specific Outputs
 -----------------------
 
-PDF
+PDF (*required*)
   Probability Density Function for each fitted parameter and the cost function.
   This is output as a :ref:`MatrixWorkspace`.
 
-Chains
+Chains (*optional*)
   The value of each parameter and the cost function for each step taken.
   This is output as a :ref:`MatrixWorkspace`.
 
-ConvergedChain
+ConvergedChain (*optional*)
   A subset of Chains containing only the section after which the parameters have
   converged.
   This records the parameters at step intervals given by StepsBetweenValues.
   This is output as a :ref:`MatrixWorkspace`.
 
-CostFunctionTable
+CostFunctionTable (*optional*)
   Table containing the minimum and most probable values of the cost function as
   well as their reduced values.
   This is output as a TableWorkspace.
 
-Parameters
+Parameters (*optional*)
   Similar to the standard parameter table but also includes left and right
   errors for each parameter (cost function is not included).
   This is output as a TableWorkspace.
 
+Usage
+-----
+
+**Example: A simple example**
+
+.. code-block:: python
+
+  ws_data = Load(Filename='irs26176_graphite002_red.nxs')
+  ws_res = Load(Filename='irs26173_graphite002_res.nxs')
+  
+  function_str = 'composite=Convolution,FixResolution=tue,NumDeriv=false;name=Resolution,Workspace=ws_res,WorkspaceIndex=0;(composite=CompositeFunction,NumDeriv=true;name=Lorentzian,Amplitude=1,PeakCentre=0.01,FWHM=0.5;name=Lorentzian,Amplitude=1,PeakCentre=0.01,FWHM=0.5)'
+  minimizer_str = "FABADA,Chain Lengh=1000000,Steps between values=10,Convergence Criteria=0.01,PDF=pdf,Chains=chain,Converged chain=conv,Cost Function Table=CostFunction,Parameter Erros =Errors"
+  
+  Fit(Function = function_str,InputWorkspace=ws_data,WorkspaceIndex=3,StartX=-0.25,EndX=0.25,CreateOutput=True,Output = 'result',OutputCompositeMembers=True,MaxIterations=2000000, Minimizer=minimizer_str)   
+
+
 .. categories:: Concepts
diff --git a/Code/Mantid/docs/source/concepts/InstrumentDefinitionFile.rst b/Code/Mantid/docs/source/concepts/InstrumentDefinitionFile.rst
index acdf04823d6ba5cd380fd0ce085bdb484879dbbe..ee404baee5d47be44bdaaecff9d1d310f4107b76 100644
--- a/Code/Mantid/docs/source/concepts/InstrumentDefinitionFile.rst
+++ b/Code/Mantid/docs/source/concepts/InstrumentDefinitionFile.rst
@@ -192,7 +192,7 @@ Of the four attributes in the example above
 
 (+) Both valid-from and valid-to are required to be set using the ISO
 8601 date-time format, i.e. as YYYY-MM-DD HH:MM:SS or
-YYYY-MM-DDTHH:MM:SS `2 <http://en.wikipedia.org/wiki/ISO_8601YYYY>`__.
+YYYY-MM-DDTHH:MM:SS `2 <http://en.wikipedia.org/wiki/ISO_8601>`__.
 Valid ranges may overlap, provided the valid-from times are all
 different. If several files are currently valid, the one with the most
 recent valid-from time is selected.
diff --git a/Code/Mantid/docs/source/concepts/PointAndSpaceGroups.rst b/Code/Mantid/docs/source/concepts/PointAndSpaceGroups.rst
new file mode 100644
index 0000000000000000000000000000000000000000..f879d1e12310122c055e4c1d1038aa92ea9d9658
--- /dev/null
+++ b/Code/Mantid/docs/source/concepts/PointAndSpaceGroups.rst
@@ -0,0 +1,375 @@
+.. _Point and space groups:
+
+Point and space groups
+======================
+
+This document explains how crystallographic point and space groups are used in Mantid. The :ref:`document <Symmetry groups>` about symmetry operations, elements and groups is a prerequisite for this text, so it is recommended to read it beforehand.
+
+Introduction
+------------
+
+As explained in the general text covering symmetry groups, groups are used to describe symmetry of objects in space. For crystallography, point and space groups are essential tools to describe crystal structures and aspects of diffraction experiments. According to the definition given in the International Tables for Crystallography A, a "point group is a group of symmetry operations all of which leave at least one point unmoved" [ITAPointGroups]_. This means that only symmetry operations without a translational component are allowed, which leaves only rotations :math:`1`, :math:`2`, :math:`3`, :math:`4`, :math:`6` and roto-inversions :math:`\bar{1}`, :math:`\bar{3}`, :math:`\bar{4}`, :math:`\bar{6}` and mirror planes :math:`m`. In space groups, translational symmetry is present as well (for example in the form of screw axes and glide planes).
+
+Theory
+------
+
+In three dimensions there are 32 crystallographic point groups and in 11 of these an inversion center (:math:`\bar{1}`) is present. These so called Laue classes are important for diffraction experiments because Friedel's law defines that diffraction patterns always show a center of symmetry if anomalous dispersion is not taken into account.
+
+Through the presence of certain symmetry operations in certain directions, the Laue classes (and also the point groups) can be categorized into seven crystal systems (see table below). This information is included in the Hermann-Mauguin symbol, which describes symmetry along different directions, depending on the crystal system.
+
+.. table:: The seven crystal systems and how they relate to the 11 Laue classes and the 32 crystallographic point groups
+
+    +----------------+-------------------------------------+------------------------------------------------------------------------------------------------------------------------+
+    | Crystal system | Laue classes                        | Point groups                                                                                                           |
+    +================+=====================================+========================================================================================================================+
+    | Cubic          | :math:`m\bar{3}`, :math:`m\bar{3}m` | :math:`23`, :math:`m\bar{3}`, :math:`432`, :math:`\bar{4}3m`, :math:`m\bar{3}m`                                        |
+    +----------------+-------------------------------------+------------------------------------------------------------------------------------------------------------------------+
+    | Hexagonal      | :math:`6/m`, :math:`6/mmm`          | :math:`6`, :math:`\bar{6}`, :math:`6/m`, :math:`622`, :math:`6mm`, :math:`\bar{6}2m`, :math:`\bar{6}m2`, :math:`6/mmm` |
+    +----------------+-------------------------------------+------------------------------------------------------------------------------------------------------------------------+
+    | Trigonal       | :math:`\bar{3}`, :math:`\bar{3}m`   | :math:`3`, :math:`\bar{3}`, :math:`321`, :math:`312`, :math:`3m1`, :math:`31m`, :math:`\bar{3}m1`, :math:`\bar{3}1m`   |
+    +----------------+-------------------------------------+------------------------------------------------------------------------------------------------------------------------+
+    | Tetragonal     | :math:`4/m`, :math:`4/mmm`          | :math:`4`, :math:`\bar{4}`, :math:`4/m`, :math:`422`, :math:`4mm`, :math:`\bar{4}2m`, :math:`\bar{4}m2`, :math:`4/mmm` |
+    +----------------+-------------------------------------+------------------------------------------------------------------------------------------------------------------------+
+    | Orthorhombic   | :math:`mmm`                         | :math:`222`, :math:`mm2`, :math:`mmm`                                                                                  |
+    +----------------+-------------------------------------+------------------------------------------------------------------------------------------------------------------------+
+    | Monoclinic     | :math:`2/m`                         | :math:`2`, :math:`m`, :math:`2/m`                                                                                      |
+    +----------------+-------------------------------------+------------------------------------------------------------------------------------------------------------------------+
+    | Triclinic      | :math:`\bar{1}`                     | :math:`1`, :math:`\bar{1}`                                                                                             |
+    +----------------+-------------------------------------+------------------------------------------------------------------------------------------------------------------------+
+
+Any point group can be generated by using a maximum of three symmetry operations as so-called generators using the principle described in [Shmueli84]_. According to this, any point group can be described either as a cyclic group or as a product of maximum three cyclic groups. The point group :math:`4` is an example for a group that is simply a cyclic group generated from a positive four fold rotation axis along the :math:`z`-axis, which has the order 4.
+
+.. math::
+    G = \left\{{4^{+}}^0, {4^{+}}^1, {4^{+}}^2, {4^{+}}^3\right\} = \left\{1, 4^{+}, 2, 4^{-}\right\}
+    
+So by specifying one single symmetry operation as generator, all symmetry operations of the point group in question are generated. From this it's convenient to expand the example to generate a point group that can be expressed as the product of two cyclic groups - :math:`4/m`. In this point group, an additional mirror plane is present perpendicular to the four fold axis. The point group can be expressed as product of :math:`4` shown above and a cyclic group generated by the symmetry operation :math:`m` (mirror plane perpendicular to :math:`z`):
+
+.. math::
+    G' = G \cdot \left\{m^0, m^1\right\} = \left\{1, 4^{+}, 2, 4^{-}\right\} \cdot \left\{1, m\right\} = \left\{1, m, 4^{+}, \bar{4}^{+}, 2, \bar{1}, 4^{-}, \bar{4}^{-}\right\}
+    
+This means that :math:`4/m` contains an inversion center as well as a four fold rotoinversion axis which result from the combination of the operations of the two cyclic groups. It's also possible to use a different cyclic group to achive the same result (:math:`\bar{1}`). As mentioned above, for some point groups it's necessary to use three generators, which follows the same principle and is not shown here.
+
+Space groups can be handled in a very similar way if translations are limited to the interval :math:`[0, 1)` so that screw-axes and glide-planes can also be used to generate cyclic groups. Without this limitation, the translational components would not be the same for :math:`S^k` and :math:`S^0`.
+
+Using point groups in Mantid
+----------------------------
+
+Point groups are represented in Mantid by the ``PointGroup``-class, which is constructed for each actual point group using generators. The interface of the class consists of two parts, one for providing information about the point group and one for working with :math:`hkl`-indices. Just as in the case of ``SymmetryOperation``, ``PointGroup``-objects are created using a factory, this time by supplying the short Hermann-Mauguin symbol [#f1]_ :
+
+.. testcode :: ExInformation
+
+    from mantid.geometry import PointGroupFactory
+    
+    pg = PointGroupFactory.createPointGroup("-1")
+    
+    print "Name:", pg.getName()
+    print "Hermann-Mauguin symbol:", pg.getHMSymbol()
+    print "Crystal system:", pg.getCrystalSystem()
+    
+When this code is executed, some information about the point group is printed:
+    
+.. testoutput :: ExInformation
+
+    Name: -1 (Triclinic)
+    Hermann-Mauguin symbol: -1
+    Crystal system: Triclinic
+    
+It's possible to query the factory about available point groups. One option returns a list of all available groups, while another possibility is to get only groups from a certain crystal system:
+
+.. testcode :: ExQueryPointGroups
+
+    from mantid.geometry import PointGroupFactory, PointGroup
+    
+    print "All point groups:", PointGroupFactory.getAllPointGroupSymbols()
+    print "Cubic point groups:", PointGroupFactory.getPointGroupSymbols(PointGroup.CrystalSystem.Cubic)
+    print "Tetragonal point groups:", PointGroupFactory.getPointGroupSymbols(PointGroup.CrystalSystem.Tetragonal)
+    
+Which results in the following output:
+
+.. testoutput :: ExQueryPointGroups
+
+    All point groups: ['-1','-3','-3 r','-31m','-3m','-3m r','-3m1','-4','-42m','-43m','-4m2','-6','-62m','-6m2','1','112/m','2','2/m','222','23','3','3 r','312','31m','32','32 r','321','3m','3m r','3m1','4','4/m','4/mmm','422','432','4mm','6','6/m','6/mmm','622','6mm','m','m-3','m-3m','mm2','mmm']
+    Cubic point groups: ['-43m','23','432','m-3','m-3m']
+    Tetragonal point groups: ['-4','-42m','-4m2','4','4/m','4/mmm','422','4mm']
+
+The point groups with an extra ``r`` at the end are trigonal point groups with rhombohedral axes. Trigonal point groups without that additional letter use the hexagonal coordinate system. For some of them there are two different axis choices, for example :math:`\bar{3}m`, which can be defined as :math:`\bar{3}m1` or :math:`\bar{3}1m`. Creating it by the symbol ``-3m`` defaults to :math:`\bar{3}m1`.
+
+After having obtained a ``PointGroup``-object, it can be used for working with reflection data, more specifically :math:`hkl`-indices. It's possible to check whether two reflections are equivalent in a certain point group:
+
+.. testcode :: ExIsEquivalent
+
+    from mantid.geometry import PointGroupFactory
+
+    pg = PointGroupFactory.createPointGroup("m-3m")
+
+    hkl1 = [2, 0, 0]
+    hkl2 = [0, 0, -2]
+    hkl3 = [0, 1, 2]
+
+    print "Are [2,0,0] and [0,0,-2] equivalent?", pg.isEquivalent(hkl1, hkl2)
+    print "Are [2,0,0] and [0,1,2] equivalent?", pg.isEquivalent(hkl1, hkl3)
+    
+.. testoutput :: ExIsEquivalent
+
+    Are [2,0,0] and [0,0,-2] equivalent? True
+    Are [2,0,0] and [0,1,2] equivalent? False
+    
+Another common task is to find all symmetry equivalents of a reflection, for example to determine its multiplicity. ``PointGroup`` has a method for this purpose which returns the set of non-identical symmetry equivalents for a given :math:`hkl` (including :math:`hkl` itself):
+
+.. testcode :: ExGetEquivalents
+
+    from mantid.geometry import PointGroupFactory
+
+    pg = PointGroupFactory.createPointGroup("m-3m")
+
+    hkl1 = [2, 0, 0]
+    equivalents1 = pg.getEquivalents(hkl1)
+
+    print "Number of reflections equivalent to [2,0,0]:", len(equivalents1)
+    print "Equivalents:", equivalents1
+    print
+
+    hkl2 = [1, 1, 1]
+    equivalents2 = pg.getEquivalents(hkl2)
+
+    print "Number of reflections equivalent to [1,1,1]:", len(equivalents2)
+    print "Equivalents:", equivalents2
+    
+Executing this code results in the following output:
+    
+.. testoutput :: ExGetEquivalents
+
+    Number of reflections equivalent to [2,0,0]: 6
+    Equivalents: [[2,0,0], [0,2,0], [0,0,2], [0,0,-2], [0,-2,0], [-2,0,0]]
+    
+    Number of reflections equivalent to [1,1,1]: 8
+    Equivalents: [[1,1,1], [1,1,-1], [1,-1,1], [1,-1,-1], [-1,1,1], [-1,1,-1], [-1,-1,1], [-1,-1,-1]]
+    
+Sometimes, a list of reflections needs to be reduced to a set of symmetry independent reflections only. That means it should not contain any two reflections that are symmetry equivalents according to the point group symmetry. To achieve this, ``PointGroup`` offers a method that returns the same :math:`hkl'` for all symmetry equivalents.
+
+.. testcode :: ExIndependentReflections
+
+    from mantid.geometry import PointGroupFactory
+
+    pg = PointGroupFactory.createPointGroup("m-3m")
+
+    hklList = [[1, 0, 0], [0, 1, 0], [-1, 0, 0],    # Equivalent to [1,0,0]
+               [1, 1, 1], [-1, 1, 1],               # Equivalent to [1,1,1]
+               [-3, 1, 1], [1, -3, 1], [-1, 1, 3]]  # Equivalent to [3,1,1]
+                 
+    independent = set()
+
+    for hkl in hklList:
+        independent.add(pg.getReflectionFamily(hkl)) # getReflectionFamily returns the same hkl for all symmetry equivalents
+        
+    print "Number of independent reflections:", len(independent)
+    print "Reflections:", list(independent)
+    
+This example code produces the output below upon execution:
+
+.. testoutput:: ExIndependentReflections
+
+    Number of independent reflections: 3
+    Reflections: [[1,1,1], [1,0,0], [3,1,1]]
+
+This is all that's covered by the Python interface regarding point groups in Mantid at the time of this writing. The use in C++ is very similar and described in detail in the API documentation.
+    
+Using space groups in Mantid
+----------------------------
+
+Space group representation in Mantid is very similar to the point group representation, there is a ``SpaceGroup``-class that contains some information about the group, but also a method to generate equivalent positions from a coordinate triplet.
+
+Exactly like point groups, space groups are also created using a factory:
+
+.. testcode:: ExSpaceGroupInfo
+
+    from mantid.geometry import SpaceGroupFactory
+    
+    sg = SpaceGroupFactory.createSpaceGroup("P -1")
+    print "Hermann-Mauguin symbol:", sg.getHMSymbol()
+    print "ITA number:", sg.getNumber()
+    
+Executing this code shows the Hermann-Mauguin symbol of the space group as well as the number defined in ITA:
+
+.. testoutput:: ExSpaceGroupInfo
+
+    Hermann-Mauguin symbol: P -1
+    ITA number: 2
+    
+For some space group types there is more than one setting. Even though these are not present in Mantid at the time of this writing, the factory already supports querying the available symbols for a given number:
+
+.. testcode:: ExSpaceGroupNumber
+
+    from mantid.geometry import SpaceGroupFactory
+    
+    print "Space group no. 2:", SpaceGroupFactory.subscribedSpaceGroupSymbols(2)
+    print "Total subscribed space group types:", len(SpaceGroupFactory.getAllSpaceGroupNumbers())
+    
+This shows that only one symbol is registered for space group number 2, and that there are 230 space group types:
+
+.. testoutput:: ExSpaceGroupNumber
+
+    Space group no. 2: ['P -1']
+    Total subscribed space group types: 230
+
+Besides containing some very basic information, the most important functionality is the ability to generate equivalent coordinates. The following example generates all coordinates for the :math:`4h` position in space group :math:`P6/m` (No. 175):
+
+.. testcode:: ExEquivalentCoordinates
+
+    from mantid.geometry import SpaceGroupFactory
+    
+    sg = SpaceGroupFactory.createSpaceGroup("P 6/m")
+    
+    position = [1./3., 2./3., 0.25]
+    equivalents = sg.getEquivalentPositions(position)
+    
+    print "There are", len(equivalents), "equivalent coordinates."
+    print "Coordinates:"
+    for i, pos in enumerate(equivalents):
+        print str(i + 1) + ":", pos
+        
+Please note that for hexagonal and trigonal space groups, where translations of :math:`1/3`, :math:`2/3`, :math:`1/6` and so on are common, these coordinates must be supplied either as ``1./3.`` or with a precision of 7 digits, e.g. ``0.6666667``.
+        
+.. testoutput:: ExEquivalentCoordinates
+
+    There are 4 equivalent coordinates.
+    Coordinates:
+    1: [0.333333,0.666667,0.25]
+    2: [0.333333,0.666667,0.75]
+    3: [0.666667,0.333333,0.25]
+    4: [0.666667,0.333333,0.75]
+    
+Furthermore, it is possible to create a PointGroup-object from a SpaceGroup object in order to obtain information about the crystal system and to perform the Miller index operations provided by PointGroup. For this, PointGroupFactory has a special method:
+
+.. testcode:: ExPointGroupFromSpaceGroup
+
+    from mantid.geometry import PointGroupFactory, SpaceGroupFactory
+
+    # Create space group Fd-3m (for example silicon or diamond)
+    sg = SpaceGroupFactory.createSpaceGroup("F d -3 m")
+    
+    pg = PointGroupFactory.createPointGroupFromSpaceGroup(sg)
+    
+    print "Space group no.", sg.getNumber(), "has point group:", pg.getHMSymbol()
+    
+The script prints the point group of the space group in question:
+    
+.. testoutput:: ExPointGroupFromSpaceGroup
+
+    Space group no. 227 has point group: m-3m
+    
+Very similar constructions are available in C++ as well, as shown in the API documentation.
+    
+Other ways of using groups in Mantid
+------------------------------------
+
+The previous two sections demonstrated how to perform common tasks using point and space groups in Mantid. With the available Python tools it is however possible to obtain other information as well. One useful method that both PointGroup and SpaceGroup expose is to query the symmetry operations of the group, although in string format:
+
+.. testcode:: ExGroupSymmetryOperationStrings
+
+    from mantid.geometry import SpaceGroupFactory
+    
+    sg = SpaceGroupFactory.createSpaceGroup("P 6/m")    
+    symOpStrings = sorted(sg.getSymmetryOperationStrings())
+    
+    print "There are", len(symOpStrings), "symmetry operations in space group", sg.getHMSymbol() + "."
+    print "Symmetry operations:", symOpStrings
+    
+Which prints the symmetry operation information:
+
+.. testoutput:: ExGroupSymmetryOperationStrings
+
+    There are 12 symmetry operations in space group P 6/m.
+    Symmetry operations: ['-x+y,-x,-z', '-x+y,-x,z', '-x,-y,-z', '-x,-y,z', '-y,x-y,-z', '-y,x-y,z', 'x,y,-z', 'x,y,z', 'x-y,x,-z', 'x-y,x,z', 'y,-x+y,-z', 'y,-x+y,z']
+    
+While this can be interesting for informational purposes, it's more useful to obtain the symmetry operations directly as objects to use them for new purposes. This script for example sorts the contained symmetry operations according to their order:
+
+.. testcode:: ExGroupSymmetryOperations
+
+    from mantid.geometry import SpaceGroupFactory
+    
+    def getMaximumOrderOperation(spaceGroup):
+        return sorted(spaceGroup.getSymmetryOperations(), key=lambda x: x.getOrder())[-1]
+    
+    sg1 = SpaceGroupFactory.createSpaceGroup("P 6/m")
+    sg2 = SpaceGroupFactory.createSpaceGroup("P 4 3 2")
+    
+    # Get the symmetry operation with the highest order
+    symOpMax1 = getMaximumOrderOperation(sg1)
+    symOpMax2 = getMaximumOrderOperation(sg2)
+    
+    print "The symmetry operation with highest order in space group no.", sg1.getNumber(), "is:", symOpMax1.getIdentifier(), "(k=" + str(symOpMax1.getOrder()) + ")"
+    print "The symmetry operation with highest order in space group no.", sg2.getNumber(), "is:", symOpMax2.getIdentifier(), "(k=" + str(symOpMax2.getOrder()) + ")"
+    
+Which produces the following output:
+
+.. testoutput:: ExGroupSymmetryOperations
+
+    The symmetry operation with highest order in space group no. 175 is: y,-x+y,z (k=6)
+    The symmetry operation with highest order in space group no. 207 is: z,y,-x (k=4)
+    
+Another way to extract more information about the symmetry in a space group is to obtain the symmetry elements and arrange them by their characteristic axis:
+
+.. testcode:: ExGroupSymmetryElements
+
+    from mantid.kernel import V3D
+    from mantid.geometry import PointGroupFactory, SpaceGroupFactory, SymmetryElementFactory
+
+    def getSymmetryElementsFromOperations(symmetryOperations):
+        return [SymmetryElementFactory.createSymElement(x) for x in symmetryOperations]
+
+    sg = SpaceGroupFactory.createSpaceGroup("P n m a")
+    pg = PointGroupFactory.createPointGroupFromSpaceGroup(sg)
+
+    symElements = getSymmetryElementsFromOperations(sg.getSymmetryOperations())    
+    symElementsByAxis = {}
+    symElementsNoAxis = []
+
+    for symElem in symElements:
+        axis = pg.getReflectionFamily(symElem.getAxis())
+        #axis = symElem.getAxis()
+        
+        # If axis is [0,0,0], put the element into the "no axis" list
+        if axis == V3D(0, 0, 0):
+            symElementsNoAxis.append(symElem)
+        else:
+            # Otherwise check if that axis is already in the dictionary with a list...
+            if axis in symElementsByAxis.keys():
+                symElementsByAxis[axis].append(symElem)
+            # ...or create a new list for that axis
+            else:
+                symElementsByAxis[axis] = [symElem]
+
+    noAxisSymbols = [x.getHMSymbol() for x in symElementsNoAxis]
+    print "There are", len(symElementsNoAxis), "element(s) with no characteristic axis."
+    print "Are there translations?", "Yes" if 't' in noAxisSymbols else "No"
+
+    axes = symElementsByAxis.keys()
+    print "There is a total of", len(axes), "different characteristic axes."
+    print "Symmetry in each direction:"
+
+    for axis in sorted(axes):
+        print str(axis) + ": ", sorted([x.getHMSymbol() for x in symElementsByAxis[axis]])
+        
+This prints the following information:
+
+.. testoutput:: ExGroupSymmetryElements
+
+    There are 2 element(s) with no characteristic axis.
+    Are there translations? No
+    There is a total of 3 different characteristic axes.
+    Symmetry in each direction:
+    [0,0,1]:  ['21', 'a']
+    [0,1,0]:  ['21', 'm']
+    [1,0,0]:  ['21', 'n']
+    
+Looking up space group number 62 (:math:`Pnma` from the example) in ITA shows that the full Hermann-Mauguin symbol for that space group is :math:`P 2_1/n 2_1/m 2_1/a`. The short script gives us all of this information, since there are no translations (the primitive lattice translations are implicit) it must be a primitive lattice (:math:`P`) and all directions encoded in the HM-symbol contain a :math:`2_1` screw axis perpendicular to a glide or mirror plane.
+    
+.. [ITAPointGroups] International Tables for Crystallography (2006). Vol. A, ch. 10.1, p. 762
+
+.. [Shmueli84] U. Shmueli, Acta Crystallogr. A, 40, p. 559 `DOI: 10.1107/S0108767384001161 <http://dx.doi.org/10.1107/S0108767384001161>`_)
+
+.. [#f1] In the case of the monoclinic Laue class :math:`2/m` it's a bit more complicated, because there are two conventions regarding the unique axis. According to current crystallographic standards, the :math:`b`-axis is used, but in some cases one may find the :math:`c`-axis for this purpose. To resolve this, both options are offered in Mantid. When using the symbol ``2/m``, the :math:`b`-axis convention is used, for :math:`c` one has to explicitly provide the symbol as ``112/m``.
+
+
+.. categories:: Concepts
diff --git a/Code/Mantid/docs/source/concepts/PointGroups.rst b/Code/Mantid/docs/source/concepts/PointGroups.rst
deleted file mode 100644
index 6904bc58deef63c146bd075771539316cce8d323..0000000000000000000000000000000000000000
--- a/Code/Mantid/docs/source/concepts/PointGroups.rst
+++ /dev/null
@@ -1,265 +0,0 @@
-.. _Point groups:
-
-Point Groups
-============
-
-This document explains how crystallographic point groups are used in Mantid.
-
-Introduction
-------------
-
-Point groups can be used to describe the symmetry of an object or a lattice, as commonly used in the context of diffraction techniques. According to the definition given in the International Tables for Crystallography A, a "point group is a group of symmetry operations all of which leave at least one point unmoved" [ITA6]_. This means that only symmetry operations without a translational component are allowed, which leaves only rotations :math:`1`, :math:`2`, :math:`3`, :math:`4`, :math:`6` and roto-inversions :math:`\bar{1}`, :math:`\bar{3}`, :math:`\bar{4}`, :math:`\bar{6}` and mirror planes :math:`m`. In space groups, translational symmetry is present as well (for example in the form of screw axes and glide planes).
-
-In three dimensions there are 32 crystallographic point groups and in 11 of these an inversion center (:math:`\bar{1}`) is present. These so called Laue classes are important for diffraction experiments because Friedel's law defines that diffraction patterns always show a center of symmetry if anomalous dispersion is not taken into account.
-
-Through the presence of certain symmetry operations in certain directions, the Laue classes can be categorized into seven crystal systems (see table below). This information is included in the Hermann-Mauguin symbol, which describes symmetry along different directions, depending on the crystal system.
-
-.. table:: The seven crystal systems and how they relate to the 11 Laue classes.
-
-    +----------------+-------------------------------------+
-    | Crystal system | Laue classes                        |
-    +================+=====================================+
-    | Cubic          | :math:`m\bar{3}`, :math:`m\bar{3}m` |
-    +----------------+-------------------------------------+
-    | Hexagonal      | :math:`6/m`, :math:`6/mmm`          |
-    +----------------+-------------------------------------+
-    | Trigonal       | :math:`\bar{3}`, :math:`\bar{3}m`   |
-    +----------------+-------------------------------------+
-    | Tetragonal     | :math:`4/m`, :math:`4/mmm`          |
-    +----------------+-------------------------------------+
-    | Orthorhombic   | :math:`mmm`                         |
-    +----------------+-------------------------------------+
-    | Monoclinic     | :math:`2/m`                         |
-    +----------------+-------------------------------------+
-    | Triclinic      | :math:`\bar{1}`                     |
-    +----------------+-------------------------------------+
-    
-As mentioned before, point groups can describe the symmetry of a lattice, including the reciprocal lattice. When working with diffraction data, which are often described in terms of reciprocal lattice vectors with their Miller indices :math:`hkl` (since it's a vector it can be written shortly as :math:`\mathbf{h}`), this is particularly useful. Each symmetry operation :math:`S_i` of the point group transforms a vector :math:`\mathbf{h}` into a new vector :math:`\mathbf{h}'`:
-
-.. math::
-    \mathbf{h}' = \mathbf{S}_i \cdot \mathbf{h}
-    
-To describe the rotational and translational components of the symmetry operation, a matrix :math:`\mathbf{W}_i` and a vector :math:`\mathbf{w}_i` are used. In three dimensions :math:`\mathbf{h}` has three elements, so :math:`\mathbf{W}_i` is a :math:`3\times3`-matrix and the symmetry operation is applied like this:
-
-.. math::
-    \mathbf{h}' = {\mathbf{W}_i^{-1}}^T \cdot \mathbf{h}
-
-Note that the translational component is not used for transforming HKLs and :math:`\mathbf{W}_i` is inverted and transposed. Coordinates :math:`\mathbf{x}` are transformed differently, they are affected by the translational component:
-
-.. math::
-    \mathbf{x}' = \mathbf{W}_i \cdot \mathbf{x} + \mathbf{w}_i
-
-A point group is an ensemble of symmetry operations. The number of operations present in this collection is the so called order :math:`N` of the corresponding point group. Applying all symmetry operations of a point group to a given vector :math:`\mathbf{h}` results in :math:`N` new vectors :math:`\mathbf{h}'`, some of which may be identical (this depends on the symmetry and also on the vectors, e.g. if one or more index is 0). This means that the symmetry operations of a point group generate a set of :math:`N'` (where :math:`N' < N`) non-identical vectors :math:`\mathbf{h}'` for a given vector :math:`\mathbf{h}` - these vectors are called symmetry equivalents.
-
-A very common representation of symmetry operations is the Jones faithful notation, which is very concise and used throughout the International Tables. Some examples of the notation are given in the following table.
-
-.. table:: Examples for symmetry operations in Jones faithful notation.
-
-    =============== ===================
-    Symbol          Symmetry operation
-    =============== ===================
-    ``x,y,z``       Identity
-    ``-x,-y,-z``    Inversion
-    ``-x,-y,z``     2-fold rotation around :math:`z`
-    ``x,y,-z``      Mirror plane perpendicular to :math:`z`
-    ``-x,-y,z+1/2`` :math:`2_1` screw axis along :math:`z`
-    =============== ===================
-
-
-Using symmetry operations
--------------------------
-
-As explained above, point groups are represented as a collection of symmetry operations, which in turn are described by a :math:`3\times3`-matrix for the rotational part and a :math:`3\times1`-vector for the translational component.
-
-Using these identifiers, ``SymmetryOperation``-objects can be created through a factory and then used to transform vectors. The following code sample shows how to do that in Python:
-
-.. testcode :: ExSymmetryOperation
-
-    from mantid.geometry import SymmetryOperation, SymmetryOperationFactory
-    
-    symOp = SymmetryOperationFactory.createSymOp("x,y,-z")
-    
-    hkl = [1, -1, 3]
-    hklPrime = symOp.transformHKL(hkl)
-    
-    print "Mirrored hkl:", hklPrime
-    
-The above code will print the mirrored index:
-
-.. testoutput :: ExSymmetryOperation
-
-    Mirrored hkl: [1,-1,-3]
-    
-Point groups can also be used to transform coordinates, which are handled a bit differently than vectors (as described above), so there the symmetry operation class has a dedicated method for performing this operation:
-
-.. testcode :: ExSymmetryOperationPoint
-
-    from mantid.geometry import SymmetryOperation, SymmetryOperationFactory
-    
-    symOp = SymmetryOperationFactory.createSymOp("x-y,x,z")
-    
-    coordinates = [0.3, 0.4, 0.5]
-    coordinatesPrime = symOp.transformCoordinates(coordinates)
-    
-    print "Transformed coordinates:", coordinatesPrime
-    
-The script prints the transformed coordinates:
-
-.. testoutput :: ExSymmetryOperationPoint
-
-    Transformed coordinates: [-0.1,0.3,0.5]
-
-Please note that in case of hexagonal or trigonal point groups, it is best to provide the often occuring values 1/3 and 2/3 actually as ``1./3.`` instead of ``0.33333``, as there may be problems with floating point precision in those cases.
-
-Sometimes it is easier to think about symmetry in terms of the elements that cause certain symmetry. These are commonly described with Herrman-Mauguin symbols. A symmetry element can be derived from the matrix/vector pair that described the symmetry operation, according to the International Tables for Crystallography A, section 11.2. Expanding a bit on the above example, it's possible to get information about the symmetry element associated to the operation ``x,y,-z``:
-
-.. testcode :: ExSymmetryElement
-
-    from mantid.geometry import SymmetryOperation, SymmetryOperationFactory
-    from mantid.geometry import SymmetryElement, SymmetryElementFactory
-
-    symOp = SymmetryOperationFactory.createSymOp("x,y,-z")
-    element = SymmetryElementFactory.createSymElement(symOp)
-
-    print "The element corresponding to 'x,y,-z' has the following symbol:", element.getHMSymbol()
-    print "The mirror plane is perpendicular to:", element.getAxis()
-
-Executing this code yields the following output:
-
-.. testoutput :: ExSymmetryElement
-
-    The element corresponding to 'x,y,-z' has the following symbol: m
-    The mirror plane is perpendicular to: [0,0,1]
-
-Some symmetry elements (identity, inversion center, translation) do not have an axis. In these cases, ``[0,0,0]`` is returned from that method.
-
-The corresponding code in C++ looks very similar and usage examples can be found in the code base, mainly in the implementation of ``PointGroup``, which will be the next topic.
-
-Using point groups
-------------------
-
-Point groups are represented in Mantid by the ``PointGroup``-interface, which is then implemented for each actual point group. The interface consists of two parts, one for providing information about the point group and one for working with :math:`hkl`-indices. Just as in the case of ``SymmetryOperation``, ``PointGroup``-objects are created using a factory, this time by supplying the short Hermann-Mauguin symbol [#f1]_ :
-
-.. testcode :: ExInformation
-
-    from mantid.geometry import PointGroup, PointGroupFactory
-    
-    pg = PointGroupFactory.createPointGroup("-1")
-    
-    print "Name:", pg.getName()
-    print "Hermann-Mauguin symbol:", pg.getHMSymbol()
-    print "Crystal system:", pg.getCrystalSystem()
-    
-When this code is executed, some information about the point group is printed:
-    
-.. testoutput :: ExInformation
-
-    Name: -1 (Triclinic)
-    Hermann-Mauguin symbol: -1
-    Crystal system: Triclinic
-    
-It's possible to query the factory about available point groups. One option returns a list of all available groups, while another possibility is to get only groups from a certain crystal system:
-
-.. testcode :: ExQueryPointGroups
-
-    from mantid.geometry import PointGroup, PointGroupFactory
-    
-    print "All point groups:", PointGroupFactory.getAllPointGroupSymbols()
-    print "Cubic point groups:", PointGroupFactory.getPointGroupSymbols(PointGroup.CrystalSystem.Cubic)
-    print "Tetragonal point groups:", PointGroupFactory.getPointGroupSymbols(PointGroup.CrystalSystem.Tetragonal)
-    
-Which results in the following output:
-
-.. testoutput :: ExQueryPointGroups
-
-    All point groups: ['-1','-3','-3 r','-31m','-3m','-3m r','-3m1','-4','-42m','-43m','-4m2','-6','-62m','-6m2','1','112/m','2','2/m','222','23','3','3 r','312','31m','32','32 r','321','3m','3m r','3m1','4','4/m','4/mmm','422','432','4mm','6','6/m','6/mmm','622','6mm','m','m-3','m-3m','mm2','mmm']
-    Cubic point groups: ['-43m','23','432','m-3','m-3m']
-    Tetragonal point groups: ['-4','-42m','-4m2','4','4/m','4/mmm','422','4mm']
-
-The point groups with an extra ``r`` at the end are trigonal point groups with rhombohedral axes. Trigonal point groups without that additional letter use the hexagonal coordinate system. For some of them there are two different axis choices, for example :math:`\bar{3}m`, which can be defined as :math:`\bar{3}m1` or :math:`\bar{3}1m`. Creating it by the symbol ``-3m`` defaults to :math:`\bar{3}m1`.
-
-After having obtained a ``PointGroup``-object, it can be used for working with reflection data, more specifically :math:`hkl`-indices. It's possible to check whether two reflections are equivalent in a certain point group:
-
-.. testcode :: ExIsEquivalent
-
-    from mantid.geometry import PointGroup, PointGroupFactory
-
-    pg = PointGroupFactory.createPointGroup("m-3m")
-
-    hkl1 = [2, 0, 0]
-    hkl2 = [0, 0, -2]
-    hkl3 = [0, 1, 2]
-
-    print "Are [2,0,0] and [0,0,-2] equivalent?", pg.isEquivalent(hkl1, hkl2)
-    print "Are [2,0,0] and [0,1,2] equivalent?", pg.isEquivalent(hkl1, hkl3)
-    
-.. testoutput :: ExIsEquivalent
-
-    Are [2,0,0] and [0,0,-2] equivalent? True
-    Are [2,0,0] and [0,1,2] equivalent? False
-    
-Another common task is to find all symmetry equivalents of a reflection, for example to determine its multiplicity. ``PointGroup`` has a method for this purpose which returns the set of non-identical symmetry equivalents for a given :math:`hkl` (including :math:`hkl` itself):
-
-.. testcode :: ExGetEquivalents
-
-    from mantid.geometry import PointGroup, PointGroupFactory
-
-    pg = PointGroupFactory.createPointGroup("m-3m")
-
-    hkl1 = [2, 0, 0]
-    equivalents1 = pg.getEquivalents(hkl1)
-
-    print "Number of reflections equivalent to [2,0,0]:", len(equivalents1)
-    print "Equivalents:", equivalents1
-    print
-
-    hkl2 = [1, 1, 1]
-    equivalents2 = pg.getEquivalents(hkl2)
-
-    print "Number of reflections equivalent to [1,1,1]:", len(equivalents2)
-    print "Equivalents:", equivalents2
-    
-Executing this code results in the following output:
-    
-.. testoutput :: ExGetEquivalents
-
-    Number of reflections equivalent to [2,0,0]: 6
-    Equivalents: [[2,0,0], [0,2,0], [0,0,2], [0,0,-2], [0,-2,0], [-2,0,0]]
-    
-    Number of reflections equivalent to [1,1,1]: 8
-    Equivalents: [[1,1,1], [1,1,-1], [1,-1,1], [1,-1,-1], [-1,1,1], [-1,1,-1], [-1,-1,1], [-1,-1,-1]]
-    
-Sometimes, a list of reflections needs to be reduced to a set of symmetry independent reflections only. That means it should not contain any two reflections that are symmetry equivalents according to the point group symmetry. To achieve this, ``PointGroup`` offers a method that returns the same :math:`hkl'` for all symmetry equivalents.
-
-.. testcode :: ExIndependentReflections
-
-    from mantid.geometry import PointGroup, PointGroupFactory
-
-    pg = PointGroupFactory.createPointGroup("m-3m")
-
-    hklList = [[1, 0, 0], [0, 1, 0], [-1, 0, 0],    # Equivalent to [1,0,0]
-               [1, 1, 1], [-1, 1, 1],               # Equivalent to [1,1,1]
-               [-3, 1, 1], [1, -3, 1], [-1, 1, 3]]  # Equivalent to [3,1,1]
-		 
-    independent = set()
-
-    for hkl in hklList:
-    	independent.add(pg.getReflectionFamily(hkl)) # getReflectionFamily returns the same hkl for all symmetry equivalents
-	
-    print "Number of independent reflections:", len(independent)
-    print "Reflections:", list(independent)
-    
-This example code produces the output below upon execution:
-
-.. testoutput:: ExIndependentReflections
-
-    Number of independent reflections: 3
-    Reflections: [[1,1,1], [1,0,0], [3,1,1]]
-
-Again, as in the case of ``SymmetryOperation``, the usage of ``PointGroup`` and the corresponding factory is very similar in C++.
-
-.. [ITA6] International Tables for Crystallography (2006). Vol. A, ch. 10.1, p. 762
-
-.. [#f1] In the case of the monoclinic Laue class :math:`2/m` it's a bit more complicated, because there are two conventions regarding the unique axis. According to current crystallographic standards, the :math:`b`-axis is used, but in some cases one may find the :math:`c`-axis for this purpose. To resolve this, both options are offered in Mantid. When using the symbol ``2/m``, the :math:`b`-axis convention is used, for :math:`c` one has to explicitly provide the symbol as ``112/m``.
-
-.. categories:: Concepts
\ No newline at end of file
diff --git a/Code/Mantid/docs/source/concepts/PropertiesFile.rst b/Code/Mantid/docs/source/concepts/PropertiesFile.rst
index 06ef5ec35579d7d58c5bd32d175dd92425dba05e..2f9aac4024b0e8baa1e432f63c163c052128e237 100644
--- a/Code/Mantid/docs/source/concepts/PropertiesFile.rst
+++ b/Code/Mantid/docs/source/concepts/PropertiesFile.rst
@@ -130,40 +130,40 @@ MantidPlot Properties
 Network Properties
 ******************
 
-+----------------------------------------+---------------------------------------------------+-----------------------+
-|Property                                |Description                                        |Example value          |
-+========================================+===================================================+=======================+
-|network.default.timeout                 |Defines the default timeout for all network        |30                     |
-|                                        |operations (in seconds).                           |                       |
-+----------------------------------------+---------------------------------------------------+-----------------------+
-|network.scriptrepo.timeout              |The timeout for network operations in the script   |5                      |
-|                                        |repository, this overrides the deafault timeout.   |                       |
-+----------------------------------------+---------------------------------------------------+-----------------------+
-|proxy.host                              | Allows the system proxy to be overridden, if not  | http://www.proxy.org  |
-|                                        | set mantid will use the system proxy              |                       |
-+----------------------------------------+---------------------------------------------------+-----------------------+
-|proxy.port                              | Must be set if proxy.host is set                  | 8080                  |
-+----------------------------------------+---------------------------------------------------+-----------------------+
-|proxy.httpsTargetUrl                    | A sample url used to determine the system proxy to| http://www.google.com |
-|                                        | use on windows.                                   |                       |
-+----------------------------------------+---------------------------------------------------+-----------------------+
++----------------------------------------+---------------------------------------------------+---------------------------------+
+|Property                                |Description                                        |Example value                    |
++========================================+===================================================+=================================+
+|network.default.timeout                 |Defines the default timeout for all network        |30                               |
+|                                        |operations (in seconds).                           |                                 |
++----------------------------------------+---------------------------------------------------+---------------------------------+
+|network.scriptrepo.timeout              |The timeout for network operations in the script   |5                                |
+|                                        |repository, this overrides the deafault timeout.   |                                 |
++----------------------------------------+---------------------------------------------------+---------------------------------+
+|proxy.host                              | Allows the system proxy to be overridden, if not  | :literal:`http://www.proxy.org` |
+|                                        | set mantid will use the system proxy              |                                 |
++----------------------------------------+---------------------------------------------------+---------------------------------+
+|proxy.port                              | Must be set if proxy.host is set                  | 8080                            |
++----------------------------------------+---------------------------------------------------+---------------------------------+
+|proxy.httpsTargetUrl                    | A sample url used to determine the system proxy to| :literal:`http://www.google.com`|
+|                                        | use on windows.                                   |                                 |
++----------------------------------------+---------------------------------------------------+---------------------------------+
 
 
 ScriptRepository Properties
 ***************************
 
-+-----------------------+-----------------------------------------------+----------------------------------------------------------------+
-|Property               |Description                                    |Example value                                                   |
-+=======================+===============================================+================================================================+
-|ScriptLocalRepository  |Directory where ScriptRepository is Installed. |c:\MantidInstall\MyScriptRepository                             |
-+-----------------------+-----------------------------------------------+----------------------------------------------------------------+
-|ScriptRepository       |Base URL for the remote script repository.     |http://download.mantidproject.org/scriptrepository/             |
-+-----------------------+-----------------------------------------------+----------------------------------------------------------------+
-|UploaderWebServer      |URL for uploading scripts.                     |http://upload.mantidproject.org/scriptrepository/payload/publish|
-+-----------------------+-----------------------------------------------+----------------------------------------------------------------+
-|ScriptRepositoryIgnore |CSV patterns for paths that should not be      |\*pyc;                                                          |
-|                       |listed at ScriptRepository.                    |                                                                |
-+-----------------------+-----------------------------------------------+----------------------------------------------------------------+
++-----------------------+-----------------------------------------------+----------------------------------------------------------------------------+
+|Property               |Description                                    |Example value                                                               |
++=======================+===============================================+============================================================================+
+|ScriptLocalRepository  |Directory where ScriptRepository is Installed. |:literal:`C:\\MantidInstall\\MyScriptRepository`                            |
++-----------------------+-----------------------------------------------+----------------------------------------------------------------------------+
+|ScriptRepository       |Base URL for the remote script repository.     |:literal:`http://download.mantidproject.org/scriptrepository/`              |
++-----------------------+-----------------------------------------------+----------------------------------------------------------------------------+
+|UploaderWebServer      |URL for uploading scripts.                     |:literal:`http://upload.mantidproject.org/scriptrepository/payload/publish` |
++-----------------------+-----------------------------------------------+----------------------------------------------------------------------------+
+|ScriptRepositoryIgnore |CSV patterns for paths that should not be      |:literal:`*pyc;`                                                            |
+|                       |listed at ScriptRepository.                    |                                                                            |
++-----------------------+-----------------------------------------------+----------------------------------------------------------------------------+
 
 
 Getting access to Mantid properties
diff --git a/Code/Mantid/docs/source/concepts/SymmetryGroups.rst b/Code/Mantid/docs/source/concepts/SymmetryGroups.rst
new file mode 100644
index 0000000000000000000000000000000000000000..07a8d428143694b2bbb6c4f13a608eea6cabd929
--- /dev/null
+++ b/Code/Mantid/docs/source/concepts/SymmetryGroups.rst
@@ -0,0 +1,272 @@
+.. _Symmetry groups:
+
+Symmetry groups
+===============
+
+This is an introduction to group theoretical concepts for symmetry in Mantid. It is the basis for further descriptions covering point groups and space groups.
+
+Introduction
+------------
+
+Symmetry in space of any dimensionality can be described by symmetry groups. This and the following guides cover symmetry in three dimensions, as it is most commonly used in crystallography and how it is integrated into Mantid. All code samples are given as Python code and can be executed directly in the program.
+
+Groups
+------
+
+A group :math:`(G, \cdot)` is defined as a set of elements :math:`G` with a binary operation :math:`\cdot` which combines two elements of :math:`G`. :math:`(G, \cdot)` is a group if the four group axioms are satisfied [Groups]_:
+
+  1. **Closure**: For all :math:`a, b` in :math:`G` the result of :math:`a \cdot b` is also in :math:`G`.
+  2. **Associativity**: For all :math:`a, b` in :math:`G`, :math:`(a \cdot b) \cdot c` is equal to :math:`a \cdot (b \cdot c)`.
+  3. **Identity element**: There exists an element :math:`e` in :math:`G` such that :math:`e \cdot a = a`.
+  4. **Inverse element**: For each :math:`a` in :math:`G` there exists an element :math:`b` in :math:`G` such that :math:`a \cdot b = e`.
+   
+There are many examples for groups, for example the group defined by the set of signed integer numbers and the addition operation. Any two integers added result again in an integer, integer addition is associative, there is an identity element (the number 0) and for each integer there is an inverse element (the number with the same magnitude, but opposite sign). For describing symmetry, groups are required that consist of a set of symmetry operations and a binary operation that combines them. The next section describes how symmetry operations can be represented and how to work with them in Mantid.
+
+Symmetry operations
+-------------------
+
+Theory
+~~~~~~
+
+As symmetry operations are used for the definition of space groups, the mathematics behind this are covered in depth in the International Tables for Crystallography A (ITA), namely part 11 [ITASymmetry]_. A symmetry operation describes the transformation of an object :math:`O` into its image :math:`O'`:
+
+.. math::
+    O' = S \cdot O
+    
+For a coordinate :math:`\mathbf{x}` in three dimensions, any transformation can be described using a transformation matrix :math:`\mathbf{W}` and a translation vector :math:`\mathbf{w}`. This leads to the following equation:
+
+.. math::
+    \mathbf{x}' = \mathbf{W} \cdot \mathbf{x} + \mathbf{w}
+    
+:math:`\mathbf{W}` is a :math:`3\times3`-matrix and for affine transformations, the determinant of the matrix is always equal to 1 or -1 (except for hexagonal coordinates, which are handled transparently in Mantid so this is not covered here).
+
+Coordinates :math:`x` are assumed to be fractional in terms of a unit cell, which defines the smallest unit of an infinite lattice that is repeated over and over. For this case, coordinates :math:`x` and :math:`x + 1`, :math:`x + 2`, :math:`-x`, :math:`-x - 1` and so forth are equivalent. That means that translation vectors can be limited to have it's elements on the interval :math:`[0, 1)` - this will be important later on.
+
+Of course it is also possible to transform vectors (such as reciprocal vectors :math:`\mathbf{h}` described by Miller indices h, k and l), in which case the translation does not apply and the matrix needs to be inverted and transposed:
+
+.. math::
+    \mathbf{h}' = {\mathbf{W}_i^{-1}}^T \cdot \mathbf{h}
+
+For the definition of the group :math:`(G, \cdot)` this means that :math:`G` is a set of matrix and vector pairs :math:`(\mathbf{W}_i, \mathbf{w}_i) = S_i`. All that's missing for completing the description of a symmetry group is the definition of the binary operation :math:`\cdot`:
+
+.. math::
+    S_3 = S_1 \cdot S_2 = \left(\mathbf{W}_1 \cdot \mathbf{W}_2, \left[\mathbf{W}_1 \cdot \mathbf{w}_2\right] + \mathbf{w}_1\right)
+    
+While matrix and vector pairs are very well suited for modelling symmetry operaitions in a computer language, they are not very convenient for human language. A very common notation is the "Jones-faithful" system, which is for example used in the symmetry operations section in the space group descriptions in ITA. It uses :math:`(x,y,z)` triplets to describe the rows of the matrix (:math:`x` meaning :math:`1, 0, 0` and so on) and the translation vector (for example :math:`x,y,z+1/2` for a translation of half a unit cell vector in :math:`c`-direction). The following table shows some more examples:
+
+.. table:: Examples for symmetry operations in Jones-faithful notation.
+
+    =============== ===================
+    Symbol          Symmetry operation
+    =============== ===================
+    ``x,y,z``       Identity
+    ``-x,-y,-z``    Inversion
+    ``-x,-y,z``     2-fold rotation around :math:`z`
+    ``x,y,-z``      Mirror plane perpendicular to :math:`z`
+    ``-x,-y,z+1/2`` :math:`2_1` screw axis along :math:`z`
+    =============== ===================
+    
+There are several advantages to this notation. First of all it's very concise and secondly it directly shows how a point :math:`x` behaves under the symmetry transformation. As such this notation was chosen for generation of symmetry operations in Mantid.
+
+Last but not least, each symmetry operation has a so called order :math:`k`, which describes how many times the operation has to be chained together to arrive at identity:
+
+.. math::
+    I = S^k = S \cdot S \cdot \dots \cdot S
+    
+The same is true for transforming coordinates as well. Applying a symmetry operation of order :math:`k` exactly :math:`k` times to a point :math:`x` will result in :math:`x` again, which is the definition of identity.
+
+Symmetry operations in Mantid
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Symmetry operations are implemented in Mantid following the scheme described above with matrix and vector pairs, it is written in C++ and resides in the `Geometry` library. How to use this code is described in the doxygen documentation and shall not be covered at this point. Instead this section describes how symmetry operations can be used in the Python environment of Mantid.
+
+As described above, the operations are represented using the Jones-faithful notation, so they can be created by a factory that parses these strings. It returns a `SymmetryOperation`-object which can be queried for certain characteristics. The most obvious one is the identifier string. It may differ from the one used to create the operation, because the strings are normalized internally so that a specific matrix and vector pair always has the same identifier.
+
+.. testcode :: ExSymmetryOperationFactory
+
+    from mantid.geometry import SymmetryOperationFactory
+    
+    # This time the identifier is already normalized
+    symOp = SymmetryOperationFactory.createSymOp("x,y,-z")
+    print symOp.getIdentifier()
+    
+    # This is an example for an identifier that changes
+    symOp = SymmetryOperationFactory.createSymOp("1/2+x,y,z")
+    print symOp.getIdentifier()
+    
+Executing the above code yields the following output, which shows how the operation identifier is modified in some cases:
+
+.. testoutput :: ExSymmetryOperationFactory
+
+    x,y,-z
+    x+1/2,y,z
+    
+For ease of use with multiple symmetry operations it's also possible to create multiple operations at once, using a semi-colon separated string of identifiers:
+
+.. testcode :: ExSymmetryOperationFactoryMultiple
+
+    from mantid.geometry import SymmetryOperationFactory
+
+    # Create a list of symmetry operations
+    symOps = SymmetryOperationFactory.createSymOps("x,y,-z; -x,-y,-z; z,x,y")
+    
+    print "Number of operations:", len(symOps)
+    print "Operations:"
+    
+    for op in symOps:
+	print op.getIdentifier()
+	
+This prints each identifier on a new line:
+
+.. testoutput :: ExSymmetryOperationFactoryMultiple
+
+    Number of operations: 3
+    Operations:
+    x,y,-z
+    -x,-y,-z
+    z,x,y
+    
+Symmetry operation objects can be used to transform coordinates or Miller indices, which are handled differently as detailed in the theory section above, so different methods exists for each of the two tasks.
+
+.. testcode :: ExSymmetryOperationPoint
+
+    from mantid.geometry import SymmetryOperationFactory
+    
+    symOp = SymmetryOperationFactory.createSymOp("x-y,x,z")
+    
+    coordinates = [0.3, 0.4, 0.5]
+    coordinatesPrime = symOp.transformCoordinates(coordinates)
+    
+    print "Transformed coordinates:", coordinatesPrime
+    
+This script generates a symmetry operation that is used in hexagonal coordinate systems and uses it to transform the given coordinates:
+
+.. testoutput :: ExSymmetryOperationPoint
+
+    Transformed coordinates: [-0.1,0.3,0.5]
+
+As transforming HKLs requires slightly different math, there is a special method for this as well:
+
+.. testcode :: ExSymmetryOperationHKL
+
+    from mantid.geometry import SymmetryOperationFactory
+    
+    symOp = SymmetryOperationFactory.createSymOp("x,y,-z")
+    
+    hkl = [1, -1, 3]
+    hklPrime = symOp.transformHKL(hkl)
+    
+    print "Transformed hkl:", hklPrime
+    
+The above code will print the transformed Miller index triplet:
+
+.. testoutput :: ExSymmetryOperationHKL
+
+    Transformed hkl: [1,-1,-3]
+    
+It's also possible to query the order of a symmetry operation. The next example generates a fourfold rotation around the :math:`z`-axis and prints some information about it.
+
+.. testcode :: ExSymmetryOperationOrder
+
+    from mantid.geometry import SymmetryOperationFactory
+
+    symOp = SymmetryOperationFactory.createSymOp("-y,x,z")
+    
+    k = symOp.getOrder()
+    print "Order of the symmetry operation:", k
+
+    x = [0.3, 0.4, 0.5]
+    print "Original point: ["+(','.join(" %.1f"%c for c in x)).strip()+"]"
+    for i in range(k):
+        x = symOp.transformCoordinates(x)
+        print "After", i + 1, "application(s):", x
+      
+.. testoutput :: ExSymmetryOperationOrder
+
+    Order of the symmetry operation: 4
+    Original point: [0.3, 0.4, 0.5]
+    After 1 application(s): [-0.4,0.3,0.5]
+    After 2 application(s): [-0.3,-0.4,0.5]
+    After 3 application(s): [0.4,-0.3,0.5]
+    After 4 application(s): [0.3,0.4,0.5]
+    
+Symmetry elements
+~~~~~~~~~~~~~~~~~
+
+Sometimes it's easier to describe symmetry in terms of the symmetry element that is associated to an operation. Several notation systems exist for these elements, but Hermann-Mauguin symbols are most commonly used in crystallography. Information on how to read these symbols can be found in ITA. Except identity, inversions and translations, all symmetry elements have a characteristic axis. In case of mirror and glide planes, this axis is perpendicular to the plane.
+
+Section 11.2 in the same book describes how to derive symmetry elements from matrix and vector pairs. The algorithms from that text are implemented in Mantid as well, so after a symmetry operation has been created using the factory, another factory can be used to generate the symmetry element corresponding to the operation. The resulting object can be queried for its Hermann-Mauguin symbol and its axis. For identity, inversion and translation this returns ``[0, 0, 0]``.
+
+.. testcode :: ExSymmetryElement
+
+    from mantid.geometry import SymmetryOperationFactory, SymmetryElementFactory
+
+    symOp = SymmetryOperationFactory.createSymOp("x,y,-z")
+    element = SymmetryElementFactory.createSymElement(symOp)
+
+    print "The element corresponding to 'x,y,-z' has the following symbol:", element.getHMSymbol()
+    print "The mirror plane is perpendicular to:", element.getAxis()
+    
+In this case, it's a mirror plane perpendicular to the :math:`z`-axis:
+    
+.. testoutput:: ExSymmetryElement
+
+    The element corresponding to 'x,y,-z' has the following symbol: m
+    The mirror plane is perpendicular to: [0,0,1]
+    
+Symmetry groups
+---------------
+
+In the previous section, symmetry operations and a binary operation combining them were introduced, which is finally sufficient to define symmetry groups. The most simple group possible contains only one element, the identity:
+
+.. math::
+    G = \left\{1\right\}
+    
+This group fulfills all four group axioms. The identity matrix multiplied with itself is again identity, so the group is closed. Associativity holds as well, since it does not matter in which order multiple identical operations are performed. Since the only element of the group is the identity, the third axiom is fulfilled as well. So is the fourth, since the inverse of the identity is again identity. This group exists as the point group :math:`1` and describes objects that do not show any symmetry except identity.
+
+As more operations are added to a group, it can be useful to display the group in terms of a group table, which makes it easy to check the group axioms. The following example group contains the symmetry operations :math:`1`, :math:`\bar{1}`, :math:`2` and :math:`m`, the latter two being characterized by the same axis. The cells of the group tables show the result of the binary operation combining the symmetry operations in the header row and header column:
+
+.. list-table:: Group table example
+    :header-rows: 1
+    :stub-columns: 1
+    
+    * - 
+      - :math:`1`
+      - :math:`\bar{1}`
+      - :math:`2`
+      - :math:`m`
+    * - :math:`1`
+      - :math:`1`
+      - :math:`\bar{1}`
+      - :math:`2`
+      - :math:`m`
+    * - :math:`\bar{1}`
+      - :math:`\bar{1}`
+      - :math:`1`
+      - :math:`m`
+      - :math:`2`
+    * - :math:`2`
+      - :math:`2`
+      - :math:`m`
+      - :math:`1`
+      - :math:`\bar{1}`
+    * - :math:`m`
+      - :math:`m`
+      - :math:`2`
+      - :math:`\bar{1}`
+      - :math:`1`
+      
+Combining the symmetry operations does not result into any new operations, so the group is closed. Each element has an inverse (in this case, each element is its own inverse). :math:` and an identity element exists (all elements in the first row are the same as in the header row).
+
+Some groups are so called cyclic groups, all elements of the group can be expressed as powers of one symmetry operation (which are explained above) from 0 to :math:`k-1`, where `k` is the order of the operation. The group with elements :math:`1` and :math:`2` is an example for such a cyclic group, it can be expressed as :math:`2^0 = 1` and :math:`2^1 = 2`.
+
+Just like in the case of symmetry operations, it's also possible to define a binary operation that combines two groups. For this, each symmetry operation of the first group is multiplied with each symmetry operation of the second group. If the resulting new set of operations fulfills the group axioms, the product of the two groups is again a group.
+
+These general group concepts are available in the C++ library of Mantid and are described in the API documentation (`Mantid::Geometry::SymmetryOperation <http://doxygen.mantidproject.org/nightly/d4/d82/classMantid_1_1Geometry_1_1SymmetryOperation.html>`_, `Mantid::Geometry::SymmetryElement <http://doxygen.mantidproject.org/nightly/df/d22/classMantid_1_1Geometry_1_1SymmetryElement.html>`_, `Mantid::Geometry::Group <http://doxygen.mantidproject.org/nightly/d3/d80/classMantid_1_1Geometry_1_1Group.html>`_). The most important specializations of symmetry groups implemented in Mantid are point- and space groups. They are explained in an additional :ref:`document <Point and space groups>`.
+
+.. [Groups] `Wikipedia article on groups <http://en.wikipedia.org/wiki/Group_%28mathematics%29#Definition>`_. Can be found in different formulations in various places such as `Wolfram MathWorld <http://mathworld.wolfram.com/Group.html>`_.
+
+.. [ITASymmetry] International Tables for Crystallography (2006). Vol. A, part 11, p. 810 (chapters `11.1 <http://it.iucr.org/Ab/ch11o1v0001/>`_ and `11.2 <http://it.iucr.org/Ab/ch11o2v0001/>`_).
+
+
+.. categories:: Concepts
diff --git a/Code/Mantid/docs/source/diagrams/DetectorDiagnostic-v1_wkflw.dot b/Code/Mantid/docs/source/diagrams/DetectorDiagnostic-v1_wkflw.dot
new file mode 100644
index 0000000000000000000000000000000000000000..1db23fe93729c7c0db99c79f7eef27fa7af776eb
--- /dev/null
+++ b/Code/Mantid/docs/source/diagrams/DetectorDiagnostic-v1_wkflw.dot
@@ -0,0 +1,65 @@
+digraph ReflectometryReductionOne {
+  label = "ReflectometryReductionOne Flowchart"
+  $global_style
+
+  subgraph params {
+    $param_style
+    inputWorkspace     [label="InputWorkspace"]
+    hardMaskWorkspace  [label="HardMaskWorkspace"]
+    outputWorkspace    [label="OutputWorkspace"]
+    detVanCompare      [label="DetVanCompare"]
+    sampleTotWorkspace [label="SampleTotalCountsWorkspace"]
+    sampleBkgWorkspace [label="SampleBackgroundWorkspace"]
+    sampleWorkspace    [label="SampleWorkspace"]
+  }
+
+  subgraph decisions {
+    $decision_style
+    checkHardMask   [label="HardMaskWorkspace?"]
+    checkDetVanComp [label="DetVanCompare?"]
+    checkSampleTot  [label="SampleTotalCountsWorkspace?"]
+    checkSampleBkg  [label="SampleBackgroundWorkspace?"]
+    checkSample     [label="SampleWorkspace?"]
+  }
+
+  subgraph algorithms {
+    $algorithm_style
+    useHardMask     [label="MaskDetectors"]
+    detEfficVar     [label="DetectorEfficiencyVariation"]
+	findDetsOutLims [label="FindDetectorsOutsideLimits"]
+	medianDetTest   [label="MedianDetectorTest"]
+	createPSDBMask  [label="CreatePSDBleedMask"]
+	extractMask     [label="ExtractMask"]
+  }
+
+  subgraph processes {
+    $process_style
+    doDetVanTest2I  [label="Do Detector\n Vanadium Tests\n on Input workspace"]
+	doDetVanTest2DV [label="Do Detector\n Vanadium Tests\n on DetVanCompare"]
+  }
+
+  inputWorkspace     -> checkHardMask
+  hardMaskWorkspace  -> checkHardMask
+  checkHardMask      -> useHardMask      [label="Yes"]
+  checkHardMask      -> doDetVanTest2I   [label="No"]
+  useHardMask        -> doDetVanTest2I
+  doDetVanTest2I     -> checkDetVanComp
+  detVanCompare      -> checkDetVanComp
+  checkDetVanComp    -> doDetVanTest2DV  [label="Yes"]
+  checkDetVanComp    -> checkSampleTot   [label="No"]
+  doDetVanTest2DV    -> detEfficVar
+  detEfficVar        -> checkSampleTot
+  sampleTotWorkspace -> checkSampleTot
+  checkSampleTot     -> findDetsOutLims  [label="Yes"]
+  checkSampleTot     -> checkSampleBkg   [label="No"]
+  sampleBkgWorkspace -> checkSampleBkg
+  findDetsOutLims    -> checkSampleBkg
+  checkSampleBkg     -> medianDetTest    [label="Yes"]
+  checkSampleBkg     -> checkSample      [label="No"]
+  medianDetTest      -> checkSample
+  sampleWorkspace    -> checkSample
+  checkSample        -> createPSDBMask  [label="Yes"]
+  checkSample        -> extractMask     [label="No"]   
+  createPSDBMask     -> extractMask
+  extractMask        -> outputWorkspace
+}
diff --git a/Code/Mantid/docs/source/diagrams/StepScanWorkflow.xml b/Code/Mantid/docs/source/diagrams/StepScanWorkflow.xml
new file mode 100644
index 0000000000000000000000000000000000000000..e8ed934229b79b7af525a5f45e0c9102fb11f66d
--- /dev/null
+++ b/Code/Mantid/docs/source/diagrams/StepScanWorkflow.xml
@@ -0,0 +1 @@
+<mxfile userAgent="Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C; .NET4.0E)" type="device"><diagram>3Zldb9o8FMc/DZcPAhzeLtf0ZZNWrVq1lV09shITrDoxcgyFffrayTGJ43RNm4BKuUDk2HGO//75+JzQQ368uxF4vbrlIWG90SDc9dBlbzSao5n61oZ9bvBm49wQCRrmpmFhuKd/CRgHYN3QkKRWR8k5k3RtGwOeJCSQlm3Jmf2INY7M8IXhPsDMtT7QUK5y62w0KexfCY1W5jHDyTxvSeXejBGSJd4w+V9mUm26OcZmrGxW6EoJJjhXw+hf8c4nTItmBMmnfv1C68FJQRJw5N83gBNbzDbg47dkvZHK9MDFY7rGAXFmkUrBHw8iKJcv0hVe68Z4F+mF7i8ZfwpWWMh+KtX3/0PVZ0kZ8znjIhsEXauP77vuwgy2REgCnGQmcP+G8JhIsVddoBUNABqAaAojPBWLNBwDMKvSAk1heTCwEh1GLuRSP0CxevWQo57PeNJOsbXgAUmVU1XFfF9r1oViwIRRTLHqSmb6WJKBrY1kQ9jzJc0cuUgSfhGCP6mrgOE0pYFWzNLQU5YXpUj5Rihuy4CT0NrdrjaCMCzp1t7sdROFW+84VU8tNJ29oKkZQu2DiEi4qyLXwY1GCpqVKSl4i9PHSyJVjOMiPTP6EDohfQd329LXBD2IDqdGD6GKUB2i5x4XGr1zOSrM0WCE8mrI82rIm3RBnntWNCNPTVfsF8o0MBd/9EV/PJ4awx0RVDlEtF66V1X1RnESuuWw2JHm5ASbBx+BYNi65SObJxqhXwmVHz922rmOZ2gtE2yy4zLBXgfJjnl2C4L7Y4vhZvw2C7YGGYtfuPUz8QvlRmkRfuIkIpreDx5953b09ZCncHDoHRwr/k7fRW8j9GBNPjt6buZ+TZnatRf7xe/MdvTg6cBWszaNg+fY0/HodOETxugm9axw9TqjcJ/FaLag3SNZSfDH1cS9OyRNplvS9H4TX22VEunF/juPzoHL0RRSQ9BrUpOWqlcYLpWHWNnqFUanFdGbsYSYUsYyX9SzxtItk35spHqtdsJCqV2oHNpITs3ZXQ6UqAbJeRdEtq+U3pVn1r8per3Kr0k8cwDOGmG3TlrENPng3M5hDY0+ZoQStlOIOGVqURevgt3qaBHj3ZkJZoB6RTBTdrYSzK1kGifkb96jGc3H34/VQqXD/diifHmzWhnKZxS91GXxj1nevfi/EV09Aw==</diagram></mxfile>
\ No newline at end of file
diff --git a/Code/Mantid/docs/source/fitfunctions/DynamicKuboToyabe.rst b/Code/Mantid/docs/source/fitfunctions/DynamicKuboToyabe.rst
index 5dc384cf2170281f06e7814b78f2151b808e48d9..024b20741acc088bb279b9fa262236276a03add6 100644
--- a/Code/Mantid/docs/source/fitfunctions/DynamicKuboToyabe.rst
+++ b/Code/Mantid/docs/source/fitfunctions/DynamicKuboToyabe.rst
@@ -24,7 +24,8 @@ where :math:`g_z\left(t\right)` is the static KT function, and :math:`\nu` the m
 
 .. math:: g_z\left(t\right) = \mbox{A} \Bigg[ 1 - 2\frac{\Delta^2}{\omega_0^2}\Big(1-cos(\omega_0 t)e^{-\frac{1}{2}\Delta^2 t^2}\Big) + 2\frac{\Delta^4}{\omega_0^4}\omega_0\int_0^\tau \sin(\omega_0\tau)e^{-\frac{1}{2}\Delta^2\tau^2}d\tau \Bigg]
 
-Note: The static function in longitudinal field will be implemented soon. In the meantime, please fix the external field :math:`B_0` (F parameter) to 0.
+DynamicKuboToyabe function has one attribute (non-fitting parameter), 'BinWidth', that sets the width of the step size between points for numerical integration. Note that 
+small values will lead to long calculation times, while large values will produce less accurate results. The default value is set to 0.05, and it is allowed to vary in the range [0.001,0.1].
 
 .. attributes::
 
diff --git a/Code/Mantid/docs/source/fitfunctions/LatticeFunction.rst b/Code/Mantid/docs/source/fitfunctions/LatticeFunction.rst
new file mode 100644
index 0000000000000000000000000000000000000000..1ee418b638b3eccbabf6140b5f04de034d5bbf58
--- /dev/null
+++ b/Code/Mantid/docs/source/fitfunctions/LatticeFunction.rst
@@ -0,0 +1,81 @@
+.. _func-LatticeFunction:
+
+===============
+LatticeFunction
+===============
+
+.. index:: LatticeFunction
+
+Description
+-----------
+
+After a list of Bragg reflections has been indexed, it is often necessary to refine the unit cell parameters that have
+been used to assign indices. LatticeFunction can be used to achieve that task with :ref:`algm-Fit`. The function can
+work with a PeaksWorkspace or with a TableWorkspace that contains two columns named `HKL` and `d` (see
+:ref:`algm-PawleyFit` for specification of the table).
+
+After setting the `CrystalSystem` attribute to one of the seven crystal systems, the function exposes the
+corresponding lattice parameters, as well as a `ZeroShift`. In most cases it's recommended to fix this additional
+parameter as this is often taken care of in earlier steps of the data reduction.
+
+Usage
+-----
+
+.. include:: ../usagedata-note.txt
+
+The following script demonstrates how the function can be used. The algorithm :ref:`algm-PoldiCreatePeaksFromCell` is
+used to generate Bragg reflections that are expected for the crystal structure of Silicon.
+
+.. testcode:: ExSiliconTheoretical
+
+    import numpy as np
+
+    # Create Silicon peaks for indexing
+    peaks_Si = PoldiCreatePeaksFromCell(
+                SpaceGroup="F d -3 m",
+                a=5.4311946,
+                Atoms="Si 0 0 0",
+                LatticeSpacingMin=0.7)
+
+    # Fit a cubic cell, starting parameter is 5
+    Fit(Function="name=LatticeFunction,CrystalSystem=Cubic,a=5",
+        InputWorkspace=peaks_Si,
+        Ties="ZeroShift=0.0",
+        CreateOutput=True,
+        Output="Si",
+        CostFunction="Unweighted least squares")
+
+    # Print the refined lattice parameter with error estimate
+    parameters = AnalysisDataService.retrieve("Si_Parameters")
+
+    a_true = 5.4311946
+    a = np.round(parameters.cell(0, 1), 7)
+    a_err = np.round(parameters.cell(0, 2), 7)
+
+    print "Refined lattice parameter: a =", a, "+/-", a_err
+    print "Difference from expected value: a_observed - a_expected =", np.round(a - a_true, 7)
+    print "Is this difference within the standard deviation?", "Yes" if np.fabs(a - a_true) < a_err else "No"
+
+Executing the script produces some output with information about the fit:
+
+.. testoutput:: ExSiliconTheoretical
+
+    Refined lattice parameter: a = 5.4311944 +/- 3e-07
+    Difference from expected value: a_observed - a_expected = -2e-07
+    Is this difference within the standard deviation? Yes
+
+In addition there is also an output workspace, which contains information about the peaks used for the fit and how
+well the peak positions calculated from the fitted parameters match the observed positions.
+
+.. testcleanup:: ExSiliconTheoretical
+
+    DeleteWorkspace("peaks_Si")
+    DeleteWorkspace("Si_Parameters")
+    DeleteWorkspace("Si_Workspace")
+    DeleteWorkspace("Si_NormalisedCovarianceMatrix")
+
+.. attributes::
+
+.. properties::
+
+.. categories::
diff --git a/Code/Mantid/docs/source/fitfunctions/Voigt.rst b/Code/Mantid/docs/source/fitfunctions/Voigt.rst
index 88d54c392c88bd3faeb78a1d6b65385fbb1c8c8c..7d71da02945dab3ef27745558838d33b3c0d3c05 100644
--- a/Code/Mantid/docs/source/fitfunctions/Voigt.rst
+++ b/Code/Mantid/docs/source/fitfunctions/Voigt.rst
@@ -30,7 +30,8 @@ described in
    photoemission lineshape analysis, Journal of Electron Spectroscopy
    and Related Phenomena, Volume 69, Issue 2, 29 September 1994, Pages
    125-132, ISSN 0368-2048,
-   10.1016/0368-2048(94)02189-7.(http://www.sciencedirect.com/science/article/pii/0368204894021897)
+   10.1016/0368-2048(94)02189-7.
+   `(Article) <http://www.sciencedirect.com/science/article/pii/0368204894021897>`__
 
 The approximation uses a combination of 4 Lorentzians in two variables
 to generate good approximation to the true function.
diff --git a/Code/Mantid/docs/source/images/IntegrateMD.png b/Code/Mantid/docs/source/images/IntegrateMD.png
new file mode 100644
index 0000000000000000000000000000000000000000..c097c14966d37d379c2e31733627143f7b973305
Binary files /dev/null and b/Code/Mantid/docs/source/images/IntegrateMD.png differ
diff --git a/Code/Mantid/docs/source/images/PreIntegrateMD.png b/Code/Mantid/docs/source/images/PreIntegrateMD.png
new file mode 100644
index 0000000000000000000000000000000000000000..a0fc2059a49299ca24fdf094e2448cd0895f05c8
Binary files /dev/null and b/Code/Mantid/docs/source/images/PreIntegrateMD.png differ
diff --git a/Code/Mantid/docs/source/images/SpectrumViewer.jpg b/Code/Mantid/docs/source/images/SpectrumViewer.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..371583c44b32e51ddeeed608df934e156fcd0ecd
Binary files /dev/null and b/Code/Mantid/docs/source/images/SpectrumViewer.jpg differ
diff --git a/Code/Mantid/docs/source/images/StepScanWorkflow.png b/Code/Mantid/docs/source/images/StepScanWorkflow.png
new file mode 100644
index 0000000000000000000000000000000000000000..74ff19aedd8e25a2931da978d8c16e1e89be4b54
Binary files /dev/null and b/Code/Mantid/docs/source/images/StepScanWorkflow.png differ
diff --git a/Code/Mantid/docs/source/interfaces/HFIRPowderReduction.rst b/Code/Mantid/docs/source/interfaces/HFIRPowderReduction.rst
new file mode 100644
index 0000000000000000000000000000000000000000..f72c3d66bfae400565365ff7c4d9845025f6b7a7
--- /dev/null
+++ b/Code/Mantid/docs/source/interfaces/HFIRPowderReduction.rst
@@ -0,0 +1,148 @@
+HFIR Powder Reduction Interface
+===============================
+
+.. contents:: Table of Contents
+  :local:
+  
+Overview
+--------
+
+HFIR powder reduction interface (HFIR-PDR-GUI) is a GUI to download, view and reduce data from HFIR's powder diffractometers
+in SPICE format. 
+
+
+Use cases for tabs
+------------------
+
+  1. **Raw Detectors**: Visualize the reading of detectors directly coming out of the raw data
+    - Plot N lines for N Pts.;
+    - Highlight (make it thicker) the Pt that is interested;
+    - New from Mantid:  *ReadRawSpiceSignal(Pts)*;
+  2. **Individual Detector**: Visual the readings of one detector across an experiment
+    - Plot the counts of any individual detector;
+    - Able to change the X-axis from 2theta to arbitrary sample environment log;
+    - New from Mantid: *ReadRawSpiceSignal(DetectorID, XLabel)*;
+  3. **Normalized**: Reduce one scan each time
+    - Plot the reduced data
+    - Automatically locate detector efficiency file
+    - New from Mantid: *ConvertCWPDMDToSpectra(ExcludedDetectors=[])*
+    - New from Mantid: *ConvertSpiceDataToRealSpace(DetectorEfficiencyTable)*
+  4. **Multiple Scans**: Reduce a set of scans
+    - Reduce a set of scans and plot in 2D/water-fall mode;
+    - Able to merge all the scans;
+    - New from Mantid: *ConvertCWPDMDToSpectra(ExcludedDetectors=[])*
+  5. **Vanadium**: strip vanadium peaks
+    - Strip vanadium peak with unit 'Degrees' because of the binning (range and step size) must be respected;
+    - Peaks' position should be calculated and indicated auotmatically;
+    - *Mantid::StripPeaks()* will be called instread of *StripVadadiumPeaks()* because
+      the later one only works in d-spacing;
+  6. **Advanced Setup**
+    - URL for raw data files; 
+
+
+Workflow for *Normalization*
+============================
+
+Here is a typical use case for reduce data via tab *Noramlization*
+
+ 1. User specifies *Exp No* and *Scan No* and push button *Load*;
+  - HFIR-PDR-GUI loads SPICE data according to experiment number and scan number;
+  - HFIR-PDR-GUI checks whether vanadium correction file, i.e., detector efficiency file exists on server;
+  - HFIR-PDR-GUI checks whether excluded detectors file exists on server;
+  - HFIR-PDR-GUI checks log **m1** for wavelength and set to *Wavelength* ;
+ 2. User may specify detector efficient file;
+ 3. User specifies *Bin Size*; 
+ 4. User pushes button *2Theta*, *dSpacng*, or *Q*;
+  - HFIR-PDF-GUI reduce data in unit of *2theta* by taking accounting of 
+    - Detector efficiency;
+    - Excluded detectors; 
+ 5. HFIR-PDR-GUI plots the reduced data;
+ 6. User may rebin by different binning parameters or unit;
+ 7. User may push button *Next Scan* or *Prev Scan* to load and reduce other scans with current setup;
+ 8. User may save the result by pushing button *Save*;
+
+
+Workflow for *Raw Detectors*
+============================
+
+Here is a typical use case for reduce data via tab *Noramlization*
+
+ 1. User specifies *Exp No* and *Scan No* and push button *Load*;
+  - HFIR-PDR-GUI loads SPICE data according to experiment number and scan number;
+  - HFIR-PDR-GUI checks whether vanadium correction file, i.e., detector efficiency file exists on server;
+  - HFIR-PDR-GUI checks whether excluded detectors file exists on server;
+  - HFIR-PDR-GUI checks log **m1** for wavelength and set to *Wavelength* ;
+ 2. User specifies a *Pt.* number and push button *Plot Raw Detector*;
+  - HFIR-PDF-GUI plots the raw detector counts normalized by monitor count;
+ 3. User may push button *Previous Pt.* or *Next Pt.* for the other experiment points;
+
+
+
+Workflow for *Multiple Scans*
+=======================================
+
+It might be confusing to use the functionalities in tab *Multiple Scans*. 
+Here is the suggested workflow to reduce multiple scans and possibly merge them.
+
+ 1. Set up *Exp No* and range of scan numbers;
+ 2. Push button *Load All* to load and reduce all runs specified in previous step to single-spectrum diffraction pattern;
+ 3. Plot all reduced scans in default;
+ 4. Optinally plot all data in 2D fill plot;
+ 5. User can delete some scans from the reduced scans via GUI or input text edit (not implemented yet);
+ 6. Push button *Merge* to merge the scans;
+ 7. Push button *Save All* to save all individual scans to files;
+ 8. Push button *Save Merged* to save the merged scans to one file; 
+
+
+HB2A Data Reduction
+-------------------
+
+Raw experimental data are to be corrected by (1) detector efficiency, (2) vanadium spectrum and etc. 
+Experiments are done with neutrons with various wavelengthes.  
+There information can be retrieved from HB2A's data repository accessible from internet. 
+
+Experiment setup and sample log
+===============================
+
+ 1. **Wavelength**: There are three settings for neutron wavelength, referenced by sample log *m1*. 
+  - Ge 113: :math:`\lambda = 2.41 \AA`, m1 = 9.45  (The **error** can be 0.05, such that in Exp 231 scan0001, m1=9.5)
+  - Ge 115: :math:`\lambda = 1.54 \AA`, m1 = 0
+  - Ge 117  :math:`\lambda = 1.12 \AA`, No used
+
+ 2. **Collimator translation**: There are two status for collimator, which is specified by sample log *colltrans*
+  - *IN*:  colltrans = 0
+  - *OUT*: colltrans = +/-80
+
+
+Raw data correction files
+=========================
+
+ 1. **Detector efficiency**: 
+  - File name: *HB2A_exp0IJK__GE_abc_XY_vcorr.txt* where
+    - IJK is the experiment number
+    - abc is the GE set up.  It can be 113, 115 or 117
+    - XY is either IN or OUT. 
+    - Exmaple: *HB2A_exp0400__Ge_113_IN_vcorr.txt*
+  - Web address: *http://neutron.ornl.gov/user_data/hb2a/exp400/Datafiles/HB2A_exp0IJK__Ge_abc_IN_vcorr.txt*
+    - IJK is the experiment number
+    - abc is the GE set up.  It can be 113, 115 or 117
+    - XY is either IN or OUT. 
+    - Exmaple: *http://neutron.ornl.gov/user_data/hb2a/exp400/Datafiles/HB2A_exp0400__Ge_113_IN_vcorr.txt*
+
+ 2. **Excluded detectors**:  Some detectors might be exluded from the experiment for some reason.  It is recorded in some excluded detectors' file.
+  - File name: *HB2A_exp0IJK__exclude_detectors.txt*
+   - IJK is the epxeriment number
+   - Exmaple: *HB2A_exp0400__exclude_detectors.txt*
+  - Web address: *http://neutron.ornl.gov/user_data/hb2a/expIJK/Datafiles/HB2A_exp0IJK__exclude_detectors.txt*
+   - IJK is the experiment number
+   - Example: *http://neutron.ornl.gov/user_data/hb2a/exp400/Datafiles/HB2A_exp0400__exclude_detectors.txt*
+
+ 3. Detector gaps: The 2-theta gap (in unit degrees) can be changed among cycles. 
+   - Location example: *http://neutron.ornl.gov/user_data/hb2a/exp400/Datafiles/HB2A_exp0400__gaps.txt*
+
+
+Limitation
+----------
+
+- HFIR powder reduction GUI supports for instrument HB2A only in release 3.4.0;
+
diff --git a/Code/Mantid/docs/source/interfaces/Indirect_DataAnalysis.rst b/Code/Mantid/docs/source/interfaces/Indirect_DataAnalysis.rst
index 7af6477eb91fb1c91f93db562be59e543e665a83..0843e4d911962523b6a69969f5586d48a64b42b8 100644
--- a/Code/Mantid/docs/source/interfaces/Indirect_DataAnalysis.rst
+++ b/Code/Mantid/docs/source/interfaces/Indirect_DataAnalysis.rst
@@ -59,13 +59,13 @@ Input File
   Specify a range of input files that are either reduced (*_red.nxs*) or
   :math:`S(Q, \omega)`.
 
-Range One
+Integration Range
   The energy range over which to integrate the values.
 
-Use Two Ranges
+Background Subtraction
   If checked a background will be calculated and subtracted from the raw data.
 
-Range Two
+Background Range
   The energy range over which a background is calculated which is subtracted from
   the raw data.
 
diff --git a/Code/Mantid/docs/source/interfaces/Indirect_DataReduction.rst b/Code/Mantid/docs/source/interfaces/Indirect_DataReduction.rst
index 7a313dc3c1d46f6768892fe1e730f1560f866114..19465b5ec8131ee79b78a7591dfd313c95f7a819 100644
--- a/Code/Mantid/docs/source/interfaces/Indirect_DataReduction.rst
+++ b/Code/Mantid/docs/source/interfaces/Indirect_DataReduction.rst
@@ -294,6 +294,10 @@ Use Calibration
   Allows you to select either a calibrtion file or workspace to apply to the raw
   files.
 
+Preview Spectrum
+  Allows selection of the spectrum to be shown in the preview plot to the right
+  of the Time Slice section.
+
 Spectra Min & Spectra Max
   Allows selection of the range of detectors you are interested in, this is
   automatically set based on the instrument and analyser bank that are currently
diff --git a/Code/Mantid/docs/source/interfaces/SpectrumViewer.rst b/Code/Mantid/docs/source/interfaces/SpectrumViewer.rst
new file mode 100644
index 0000000000000000000000000000000000000000..58c6a8cd181bc2a43cc85fdbf51d936a4a35efeb
--- /dev/null
+++ b/Code/Mantid/docs/source/interfaces/SpectrumViewer.rst
@@ -0,0 +1,144 @@
+SpectrumView
+============
+
+.. contents:: Table of Contents
+  :local:
+
+Overview
+--------
+
+The 2.2 release of MantidPlot includes the "SpectrumView" data viewer, a viewer
+that quickly displays a large collection of spectra as an image.  The viewer can
+be started from the right-click menu of a matrix workspace by selecting ''Show
+Spectrum Viewer''.  Each row of the image represents one spectrum.
+
+If the user points at a location on the image the data from that spectrum are
+displayed on a graph across the bottom of the image, and the data from the
+different spectra for that column are displayed on a graph at the left side of
+the image.  Basic information about that point on the image is shown in the
+Image Info table. Similarly information about a position pointed at by the user
+in a graph is displayed in the table associated
+with that graph.
+
+Example
+-------
+
+For example, the figure shows the spectra from slightly more than three LPSDs on
+the ARCS instrument at the SNS.  The four horizontal dark lines across the image
+are due to there being no data from pixels at the ends of the LPSDs.The image
+quickly shows several interesting aspects of the data, includingpowder lines,
+single crystal peaks and a dead-time of the LPSDs for
+approximately 200 micro-seconds following particularly strong SCD peaks.
+
+.. figure:: /images/SpectrumViewer.jpg
+
+Interactive Rebinning
+---------------------
+
+The spectra displayed are initially binned in 2000 uniform steps.
+They can be quickly rebinned for the viewer by specifying new values for X Min,
+X Max and a new Step size.
+
+If the step size is positive, it specifies the size of the uniform bin width to
+use across the selected X range. If the step size is negative, its absolute
+value specifies the fractional increase for each bin boundary in a "log" scale.
+The effect of rebinning with a large number of small bins is most useful in
+combination with the horizontal scroll bar, described below.
+
+Scrolling
+---------
+
+If there are more spectra than can be displayed at one time, the image can
+be scrolled up and down using the vertical scroll bar at the right side of the
+image.  In this way, all spectra from an instrument with hundreds of
+thousands of detector pixels can be examined quickly.  The View menu includes
+a control to turn off the vertical scroll bar.  If the vertical scroll bar
+is turned off, then the number of spectra displayed is limited to the number of
+rows in the displayed image.  For example, if there are 500 rows in the
+image, but there are 5,000 spectra to display, then the image will be formed
+by using every 10th spectrum.  While this can be useful in some cases, this
+subsampling of the available spectra can also miss important features and
+can suffer from various "aliasing" effects.  For this reason the vertical
+scroll bar is turned on by default.
+
+The view menu also has a control to turn on a horizontal scroll bar to
+scroll the image left and right.  This will only be useful when the spectra
+are binned using more bins than the number of image columns.  In this case,
+the horizontal scroll bar will allow scrolling the image and associated
+graph left and right to examine other portions of the spectra.  If the
+horizontal scroll bar is turned off, and the binning controls specify more
+bins than can be displayed, the binning is adjusted to match the number
+of displayable columns before the image is created.
+
+Information Readout
+-------------------
+
+The user can use the left mouse button to point at features on the image
+or graphs.  This will initiate a full size crosshair cursor for comparing
+features and will show information about the selected point in the table
+associated with the image or graph in use.  The information is for the
+selected spectrum and X location.  The "Value" shown is the value of
+the spectrum in the selected bin, using the current binning.
+
+Intensity to Color Mapping
+--------------------------
+
+A pseudo-log intensity scale is used to help see lower intensity features
+in the same image as high intensity peaks.  The relative intensity of low
+intensity features to high intensity features is controlled by the intensity
+slider.
+
+When the slider is fully to the left, the mapping from
+data value to color index is linear.  As the slider is moved to the right
+low intensity features are increasingly emphasized, relative to the
+maximum intensity in the displayed image.
+
+The selected color scale is always fully used.  If the image is scrolled
+to display a different portion of the image, the mapping is adjusted so
+that the largest positive value present in the image is mapped to the
+largest color index.
+
+The color scale in use is displayed in a color bar on the right side of
+the viewer.  This color scale is "two-sided" in that separate color
+scales are used for negative and for positive values in the data.  In
+the example shown, values greater than or equal to zero are mapped to
+colors ranging from black to red, orange and then white.  Negative
+values range from black through shades of gray.  The pseudo-log
+intensity scaling is actually applied to the absolute value of the
+data intensity, before mapping to a color. This allows small negative
+as well as small positive values to be seen and distinguished in the
+presence of large peaks.  This can be useful when dealing with data
+that was obtained by subtracting two workspaces, such as when
+background is subtracted, since due to errors in the data, this often
+introduces negative "intensities".
+
+Graphs
+------
+
+The displayed graphs are just cuts through the displayed image.
+That is, the graph of a spectrum across the bottom of the window
+is obtained from the corresponding row of the image data.  Consequently,
+the graph shows that spectrum as rebinned for the image display.
+Similarly, the graph at the left side of the window is obtained
+from the corresponding column of the image data, so it shows values
+from whatever spectra formed the image, at the selected bin.
+
+The graphs are both "auto-scaling" and adapt to the range of values
+in the selected portion of the data.  The Graph Max control allows
+the user to see lower level features in the data by reducing the
+portion of the range of values that are displayed.  When the control
+is at the right limit, 100% of the total range is displayed.  When
+the control is in the middle, only 50% of the total range is
+displayed.  When the control is at the far left, only 1% of the
+total range is displayed.
+
+Each of the graphs is in a separate pane that can be collapsed
+to zero size, if not needed.  The "control" for this is a small
+graphical "handle" on a divider between the graph and image.
+The graph size can be altered by grabbing the handle with the
+left mouse button pressed.  The size can be increased or decreased
+to a minimum size.  If the handle is moved substantially below
+the minimum size, the graph will collapse to zero size.
+
+
+.. categories:: Interfaces
diff --git a/Code/Mantid/docs/source/interfaces/Tomographic_Reconstruction.rst b/Code/Mantid/docs/source/interfaces/Tomographic_Reconstruction.rst
new file mode 100644
index 0000000000000000000000000000000000000000..d31f16f6ad90f25f598f33de0f037bcb527bc861
--- /dev/null
+++ b/Code/Mantid/docs/source/interfaces/Tomographic_Reconstruction.rst
@@ -0,0 +1,194 @@
+Tomographic Reconstruction
+==========================
+
+.. contents:: Table of Contents
+  :local:
+
+Overview
+--------
+
+This interface aims at integrating and simplifying the following tasks
+related to tomographic reconstruction and imaging with neutrons. While
+much of its functionality is being developed in a generic way, it is
+presently being tested and trialed for the IMAT instrument at ISIS.
+
+.. interface:: Tomographic Reconstruction
+  :align: center
+  :width: 600
+
+An important feature of this interface is the capability to submit
+jobs to a remote compute resource (a compute cluster for
+example). Currently remote jobs are run on the `SCARF cluster
+<http://www.scarf.rl.ac.uk/>`_, administered by the Scientific
+Computing Department of STFC. You can also use this cluster via remote
+login and through its `web portal <https://portal.scarf.rl.ac.uk/>`_.
+
+Interface at a glance
+---------------------
+
+By default the interface shows the *Run* tab, where you can visualize
+images, submit reconstruction jobs, see and control the status of the
+jobs submitted recently.
+
+.. interface:: Tomographic Reconstruction
+  :widget: runTab
+  :align: right
+  :width: 300
+
+In the setup tab you can set the details of the remote and/or local
+compute resources. Importantly, here is where you can set you username
+and password to log into the remote compute resource. To be able to
+run jobs remotely you first need to log into the remote compute
+resource. Once you log in, an automatic mechanism will periodically
+query the status of jobs (for example every minute). You can also
+update it at any time by clicking on the refresh button.
+
+In this tab you also have to set the folders/directories where the
+input data for reconstruction jobs is found. This information is
+required every time you start analyzing a new dataset. The required
+fields are:
+
+Samples directory
+  Directory containing the sample images
+
+Open beam directory
+  Where to find the open beam (flat/white) image(s)
+
+Dark field directory
+  Where to find the dark image(s)
+
+.. interface:: Tomographic Reconstruction
+  :widget: setupTab
+  :align: right
+  :width: 300
+
+In principle, the use of this interface is straightforward. **NB**: as
+this interface is in an early stage and under heavy development,
+several practical details are missing. This implies that there may be
+usability issues at times and some steps may not be as intuitive or
+simple as they could. Please, do not hesitate to provide feedback.
+
+The next sections provide further details that might be needed to
+fully understand the process of generating tomographic reconstructions
+with this interface.
+
+Tools
+-----
+
+At the moment two reconstruction tools are being set up and trialed on
+SCARF:
+
+* `TomoPy
+  <https://www1.aps.anl.gov/Science/Scientific-Software/TomoPy>`_
+
+* `Astra Toolbox <http://sourceforge.net/p/astra-toolbox/wiki/Home/>`_
+
+In the near future it is expected that support will be added for `Savu
+<https://github.com/DiamondLightSource/Savu>`_, developed at the
+Diamond Light Source.
+
+Data formats
+------------
+
+In principle, users do not need to deal with specificities of
+different file formats. That is the aim of this interface, but as it
+is currently being developed, and for reference a brief list of
+relevant file and data formats is given here:
+
+* FITS: `Flexible Image Transport System format
+  <http://en.wikipedia.org/wiki/FITS>`__ used to store images in
+  files. You can see the details on how FITS images can be loaded into
+  Mantid in the documentation of the algorithm LoadFITS
+  `<http://docs.mantidproject.org/nightly/algorithms/LoadFITS-v1.html>`__.
+
+* TIFF: `Tagged Image File Format
+  <http://en.wikipedia.org/wiki/Tagged_Image_File_Format>`__ images
+  used as FITS for image or slice files. This format is presently not
+  supported in the Mantid data analysis framework but it is used in
+  the tomographic reconstruction interface.
+
+* Diamond Light Source (DLS) NXTomo: a specific NeXus format used by
+  some of the tools that this interface supports or will support. See
+  next sections for details.
+
+These formats are used in different processing steps and parts of this
+interface. For example, you can visualize FITS and TIFF images in the
+**Run** tab. As another example, the reconstruction tools typically
+need as inputs at least a stack of images which can be in different
+formats, including a set of FITS or TIFF files, or a single DLS NXTomo
+file. Other third party tools use files in these formats as inputs,
+outputs or both.
+
+Data locations
+--------------
+
+This is dependent on the facility and instrument.
+
+TODO: this is work in progress. In principle data will be replicated
+in the ISIS archive, the SCARF imat disk space, and possibly an
+analysis machine located in R3.
+
+Running jobs remotely
+---------------------
+
+To be able to run jobs on a remote compute resource (cluster, supercomputer, etc.)
+
+* Log into the resource
+* Select it and setup one reconstruction tool
+* Use the **reconstruct** button in the **Run** tab of the interface
+
+You can monitor the status of the jobs currently running (and recently
+run) on remote compute resources in the same tab.
+
+Running jobs locally
+--------------------
+
+This functionality is not available at present.
+
+Example
+-------
+
+TODO: ideally, come up with a good and small example data set.
+
+TomoPy
+------
+
+TODO: how to use it. Hints.
+
+Astra Toolbox
+-------------
+
+TODO: how to use it. Hints.
+
+Astra Toolbox
+-------------
+
+TODO: how to use it. Hints.
+
+Savu
+----
+
+TODO: how to use it. Hints.
+
+Savu uses a specific file format developed by the Diamond Light
+Source, the DLS NXTomo. A few examples can be found from `the savu
+repository on GitHub
+<https://github.com/DiamondLightSource/Savu/tree/master/test_data>`__.
+
+Pipeline configuration
+~~~~~~~~~~~~~~~~~~~~~~
+
+A Savu reconstruction pipeline is defined by a list of processing
+steps (or plugins) and their parameters. In the Savu setup dialog this
+list is built on the right panel (current configuration) by adding and
+sorting available plugins available from the tree shown on the left
+panel. From the file menu, different savu configurations can be saved for
+later use and loaded from previously saved files.
+
+.. Leave this out for now. Not used at the moment.
+   .. interface:: Tomographic Reconstruction
+     :widget: savuConfigCentralWidget
+     :align: right
+
+
+.. categories:: Interfaces Diffraction
diff --git a/Code/Mantid/docs/sphinxext/mantiddoc/directives/interface.py b/Code/Mantid/docs/sphinxext/mantiddoc/directives/interface.py
index 392c29b2a9d28b02a0d982e25e770cf688000818..531e6297162a747d64b7dea005e2099b69dd85d7 100644
--- a/Code/Mantid/docs/sphinxext/mantiddoc/directives/interface.py
+++ b/Code/Mantid/docs/sphinxext/mantiddoc/directives/interface.py
@@ -59,7 +59,11 @@ class InterfaceDirective(BaseDirective):
         if not os.path.exists(screenshots_dir):
             os.makedirs(screenshots_dir)
 
-        return custominterface_screenshot(self.interface_name(), screenshots_dir, widget_name = widget_name)
+        try:
+            return custominterface_screenshot(self.interface_name(), screenshots_dir, widget_name = widget_name)
+        except RuntimeError:
+            # Assume GUI is not available
+            return None
 
     def _insert_screenshot_link(self, picture, align=None, width=None):
         """
diff --git a/Code/Mantid/instrument/BASIS_silicon_111_Parameters.xml b/Code/Mantid/instrument/BASIS_silicon_111_Parameters.xml
index c3f972fadbb9249f843be91841da559d468bd1b8..7be86ffc7af9515bdfb67c27b6d4ad30c2f43743 100644
--- a/Code/Mantid/instrument/BASIS_silicon_111_Parameters.xml
+++ b/Code/Mantid/instrument/BASIS_silicon_111_Parameters.xml
@@ -3,56 +3,55 @@
 
 <component-link name = "BASIS">
 
-<parameter name="analysis-type" type="string">
-  <value val="spectroscopy" />
-</parameter>
-
-<parameter name="spectra-min">
-	<value val="1" />
-</parameter>
+  <parameter name="analysis-type" type="string">
+    <value val="spectroscopy" />
+  </parameter>
 
-<!--FIXME: This spectrum max should be bigger -->
-<parameter name="spectra-max">
-	<value val="16385" />
-</parameter>
+  <parameter name="spectra-min">
+    <value val="1" />
+  </parameter>
 
-<parameter name="efixed-val">
-	<value val="2.082" />
-</parameter>
+  <!--FIXME: This spectrum max should be bigger -->
+  <parameter name="spectra-max">
+    <value val="16385" />
+  </parameter>
 
-<parameter name="peak-start">
-	<value val="140400" />
-</parameter>
+  <parameter name="peak-start">
+    <value val="140400" />
+  </parameter>
 
-<parameter name="peak-end">
-	<value val="141000" />
-</parameter>
+  <parameter name="peak-end">
+    <value val="141000" />
+  </parameter>
 
-<parameter name="back-start">
-	<value val="136500" />
-</parameter>
+  <parameter name="back-start">
+    <value val="136500" />
+  </parameter>
 
-<parameter name="back-end">
-	<value val="138000" />
-</parameter>
+  <parameter name="back-end">
+    <value val="138000" />
+  </parameter>
 
-<parameter name="analyser" type="string">
-  <value val="silicon" />
-</parameter>
+  <parameter name="analyser" type="string">
+    <value val="silicon" />
+  </parameter>
 
-<parameter name="reflection" type="string">
-  <value val="111" />
-</parameter>
+  <parameter name="reflection" type="string">
+    <value val="111" />
+  </parameter>
 
 </component-link>
 
 <component-link name="silicon">
+
   <parameter name="Efixed">
     <value val="2.082" />
   </parameter>
+
   <parameter name="resolution">
     <value val="0.0035" />
   </parameter>
+
 </component-link>
 
 </parameter-file>
diff --git a/Code/Mantid/instrument/IN10_Definition.xml b/Code/Mantid/instrument/IN10_Definition.xml
index 809db8d9389991e530c1004c45e6359ce8c88968..4efcdd5babfeb687bde5c18653560fc710049f07 100644
--- a/Code/Mantid/instrument/IN10_Definition.xml
+++ b/Code/Mantid/instrument/IN10_Definition.xml
@@ -1,7 +1,7 @@
 <?xml version="1.0" encoding="UTF-8" ?>
-<!-- For help on the notation used to specify an Instrument Definition File 
+<!-- For help on the notation used to specify an Instrument Definition File
      see http://www.mantidproject.org/IDF -->
-<instrument xmlns="http://www.mantidproject.org/IDF/1.0" 
+<instrument xmlns="http://www.mantidproject.org/IDF/1.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.mantidproject.org/IDF/1.0 http://schema.mantidproject.org/IDF/1.0/IDFSchema.xsd"
  name="IN10" valid-from   ="1900-01-31 23:59:59"
@@ -21,7 +21,7 @@
 </defaults>
 
 <!-- LIST OF PHYSICAL COMPONENTS (which the instrument consists of) -->
-  
+
 <!-- source and sample-position components -->
 
 <component type="moderator">
@@ -63,18 +63,17 @@
       <right-front-bottom-point  x="0.0125" y="0.0125" z="0.0"  />
     </cuboid>
     <algebra val="shape" />
-  </type>  
+  </type>
 
   <idlist idname="monitor1">
-    <id val="8" />  
+    <id val="8" />
   </idlist>
-  
+
 <!--  detector components -->
 
 <component type="silicon" idlist="silicon">
   <properties />
   <parameter name="Efixed"> <value val="2.08" /> </parameter>
-  <parameter name="efixed-val">	<value val="2.08" /></parameter>
   <location  />
 </component>
 
diff --git a/Code/Mantid/instrument/IN10_silicon_111_Parameters.xml b/Code/Mantid/instrument/IN10_silicon_111_Parameters.xml
index e292a34e1b21f36f342cf88768378922fa1c592a..2ecf0657395dd374418f355531bc1ee9b5addbf6 100644
--- a/Code/Mantid/instrument/IN10_silicon_111_Parameters.xml
+++ b/Code/Mantid/instrument/IN10_silicon_111_Parameters.xml
@@ -1,29 +1,24 @@
 <?xml version="1.0" encoding="UTF-8" ?>
 <parameter-file instrument = "IN10" valid-from = "2010-07-15T00:00:00">
 
-<component-link name = "IN10">
+  <component-link name = "IN10">
 
-<parameter name="analysis-type" type="string">
-  <value val="spectroscopy" />
-</parameter>
+    <parameter name="analysis-type" type="string">
+      <value val="spectroscopy" />
+    </parameter>
 
-<parameter name="efixed-val">
-	<value val="2.082" />
-</parameter>
+    <parameter name="analyser" type="string">
+      <value val="silicon" />
+    </parameter>
 
+    <parameter name="reflection" type="string">
+      <value val="111" />
+    </parameter>
 
+  </component-link>
 
-<parameter name="analyser" type="string">
-  <value val="silicon" />
-</parameter>
-
-<parameter name="reflection" type="string">
-  <value val="111" />
-</parameter>
-
-</component-link>
   <component-link name="silicon">
     <parameter name="Efixed"> <value val="2.082" /> </parameter>
     <parameter name="resolution"> <value val="0.001" /> </parameter>
   </component-link>
-</parameter-file>
\ No newline at end of file
+</parameter-file>
diff --git a/Code/Mantid/instrument/IN10_silicon_311_Parameters.xml b/Code/Mantid/instrument/IN10_silicon_311_Parameters.xml
index e2a1b00f7bc8dcf7b5f1377ce883e768ae80546b..ce0748d14f5fa51b9b47a80cc625f223da3bb15f 100644
--- a/Code/Mantid/instrument/IN10_silicon_311_Parameters.xml
+++ b/Code/Mantid/instrument/IN10_silicon_311_Parameters.xml
@@ -1,27 +1,22 @@
 <?xml version="1.0" encoding="UTF-8" ?>
 <parameter-file instrument = "IN10" valid-from = "2010-07-15T00:00:00">
 
-<component-link name = "IN10">
+  <component-link name = "IN10">
 
-<parameter name="analysis-type" type="string">
-  <value val="spectroscopy" />
-</parameter>
+    <parameter name="analysis-type" type="string">
+      <value val="spectroscopy" />
+    </parameter>
 
-<parameter name="efixed-val">
-	<value val="7.627" />
-</parameter>
+    <parameter name="analyser" type="string">
+      <value val="silicon" />
+    </parameter>
 
+    <parameter name="reflection" type="string">
+      <value val="311" />
+    </parameter>
 
+  </component-link>
 
-<parameter name="analyser" type="string">
-  <value val="silicon" />
-</parameter>
-
-<parameter name="reflection" type="string">
-  <value val="311" />
-</parameter>
-
-</component-link>
   <component-link name="silicon">
     <parameter name="Efixed"> <value val="7.627" /> </parameter>
     <parameter name="resolution"> <value val="0.002" /> </parameter>
diff --git a/Code/Mantid/instrument/IN13_CaF_422_Parameters.xml b/Code/Mantid/instrument/IN13_CaF_422_Parameters.xml
index 0c64bdac24fd2b784936bfb3e65a8fbb0466185f..6c700693b8bb8c8fda326e7bce077f69d7887ae6 100644
--- a/Code/Mantid/instrument/IN13_CaF_422_Parameters.xml
+++ b/Code/Mantid/instrument/IN13_CaF_422_Parameters.xml
@@ -1,29 +1,24 @@
 <?xml version="1.0" encoding="UTF-8" ?>
 <parameter-file instrument = "IN13" valid-from = "2010-07-15T00:00:00">
 
-<component-link name = "IN13">
+  <component-link name = "IN13">
 
-<parameter name="analysis-type" type="string">
-  <value val="spectroscopy" />
-</parameter>
+    <parameter name="analysis-type" type="string">
+      <value val="spectroscopy" />
+    </parameter>
 
-<parameter name="efixed-val">
-	<value val="16.45" />
-</parameter>
+    <parameter name="analyser" type="string">
+      <value val="CaF" />
+    </parameter>
 
+    <parameter name="reflection" type="string">
+      <value val="422" />
+    </parameter>
 
+  </component-link>
 
-<parameter name="analyser" type="string">
-  <value val="CaF" />
-</parameter>
-
-<parameter name="reflection" type="string">
-  <value val="422" />
-</parameter>
-
-</component-link>
   <component-link name="silicon">
     <parameter name="Efixed"> <value val="16.45" /> </parameter>
     <parameter name="resolution"> <value val="0.008" /> </parameter>
   </component-link>
-</parameter-file>
\ No newline at end of file
+</parameter-file>
diff --git a/Code/Mantid/instrument/IN13_Definition.xml b/Code/Mantid/instrument/IN13_Definition.xml
index ef5bb4e1f67255fa722fba38d74b6895ed8e5a98..5032be670233717c992fc32daf8a31a3d6c39301 100644
--- a/Code/Mantid/instrument/IN13_Definition.xml
+++ b/Code/Mantid/instrument/IN13_Definition.xml
@@ -1,7 +1,7 @@
 <?xml version="1.0" encoding="UTF-8" ?>
-<!-- For help on the notation used to specify an Instrument Definition File 
+<!-- For help on the notation used to specify an Instrument Definition File
      see http://www.mantidproject.org/IDF -->
-<instrument xmlns="http://www.mantidproject.org/IDF/1.0" 
+<instrument xmlns="http://www.mantidproject.org/IDF/1.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.mantidproject.org/IDF/1.0 http://schema.mantidproject.org/IDF/1.0/IDFSchema.xsd"
  name="IN13" valid-from   ="1900-01-31 23:59:59"
@@ -21,7 +21,7 @@
 </defaults>
 
 <!-- LIST OF PHYSICAL COMPONENTS (which the instrument consists of) -->
-  
+
 <!-- source and sample-position components -->
 
 <component type="moderator">
@@ -63,18 +63,17 @@
       <right-front-bottom-point  x="0.0125" y="0.0125" z="0.0"  />
     </cuboid>
     <algebra val="shape" />
-  </type>  
+  </type>
 
   <idlist idname="monitor1">
-    <id val="8" />  
+    <id val="8" />
   </idlist>
-  
+
 <!--  detector components -->
 
 <component type="CaF" idlist="CaF">
   <properties />
   <parameter name="Efixed"> <value val="16.45" /> </parameter>
-  <parameter name="efixed-val">	<value val="16.45" /></parameter>
   <location  />
 </component>
 
diff --git a/Code/Mantid/instrument/IN16B_silicon_111_Parameters.xml b/Code/Mantid/instrument/IN16B_silicon_111_Parameters.xml
index b8ab7a5d9ecf5b6f993d0199e61bd11e68a6ad3c..a23c0c5c0e50ec36213c42c7d298c3368ef1182a 100644
--- a/Code/Mantid/instrument/IN16B_silicon_111_Parameters.xml
+++ b/Code/Mantid/instrument/IN16B_silicon_111_Parameters.xml
@@ -1,29 +1,25 @@
 <?xml version="1.0" encoding="UTF-8" ?>
 <parameter-file instrument = "IN16B" valid-from = "2014-05-06T00:00:00">
 
-<component-link name = "IN16B">
+  <component-link name = "IN16B">
 
-<parameter name="analysis-type" type="string">
-  <value val="spectroscopy" />
-</parameter>
+    <parameter name="analysis-type" type="string">
+      <value val="spectroscopy" />
+    </parameter>
 
-<parameter name="efixed-val">
-  <value val="2.082" />
-</parameter>
+    <parameter name="analyser" type="string">
+      <value val="silicon" />
+    </parameter>
 
+    <parameter name="reflection" type="string">
+      <value val="111" />
+    </parameter>
 
+  </component-link>
 
-  <parameter name="analyser" type="string">
-    <value val="silicon" />
-  </parameter>
+  <component-link name="silicon">
+    <parameter name="Efixed"> <value val="2.082" /> </parameter>
+    <parameter name="resolution"> <value val="0.0003" /> </parameter>
+  </component-link>
 
-  <parameter name="reflection" type="string">
-    <value val="111" />
-  </parameter>
-
-</component-link>
-<component-link name="silicon">
-  <parameter name="Efixed"> <value val="2.082" /> </parameter>
-  <parameter name="resolution"> <value val="0.0003" /> </parameter>
-</component-link>
 </parameter-file>
diff --git a/Code/Mantid/instrument/IN16_Definition.xml b/Code/Mantid/instrument/IN16_Definition.xml
index 77b43629a07f8bbcfa7ee379a1ba611ad6129165..683e89cfa5591f687757d038d5e82a50a670a6c6 100644
--- a/Code/Mantid/instrument/IN16_Definition.xml
+++ b/Code/Mantid/instrument/IN16_Definition.xml
@@ -1,7 +1,7 @@
 <?xml version="1.0" encoding="UTF-8" ?>
-<!-- For help on the notation used to specify an Instrument Definition File 
+<!-- For help on the notation used to specify an Instrument Definition File
      see http://www.mantidproject.org/IDF -->
-<instrument xmlns="http://www.mantidproject.org/IDF/1.0" 
+<instrument xmlns="http://www.mantidproject.org/IDF/1.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.mantidproject.org/IDF/1.0 http://schema.mantidproject.org/IDF/1.0/IDFSchema.xsd"
  name="IN16" valid-from   ="1900-01-31 23:59:59"
@@ -21,7 +21,7 @@
 </defaults>
 
 <!-- LIST OF PHYSICAL COMPONENTS (which the instrument consists of) -->
-  
+
 <!-- source and sample-position components -->
 
 <component type="moderator">
@@ -63,18 +63,17 @@
       <right-front-bottom-point  x="0.0125" y="0.0125" z="0.0"  />
     </cuboid>
     <algebra val="shape" />
-  </type>  
+  </type>
 
   <idlist idname="monitor1">
-    <id val="19" />  
+    <id val="19" />
   </idlist>
-  
+
 <!--  detector components -->
 
 <component type="silicon" idlist="silicon">
   <properties />
   <parameter name="Efixed"> <value val="2.08" /> </parameter>
-  <parameter name="efixed-val">	<value val="2.08" /></parameter>
   <location  />
 </component>
 
diff --git a/Code/Mantid/instrument/IN16_silicon_111_Parameters.xml b/Code/Mantid/instrument/IN16_silicon_111_Parameters.xml
index 42e9bf49e4fa9e99827b5c99fed07913c3926622..4d9eede6af7ea0f9cd90390c23850136698ed5c1 100644
--- a/Code/Mantid/instrument/IN16_silicon_111_Parameters.xml
+++ b/Code/Mantid/instrument/IN16_silicon_111_Parameters.xml
@@ -1,29 +1,25 @@
 <?xml version="1.0" encoding="UTF-8" ?>
 <parameter-file instrument = "IN16" valid-from = "2010-07-15T00:00:00">
 
-<component-link name = "IN16">
+  <component-link name = "IN16">
 
-<parameter name="analysis-type" type="string">
-  <value val="spectroscopy" />
-</parameter>
+    <parameter name="analysis-type" type="string">
+      <value val="spectroscopy" />
+    </parameter>
 
-<parameter name="efixed-val">
-  <value val="2.082" />
-</parameter>
+    <parameter name="analyser" type="string">
+      <value val="silicon" />
+    </parameter>
 
+    <parameter name="reflection" type="string">
+      <value val="111" />
+    </parameter>
 
+  </component-link>
 
-  <parameter name="analyser" type="string">
-    <value val="silicon" />
-  </parameter>
+  <component-link name="silicon">
+    <parameter name="Efixed"> <value val="2.082" /> </parameter>
+    <parameter name="resolution"> <value val="0.0003" /> </parameter>
+  </component-link>
 
-  <parameter name="reflection" type="string">
-    <value val="111" />
-  </parameter>
-
-</component-link>
-<component-link name="silicon">
-  <parameter name="Efixed"> <value val="2.082" /> </parameter>
-  <parameter name="resolution"> <value val="0.0003" /> </parameter>
-</component-link>
-</parameter-file>
\ No newline at end of file
+</parameter-file>
diff --git a/Code/Mantid/instrument/IN16_silicon_311_Parameters.xml b/Code/Mantid/instrument/IN16_silicon_311_Parameters.xml
index 2467d81b2bfca6a8b82806d5c220ac4f52a1b2b2..8e7e07d263925dd34bfaafc1bac9320252866042 100644
--- a/Code/Mantid/instrument/IN16_silicon_311_Parameters.xml
+++ b/Code/Mantid/instrument/IN16_silicon_311_Parameters.xml
@@ -1,29 +1,25 @@
 <?xml version="1.0" encoding="UTF-8" ?>
 <parameter-file instrument = "IN16" valid-from = "2010-07-15T00:00:00">
 
-<component-link name = "IN16">
+  <component-link name = "IN16">
 
-<parameter name="analysis-type" type="string">
-  <value val="spectroscopy" />
-</parameter>
+    <parameter name="analysis-type" type="string">
+      <value val="spectroscopy" />
+    </parameter>
 
-<parameter name="efixed-val">
-	<value val="7.627"/>
-</parameter>
+    <parameter name="analyser" type="string">
+      <value val="silicon" />
+    </parameter>
 
+    <parameter name="reflection" type="string">
+      <value val="311" />
+    </parameter>
 
+  </component-link>
 
-  <parameter name="analyser" type="string">
-    <value val="silicon" />
-  </parameter>
+  <component-link name="silicon">
+    <parameter name="Efixed"> <value val="7.627" /> </parameter>
+    <parameter name="resolution"> <value val="0.002" /> </parameter>
+  </component-link>
 
-  <parameter name="reflection" type="string">
-    <value val="311" />
-  </parameter>
-
-</component-link>
-<component-link name="silicon">
-  <parameter name="Efixed"> <value val="7.627" /> </parameter>
-  <parameter name="resolution"> <value val="0.002" /> </parameter>
-</component-link>
-</parameter-file>
\ No newline at end of file
+</parameter-file>
diff --git a/Code/Mantid/instrument/IRIS_Parameters.xml b/Code/Mantid/instrument/IRIS_Parameters.xml
index a2e673bd25f37513e63076809ea3e2f22ff840c2..9c0ba3b1958acf48d1c583c7e77c0c36c39fe23e 100644
--- a/Code/Mantid/instrument/IRIS_Parameters.xml
+++ b/Code/Mantid/instrument/IRIS_Parameters.xml
@@ -32,6 +32,9 @@
 <parameter name="cm-1-convert-choice" type="string">
     <value val="false" />
 </parameter>
+<parameter name="save-nexus-choice" type="string">
+    <value val="true" />
+</parameter>
 <parameter name="save-ascii-choice" type="string">
     <value val="false" />
 </parameter>
diff --git a/Code/Mantid/instrument/IRIS_fmica_002_Parameters.xml b/Code/Mantid/instrument/IRIS_fmica_002_Parameters.xml
index d38016d8faa297298ada03f2405aec1ef0094bbd..fb38af61de82f0097a05701e349b5eba6e8693ac 100644
--- a/Code/Mantid/instrument/IRIS_fmica_002_Parameters.xml
+++ b/Code/Mantid/instrument/IRIS_fmica_002_Parameters.xml
@@ -15,10 +15,6 @@
 	<value val="104" />
 </parameter>
 
-<parameter name="efixed-val">
-	<value val="0.2067" />
-</parameter>
-
 <parameter name="peak-start">
 	<value val="189000" />
 </parameter>
@@ -47,5 +43,5 @@
 <parameter name="Efixed"> <value val="0.2067" /> </parameter>
 <parameter name="resolution"> <value val="0.0012" /> </parameter>
 </component-link>
-  
-</parameter-file>
\ No newline at end of file
+
+</parameter-file>
diff --git a/Code/Mantid/instrument/IRIS_fmica_006_Parameters.xml b/Code/Mantid/instrument/IRIS_fmica_006_Parameters.xml
index 05028b4dd127fe4f7faf3c7bced3b33bda88c95f..2cc3724dd7ebdac60f6b207838a0b67daa18d502 100644
--- a/Code/Mantid/instrument/IRIS_fmica_006_Parameters.xml
+++ b/Code/Mantid/instrument/IRIS_fmica_006_Parameters.xml
@@ -15,10 +15,6 @@
 	<value val="104" />
 </parameter>
 
-<parameter name="efixed-val">
-	<value val="1.8567" />
-</parameter>
-
 <parameter name="peak-start">
 	<value val="62500" />
 </parameter>
@@ -48,4 +44,4 @@
 <parameter name="Efixed"> <value val="1.8567" /> </parameter>
 <parameter name="resolution"> <value val="0.011" /> </parameter>
 </component-link>
-</parameter-file>
\ No newline at end of file
+</parameter-file>
diff --git a/Code/Mantid/instrument/IRIS_graphite_002_Parameters.xml b/Code/Mantid/instrument/IRIS_graphite_002_Parameters.xml
index 817833e7cbd10e6aae6f49f5127a25542519b7a8..e0c14a3524ebf988a930cb4ce2712af2dccf8db4 100644
--- a/Code/Mantid/instrument/IRIS_graphite_002_Parameters.xml
+++ b/Code/Mantid/instrument/IRIS_graphite_002_Parameters.xml
@@ -15,10 +15,6 @@
 	<value val="53" />
 </parameter>
 
-<parameter name="efixed-val">
-	<value val="1.8450" />
-</parameter>
-
 <parameter name="peak-start">
 	<value val="62500" />
 </parameter>
@@ -51,4 +47,4 @@
 </component-link>
 
 
-</parameter-file>
\ No newline at end of file
+</parameter-file>
diff --git a/Code/Mantid/instrument/IRIS_graphite_004_Parameters.xml b/Code/Mantid/instrument/IRIS_graphite_004_Parameters.xml
index 07129e79b355356d8835effaa5681a529b81207b..cba0c4f8504a94a941030cea0b4e27bec8ff34b4 100644
--- a/Code/Mantid/instrument/IRIS_graphite_004_Parameters.xml
+++ b/Code/Mantid/instrument/IRIS_graphite_004_Parameters.xml
@@ -17,10 +17,6 @@
 	<value val="53" />
 </parameter>
 
-<parameter name="efixed-val">
-	<value val="7.3812" />
-</parameter>
-
 <parameter name="peak-start">
 	<value val="31500" />
 </parameter>
@@ -37,17 +33,18 @@
 	<value val="27000" />
 </parameter>
 
-  <parameter name="analyser" type="string">
-    <value val="graphite" />
-  </parameter>
+<parameter name="analyser" type="string">
+  <value val="graphite" />
+</parameter>
 
-  <parameter name="reflection" type="string">
-    <value val="004" />
-  </parameter>
+<parameter name="reflection" type="string">
+  <value val="004" />
+</parameter>
 
 </component-link>
+
 <component-link name="graphite">
 <parameter name="Efixed"> <value val="7.3812" /> </parameter>
 <parameter name="resolution"> <value val="0.0545" /> </parameter>
 </component-link>
-</parameter-file>
\ No newline at end of file
+</parameter-file>
diff --git a/Code/Mantid/instrument/IRIS_mica_002_Parameters.xml b/Code/Mantid/instrument/IRIS_mica_002_Parameters.xml
index 77edcc83d0d7bc9ad5d9be378b0e07840641a2b7..9e46c5ba86ea61c5705b3e2c456a7c1a6371b3ff 100644
--- a/Code/Mantid/instrument/IRIS_mica_002_Parameters.xml
+++ b/Code/Mantid/instrument/IRIS_mica_002_Parameters.xml
@@ -15,10 +15,6 @@
 	<value val="104" />
 </parameter>
 
-<parameter name="efixed-val">
-	<value val="0.2067" />
-</parameter>
-
 <parameter name="peak-start">
 	<value val="189000" />
 </parameter>
@@ -35,8 +31,6 @@
 	<value val="188000" />
 </parameter>
 
-
-
 <parameter name="analyser" type="string">
   <value val="mica" />
 </parameter>
@@ -46,9 +40,10 @@
 </parameter>
 
 </component-link>
+
   <component-link name="mica">
     <parameter name="Efixed">
       <value val="0.2067" />
     </parameter>
   </component-link>
-</parameter-file>
\ No newline at end of file
+</parameter-file>
diff --git a/Code/Mantid/instrument/IRIS_mica_004_Parameters.xml b/Code/Mantid/instrument/IRIS_mica_004_Parameters.xml
index 315f7dce4a396123d8350025a8607aa3a6e52f9e..ac402875687048d2ea1e663a173978f89f2acaed 100644
--- a/Code/Mantid/instrument/IRIS_mica_004_Parameters.xml
+++ b/Code/Mantid/instrument/IRIS_mica_004_Parameters.xml
@@ -15,10 +15,6 @@
 	<value val="104" />
 </parameter>
 
-<parameter name="efixed-val">
-	<value val="0.8255" />
-</parameter>
-
 <parameter name="peak-start">
 	<value val="94500" />
 </parameter>
@@ -35,8 +31,6 @@
 	<value val="101500" />
 </parameter>
 
-
-
 <parameter name="analyser" type="string">
   <value val="mica" />
 </parameter>
@@ -46,9 +40,10 @@
 </parameter>
 
 </component-link>
+
   <component-link name="mica">
     <parameter name="Efixed">
       <value val="0.8255" />
     </parameter>
   </component-link>
-</parameter-file>
\ No newline at end of file
+</parameter-file>
diff --git a/Code/Mantid/instrument/IRIS_mica_006_Parameters.xml b/Code/Mantid/instrument/IRIS_mica_006_Parameters.xml
index b03b9d36712ff888278e92e8a19af74491934b3f..a4e143cd8a9527ee7f412c532cb7d6e9fbf197c6 100644
--- a/Code/Mantid/instrument/IRIS_mica_006_Parameters.xml
+++ b/Code/Mantid/instrument/IRIS_mica_006_Parameters.xml
@@ -15,10 +15,6 @@
 	<value val="104" />
 </parameter>
 
-<parameter name="efixed-val">
-	<value val="1.8567" />
-</parameter>
-
 <parameter name="peak-start">
 	<value val="62500" />
 </parameter>
@@ -35,20 +31,20 @@
 	<value val="61500" />
 </parameter>
 
+<parameter name="analyser" type="string">
+  <value val="mica" />
+</parameter>
 
-  <parameter name="analyser" type="string">
-    <value val="mica" />
-  </parameter>
-
-  <parameter name="reflection" type="string">
-    <value val="006" />
-  </parameter>
+<parameter name="reflection" type="string">
+  <value val="006" />
+</parameter>
 
 </component-link>
+
 <component-link name="mica">
   <parameter name="Efixed">
     <value val="1.8567" />
   </parameter>
 </component-link>
 
-</parameter-file>
\ No newline at end of file
+</parameter-file>
diff --git a/Code/Mantid/instrument/LET_Definition.xml b/Code/Mantid/instrument/LET_Definition.xml
index f54ab3fd09a8117bf230aa25909ceca4bbb009fb..a79bb314a74bb19549a4f00e59d65464e242a800 100644
--- a/Code/Mantid/instrument/LET_Definition.xml
+++ b/Code/Mantid/instrument/LET_Definition.xml
@@ -6,7 +6,7 @@
             xsi:schemaLocation="http://www.mantidproject.org/IDF/1.0 http://schema.mantidproject.org/IDF/1.0/IDFSchema.xsd"
  name="LET" valid-from   ="1900-01-31 23:59:59"
                        valid-to     ="2014-02-10 23:59:59"
-		       last-modified="2012-03-13 00:00:00">
+		       last-modified="2015-03-09 00:00:00">
  
    <defaults>
      <length unit="meter"/>
diff --git a/Code/Mantid/instrument/LET_Definition_dr2to9.xml b/Code/Mantid/instrument/LET_Definition_dr2to9.xml
index d480ca3eb474b911bb38bc451cd00de435b09b7e..24b6b7e5be2a4f27bc651af01b3265b360581508 100644
--- a/Code/Mantid/instrument/LET_Definition_dr2to9.xml
+++ b/Code/Mantid/instrument/LET_Definition_dr2to9.xml
@@ -6,7 +6,7 @@
             xsi:schemaLocation="http://www.mantidproject.org/IDF/1.0 http://schema.mantidproject.org/IDF/1.0/IDFSchema.xsd"
  name="LET" valid-from   ="2014-02-11 00:00:01"
                        valid-to     ="2014-05-01 23:59:59"
-		       last-modified="2014-05-06 00:00:00">
+		       last-modified="2015-03-09 00:00:00">
  
    <defaults>
      <length unit="meter"/>
diff --git a/Code/Mantid/instrument/LET_Definition_dr3to10.xml b/Code/Mantid/instrument/LET_Definition_dr3to10.xml
index 9cd7fd1b83d8369652d953d4a82ba1e066bde965..cad57540e55360767d147c683b1fcab2542f2b7c 100644
--- a/Code/Mantid/instrument/LET_Definition_dr3to10.xml
+++ b/Code/Mantid/instrument/LET_Definition_dr3to10.xml
@@ -6,7 +6,7 @@
             xsi:schemaLocation="http://www.mantidproject.org/IDF/1.0 http://schema.mantidproject.org/IDF/1.0/IDFSchema.xsd"
  name="LET" valid-from   ="2014-05-02 23:59:59"
                valid-to     ="2014-07-11 23:59:59"
-               last-modified="2014-07-16 18:27:00">
+               last-modified="2015-03-09 18:27:00">
  
    <defaults>
      <length unit="meter"/>
diff --git a/Code/Mantid/instrument/LET_Definition_dr3to11.xml b/Code/Mantid/instrument/LET_Definition_dr3to11.xml
index 15c624c0027284113ffcfc9789964881c8fc85c1..7652e186a34eac8fe907468959ea75bf3b55fc8c 100644
--- a/Code/Mantid/instrument/LET_Definition_dr3to11.xml
+++ b/Code/Mantid/instrument/LET_Definition_dr3to11.xml
@@ -6,7 +6,7 @@
             xsi:schemaLocation="http://www.mantidproject.org/IDF/1.0 http://schema.mantidproject.org/IDF/1.0/IDFSchema.xsd"
  name="LET" valid-from   ="2014-07-12 00:00:01"
                valid-to     ="2014-08-31 23:59:59"
-               last-modified="2014-07-16 18:30:0">
+               last-modified="2015-03-09 18:30:0">
  
    <defaults>
      <length unit="meter"/>
diff --git a/Code/Mantid/instrument/MolDyn_Definition.xml b/Code/Mantid/instrument/MolDyn_Definition.xml
index 8d1524311b3c9e7a9174dd226b84ff781196afc5..904141d272f09d1cac40aebafd2b2a627eb59866 100644
--- a/Code/Mantid/instrument/MolDyn_Definition.xml
+++ b/Code/Mantid/instrument/MolDyn_Definition.xml
@@ -1,7 +1,7 @@
 <?xml version="1.0" encoding="UTF-8" ?>
-<!-- For help on the notation used to specify an Instrument Definition File 
+<!-- For help on the notation used to specify an Instrument Definition File
      see http://www.mantidproject.org/IDF -->
-<instrument xmlns="http://www.mantidproject.org/IDF/1.0" 
+<instrument xmlns="http://www.mantidproject.org/IDF/1.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.mantidproject.org/IDF/1.0 http://schema.mantidproject.org/IDF/1.0/IDFSchema.xsd"
  name="MolDyn" valid-from   ="1900-01-31 23:59:59"
@@ -21,7 +21,7 @@
 </defaults>
 
 <!-- LIST OF PHYSICAL COMPONENTS (which the instrument consists of) -->
-  
+
 <!-- source and sample-position components -->
 
 <component type="moderator">
@@ -48,13 +48,12 @@
 
 <!-- LIST OF DETECTORS AND MONITORS -->
 
-  
+
 <!--  detector components -->
 
 <component type="simul" idlist="simul">
   <properties />
   <parameter name="Efixed"> <value val="2.08" /> </parameter>
-  <parameter name="efixed-val">	<value val="2.08" /></parameter>
   <location  />
 </component>
 
diff --git a/Code/Mantid/instrument/MolDyn_qmax_2_Parameters.xml b/Code/Mantid/instrument/MolDyn_qmax_2_Parameters.xml
index 856b1c39b8de7b493fbc803c38cd8d08b34867d7..be6c1cb93aa18d97eab8733864883b24e8a9c3c4 100644
--- a/Code/Mantid/instrument/MolDyn_qmax_2_Parameters.xml
+++ b/Code/Mantid/instrument/MolDyn_qmax_2_Parameters.xml
@@ -7,10 +7,6 @@
   <value val="spectroscopy" />
 </parameter>
 
-<parameter name="efixed-val">
-	<value val="1.8450" />
-</parameter>
-
 <parameter name="analyser" type="string">
   <value val="qmax" />
 </parameter>
diff --git a/Code/Mantid/instrument/MolDyn_qmax_4_Parameters.xml b/Code/Mantid/instrument/MolDyn_qmax_4_Parameters.xml
index 33c2cb3fd3aaec2be36d67cf265e010c76758d04..08f7a37ee470a72b45459674b25c2d4af45c1d92 100644
--- a/Code/Mantid/instrument/MolDyn_qmax_4_Parameters.xml
+++ b/Code/Mantid/instrument/MolDyn_qmax_4_Parameters.xml
@@ -7,10 +7,6 @@
   <value val="spectroscopy" />
 </parameter>
 
-<parameter name="efixed-val">
-	<value val="7.3812" />
-</parameter>
-
 <parameter name="analyser" type="string">
   <value val="qmax" />
 </parameter>
diff --git a/Code/Mantid/instrument/OSIRIS_Parameters.xml b/Code/Mantid/instrument/OSIRIS_Parameters.xml
index 2da0640530efeb257dd3b8556342f10a21f36f6c..e74511bb3df614223c4fd31197d51e3f6028568c 100644
--- a/Code/Mantid/instrument/OSIRIS_Parameters.xml
+++ b/Code/Mantid/instrument/OSIRIS_Parameters.xml
@@ -24,6 +24,9 @@
 <parameter name="cm-1-convert-choice" type="string">
     <value val="false" />
 </parameter>
+<parameter name="save-nexus-choice" type="string">
+    <value val="true" />
+</parameter>
 <parameter name="save-ascii-choice" type="string">
     <value val="false" />
 </parameter>
diff --git a/Code/Mantid/instrument/OSIRIS_graphite_002_Parameters.xml b/Code/Mantid/instrument/OSIRIS_graphite_002_Parameters.xml
index e596b0248c3ef43ee121acc355657f2d4555a892..131fce40af190104f97379557b6378b749e5d1f7 100644
--- a/Code/Mantid/instrument/OSIRIS_graphite_002_Parameters.xml
+++ b/Code/Mantid/instrument/OSIRIS_graphite_002_Parameters.xml
@@ -2,59 +2,55 @@
 <parameter-file instrument = "OSIRIS" valid-from = "2010-07-15T00:00:00">
 
   <component-link name = "OSIRIS">
-    
+
     <parameter name="analysis-type" type="string">
       <value val="spectroscopy" />
     </parameter>
-    
+
     <parameter name="spectra-min">
       <value val="963" />
     </parameter>
-    
+
     <parameter name="spectra-max">
       <value val="1004" />
     </parameter>
-    
-    <parameter name="efixed-val">
-      <value val="1.8450" />
-    </parameter>
-    
+
     <parameter name="peak-start">
       <value val="59000" />
     </parameter>
-    
+
     <parameter name="peak-end">
       <value val="61000" />
     </parameter>
     <parameter name="back-start">
       <value val="68000" />
     </parameter>
-    
+
     <parameter name="back-end">
       <value val="70000" />
     </parameter>
-    
+
     <parameter name="analyser" type="string">
       <value val="graphite" />
     </parameter>
-    
+
     <parameter name="reflection" type="string">
       <value val="002" />
     </parameter>
-    
+
   </component-link>
-  
+
   <component-link name="graphite">
-    
+
     <parameter name="Efixed">
       <value val="1.845" />
     </parameter>
-    
+
     <parameter name="resolution">
       <value val="0.0245" />
     </parameter>
-    
+
   </component-link>
-  
+
 </parameter-file>
 
diff --git a/Code/Mantid/instrument/OSIRIS_graphite_004_Parameters.xml b/Code/Mantid/instrument/OSIRIS_graphite_004_Parameters.xml
index 7d4703369defde264ffc5c4820783844f417227a..0dec5639e3220df1a08931ec317df71bba98edda 100644
--- a/Code/Mantid/instrument/OSIRIS_graphite_004_Parameters.xml
+++ b/Code/Mantid/instrument/OSIRIS_graphite_004_Parameters.xml
@@ -1,53 +1,56 @@
 <?xml version="1.0" encoding="UTF-8" ?>
 <parameter-file instrument = "OSIRIS" valid-from = "2010-07-15T00:00:00">
 
-<component-link name = "OSIRIS">
+  <component-link name = "OSIRIS">
 
-<parameter name="analysis-type" type="string">
-  <value val="spectroscopy" />
-</parameter>
+    <parameter name="analysis-type" type="string">
+      <value val="spectroscopy" />
+    </parameter>
 
-<parameter name="spectra-min">
-	<value val="963" />
-</parameter>
+    <parameter name="spectra-min">
+      <value val="963" />
+    </parameter>
 
-<parameter name="spectra-max">
-	<value val="1004" />
-</parameter>
+    <parameter name="spectra-max">
+      <value val="1004" />
+    </parameter>
 
-<parameter name="efixed-val">
-	<value val="7.3812" />
-</parameter>
+    <parameter name="peak-start">
+      <value val="29500" />
+    </parameter>
 
-<parameter name="peak-start">
-	<value val="29500" />
-</parameter>
+    <parameter name="peak-end">
+      <value val="30500" />
+    </parameter>
 
-<parameter name="peak-end">
-	<value val="30500" />
-</parameter>
+    <parameter name="back-start">
+      <value val="24000" />
+    </parameter>
 
-<parameter name="back-start">
-	<value val="24000" />
-</parameter>
+    <parameter name="back-end">
+      <value val="26000" />
+    </parameter>
 
-<parameter name="back-end">
-	<value val="26000" />
-</parameter>
+    <parameter name="analyser" type="string">
+      <value val="graphite" />
+    </parameter>
 
-<parameter name="analyser" type="string">
-  <value val="graphite" />
-</parameter>
+    <parameter name="reflection" type="string">
+      <value val="004" />
+    </parameter>
 
-<parameter name="reflection" type="string">
-  <value val="004" />
-</parameter>
+  </component-link>
 
-</component-link>
+  <component-link name="graphite">
 
-<component-link name="graphite">
-<parameter name="Efixed"> <value val="7.3812" /> </parameter>
+    <parameter name="Efixed">
+      <value val="7.3812" />
+    </parameter>
 
-<parameter name="resolution"> <value val="0.100" /> </parameter>
-</component-link>
-</parameter-file>
\ No newline at end of file
+    <parameter name="resolution">
+      <value val="0.100" />
+    </parameter>
+
+  </component-link>
+
+</parameter-file>
diff --git a/Code/Mantid/instrument/TFXA_Parameters.xml b/Code/Mantid/instrument/TFXA_Parameters.xml
index 99740aea3036fdae16336f9548b56590793cfe8e..81030abbcd6a46e20e3fc65bd59b2b420b3ca104 100644
--- a/Code/Mantid/instrument/TFXA_Parameters.xml
+++ b/Code/Mantid/instrument/TFXA_Parameters.xml
@@ -25,6 +25,10 @@
       <value val="true" />
     </parameter>
 
+    <parameter name="save-nexus-choice" type="string">
+      <value val="false" />
+    </parameter>
+
     <parameter name="save-ascii-choice" type="string">
       <value val="true" />
     </parameter>
diff --git a/Code/Mantid/instrument/TFXA_Parameters_Post-1993-10-06.xml b/Code/Mantid/instrument/TFXA_Parameters_Post-1993-10-06.xml
index 3a4c07aac3355eb08b9140fecdae48a2ac1e8812..4eb44dc738428af880359913dce513a92e71b9c5 100644
--- a/Code/Mantid/instrument/TFXA_Parameters_Post-1993-10-06.xml
+++ b/Code/Mantid/instrument/TFXA_Parameters_Post-1993-10-06.xml
@@ -25,6 +25,10 @@
       <value val="true" />
     </parameter>
 
+    <parameter name="save-nexus-choice" type="string">
+      <value val="false" />
+    </parameter>
+
     <parameter name="save-ascii-choice" type="string">
       <value val="true" />
     </parameter>
diff --git a/Code/Mantid/instrument/TFXA_graphite_002_Parameters.xml b/Code/Mantid/instrument/TFXA_graphite_002_Parameters.xml
index 51168e630d43ac67ad3c844718efb7339ad5e155..5b2b76596051beaa2432a8afdfbcc400d4d1d63a 100644
--- a/Code/Mantid/instrument/TFXA_graphite_002_Parameters.xml
+++ b/Code/Mantid/instrument/TFXA_graphite_002_Parameters.xml
@@ -15,10 +15,6 @@
       <value val="28" />
     </parameter>
 
-    <parameter name="efixed-val">
-      <value val="0" />
-    </parameter>
-
     <parameter name="peak-start">
       <value val="0" />
     </parameter>
diff --git a/Code/Mantid/instrument/TOSCA_Definition_TOSCA-1.xml b/Code/Mantid/instrument/TOSCA_Definition_TOSCA-1.xml
index bf662fadb7276c2f9f267c40eebb3cd593264717..5aca28062510cbe4f9b9f2594ebfe5248ac4fd07 100644
--- a/Code/Mantid/instrument/TOSCA_Definition_TOSCA-1.xml
+++ b/Code/Mantid/instrument/TOSCA_Definition_TOSCA-1.xml
@@ -21,7 +21,7 @@
 
   <!--  SOURCE AND SAMPLE POSITION -->
   <component type="moderator">
-    <location z="-17.0" />
+    <location z="-12.0" />
   </component>
 
   <type name="moderator" is="Source">
diff --git a/Code/Mantid/instrument/TOSCA_Parameters.xml b/Code/Mantid/instrument/TOSCA_Parameters.xml
index ab712fcba5b9a2d6137aa884a49169774254652b..ee9239c9b9b42b99dc68410150643bea1f69b72b 100644
--- a/Code/Mantid/instrument/TOSCA_Parameters.xml
+++ b/Code/Mantid/instrument/TOSCA_Parameters.xml
@@ -24,6 +24,9 @@
     <parameter name="cm-1-convert-choice" type="string">
       <value val="true" />
     </parameter>
+    <parameter name="save-nexus-choice" type="string">
+      <value val="false" />
+    </parameter>
     <parameter name="save-ascii-choice" type="string">
       <value val="true" />
     </parameter>
diff --git a/Code/Mantid/instrument/TOSCA_Parameters_TOSCA-1.xml b/Code/Mantid/instrument/TOSCA_Parameters_TOSCA-1.xml
index ef7ed1a7cbed5445eabd57a6a9e37ad0ada6bf73..83974f47b014b3b6ff5e3f86173da73debba869c 100644
--- a/Code/Mantid/instrument/TOSCA_Parameters_TOSCA-1.xml
+++ b/Code/Mantid/instrument/TOSCA_Parameters_TOSCA-1.xml
@@ -22,10 +22,13 @@
 
     <!-- Available options are "Show" or "Hide". -->
     <parameter name="cm-1-convert-choice" type="string">
-      <value val="Show" />
+      <value val="true" />
+    </parameter>
+    <parameter name="save-nexus-choice" type="string">
+      <value val="false" />
     </parameter>
-    <parameter name="save-aclimax-choice" type="string">
-      <value val="Show" />
+    <parameter name="save-ascii-choice" type="string">
+      <value val="true" />
     </parameter>
     <parameter name="fold-frames-choice" type="string">
       <value val="true" />
diff --git a/Code/Mantid/instrument/TOSCA_graphite_002_Parameters.xml b/Code/Mantid/instrument/TOSCA_graphite_002_Parameters.xml
index 6a063db5ac1c78b5f868dcfdca1f3323ae1f5a41..8b6f3b861448fea7a8e47cddfe432816fbbad02a 100644
--- a/Code/Mantid/instrument/TOSCA_graphite_002_Parameters.xml
+++ b/Code/Mantid/instrument/TOSCA_graphite_002_Parameters.xml
@@ -1,40 +1,36 @@
 <?xml version="1.0" encoding="UTF-8" ?>
 <parameter-file instrument = "TOSCA" valid-from = "2011-01-19T00:00:00">
 
-<component-link name = "TOSCA">
+  <component-link name = "TOSCA">
 
-<parameter name="analysis-type" type="string">
-  <value val="spectroscopy" />
-</parameter>
+    <parameter name="analysis-type" type="string">
+      <value val="spectroscopy" />
+    </parameter>
 
-<parameter name="spectra-min">
-	<value val="1" />
-</parameter>
+    <parameter name="spectra-min">
+      <value val="1" />
+    </parameter>
 
-<parameter name="spectra-max">
-	<value val="140" />
-</parameter>
+    <parameter name="spectra-max">
+      <value val="140" />
+    </parameter>
 
-<parameter name="efixed-val">
-	<value val="0" />
-</parameter>
+    <parameter name="peak-start">
+      <value val="0" />
+    </parameter>
 
-<parameter name="peak-start">
-	<value val="0" />
-</parameter>
+    <parameter name="peak-end">
+      <value val="0" />
+    </parameter>
 
-<parameter name="peak-end">
-	<value val="0" />
-</parameter>
+    <parameter name="back-start">
+      <value val="0" />
+    </parameter>
 
-<parameter name="back-start">
-	<value val="0" />
-</parameter>
+    <parameter name="back-end">
+      <value val="0" />
+    </parameter>
 
-<parameter name="back-end">
-	<value val="0" />
-</parameter>
+  </component-link>
 
-</component-link>
-
-</parameter-file>
\ No newline at end of file
+</parameter-file>
diff --git a/Code/Mantid/instrument/VISION_graphite_002_Parameters.xml b/Code/Mantid/instrument/VISION_graphite_002_Parameters.xml
index 706e53d59d3e6e66b44f277d3e94c5c0f68c06e7..368ae467aadd50abd25d78d7b5f0b8272602d622 100644
--- a/Code/Mantid/instrument/VISION_graphite_002_Parameters.xml
+++ b/Code/Mantid/instrument/VISION_graphite_002_Parameters.xml
@@ -7,9 +7,9 @@
   <value val="spectroscopy" />
 </parameter>
 
-<!-- 
-This Min/Max approach doesn't work for instruments with gaps 
-in the detector numbering! 
+<!--
+This Min/Max approach doesn't work for instruments with gaps
+in the detector numbering!
 -->
 <parameter name="spectra-min">
 	<value val="1" />
diff --git a/Code/Mantid/instrument/nexusdictionaries/poldi.dic b/Code/Mantid/instrument/nexusdictionaries/poldi.dic
index d54f592483a7b8c3f1329ebb55fc4b64eb3d4d74..debe21d9ef5b78432aa8df5885bbcd6839da7ce7 100644
--- a/Code/Mantid/instrument/nexusdictionaries/poldi.dic
+++ b/Code/Mantid/instrument/nexusdictionaries/poldi.dic
@@ -1,12 +1,9 @@
-data=/entry1/detector/counts
-x-axis=/entry1/detector/time_binning
+data=/entry1/detector_1/counts
+x-axis=/entry1/detector_1/time_binning
 x-axis-name=time-of-flight
 title=/entry1/title
-det2theta=/entry1/detector/2theta
 sample=/entry1/sample/name
-sample_distance=/entry1/sample/distance1
 chopperspeed=/entry1/POLDI/chopper/rotation_speed
-monitor=/entry1/POLDI/detector/monitor
 #
 #
 FacilityName=/entry1/POLDI/SINQ/name
@@ -16,38 +13,20 @@ InstrumentName=/entry1/POLDI/name
 #
 ExperimentName=/entry1/title
 StartTime=/entry1/start_time
-#
-#ProtonMonitor=/entry1/proton_monitor/data
-#
-DetdRes=/entry1/POLDI/detector/d_resolution
-DetRadius=/entry1/POLDI/detector/det_radius
-DetDistance=/entry1/POLDI/detector/distance
-DetMonitor=/entry1/POLDI/detector/monitor
-DetPreset=/entry1/POLDI/detector/preset
-DetScattAngle=/entry1/POLDI/detector/scatt_angle
-DetTime=/entry1/POLDI/detector/time
-DetTwoTheta=/entry1/POLDI/detector/twotheta
-Detx0=/entry1/POLDI/detector/x0
-Dety0=/entry1/POLDI/detector/y0
-#
-Diaphragm1Dist=/entry1/POLDI/diaphragm1/distance
-Diaphragm1x=/entry1/POLDI/diaphragm1/x
-Diaphragm1x0=/entry1/POLDI/diaphragm1/x_zero
-Diaphragm1y=/entry1/POLDI/diaphragm1/y
-Diaphragm1y0=/entry1/POLDI/diaphragm1/y_zero
-#
-Diaphragme2Dist=/entry1/POLDI/diaphragm2/distance
-Diaphragme2xminus=/entry1/POLDI/diaphragm2/x_minus
-Diaphragme2xplus=/entry1/POLDI/diaphragm2/x_plus
-Diaphragme2xminus0=/entry1/POLDI/diaphragm2/xminus_zero
-Diaphragme2xplus0=/entry1/POLDI/diaphragm2/xplus_zero
-Diaphragme2zminus=/entry1/POLDI/diaphragm2/z_minus
-Diaphragme2zminus0=/entry1/POLDI/diaphragm2/z_minus_zero
-Diaphragme2plus=/entry1/POLDI/diaphragm2/z_plus
-Diaphragme2plus0=/entry1/POLDI/diaphragm2/zplus_zero
+DetRadius=/entry1/POLDI/detector_1/det_radius
+DetDistance=/entry1/POLDI/detector_1/distance
+DetMonitor=/entry1/POLDI/detector_1/monitor
+DetPreset=/entry1/POLDI/detector_1/preset
+DetScattAngle=/entry1/POLDI/detector_1/twotheta_detector
+DetTime=/entry1/POLDI/detector_1/time
+DetTwoTheta=/entry1/POLDI/detector_1/polar_angle
+Detx0=/entry1/POLDI/detector_1/x_pixel_offset
+Dety0=/entry1/POLDI/detector_1/y_pixel_offset
+
 #
 ChopperName=/entry1/POLDI/chopper/name
-ChopperPhase=/entry1/POLDI/chopper/chopper_phase
+ChopperDistance=/entry1/POLDI/chopper/distance
+ChopperParkingPosition=/entry1/POLDI/chopper/parking_position
 ChopperSpeed=/entry1/POLDI/chopper/rotation_speed
 
 # There seems to be an issue with this field in some data files.
@@ -57,7 +36,3 @@ ChopperSpeed=/entry1/POLDI/chopper/rotation_speed
 SampleName=/entry1/POLDI/name
 #
 start_time=/entry1/start_time
-#
-TablePositionX=/entry1/sample/sample_x
-TablePositionY=/entry1/sample/sample_y
-TablePositionZ=/entry1/sample/sample_lift
\ No newline at end of file
diff --git a/Code/Mantid/instrument/nexusdictionaries/poldi_legacy.dic b/Code/Mantid/instrument/nexusdictionaries/poldi_legacy.dic
new file mode 100644
index 0000000000000000000000000000000000000000..3dc18437eff5ea7181a8f7df42dd1ea9b905f56d
--- /dev/null
+++ b/Code/Mantid/instrument/nexusdictionaries/poldi_legacy.dic
@@ -0,0 +1,66 @@
+# This file defines the format of POLDI files before the 2015 cycle.
+# For the currently valid definition see poldi.dic in this directory.
+#
+data=/entry1/detector/counts
+x-axis=/entry1/detector/time_binning
+x-axis-name=time-of-flight
+title=/entry1/title
+det2theta=/entry1/detector/2theta
+sample=/entry1/sample/name
+sample_distance=/entry1/sample/distance1
+chopperspeed=/entry1/POLDI/chopper/rotation_speed
+monitor=/entry1/POLDI/detector/monitor
+#
+#
+FacilityName=/entry1/POLDI/SINQ/name
+FacilityType=/entry1/POLDI/SINQ/type
+#
+InstrumentName=/entry1/POLDI/name
+#
+ExperimentName=/entry1/title
+StartTime=/entry1/start_time
+#
+#ProtonMonitor=/entry1/proton_monitor/data
+#
+DetdRes=/entry1/POLDI/detector/d_resolution
+DetRadius=/entry1/POLDI/detector/det_radius
+DetDistance=/entry1/POLDI/detector/distance
+DetMonitor=/entry1/POLDI/detector/monitor
+DetPreset=/entry1/POLDI/detector/preset
+DetScattAngle=/entry1/POLDI/detector/scatt_angle
+DetTime=/entry1/POLDI/detector/time
+DetTwoTheta=/entry1/POLDI/detector/twotheta
+Detx0=/entry1/POLDI/detector/x0
+Dety0=/entry1/POLDI/detector/y0
+#
+Diaphragm1Dist=/entry1/POLDI/diaphragm1/distance
+Diaphragm1x=/entry1/POLDI/diaphragm1/x
+Diaphragm1x0=/entry1/POLDI/diaphragm1/x_zero
+Diaphragm1y=/entry1/POLDI/diaphragm1/y
+Diaphragm1y0=/entry1/POLDI/diaphragm1/y_zero
+#
+Diaphragme2Dist=/entry1/POLDI/diaphragm2/distance
+Diaphragme2xminus=/entry1/POLDI/diaphragm2/x_minus
+Diaphragme2xplus=/entry1/POLDI/diaphragm2/x_plus
+Diaphragme2xminus0=/entry1/POLDI/diaphragm2/xminus_zero
+Diaphragme2xplus0=/entry1/POLDI/diaphragm2/xplus_zero
+Diaphragme2zminus=/entry1/POLDI/diaphragm2/z_minus
+Diaphragme2zminus0=/entry1/POLDI/diaphragm2/z_minus_zero
+Diaphragme2plus=/entry1/POLDI/diaphragm2/z_plus
+Diaphragme2plus0=/entry1/POLDI/diaphragm2/zplus_zero
+#
+ChopperName=/entry1/POLDI/chopper/name
+ChopperPhase=/entry1/POLDI/chopper/chopper_phase
+ChopperSpeed=/entry1/POLDI/chopper/rotation_speed
+
+# There seems to be an issue with this field in some data files.
+# Once this is fixed, it can be reactivated.
+#ChopperSpeedTarget=/entry1/POLDI/chopper/rotation_speed_target
+#
+SampleName=/entry1/POLDI/name
+#
+start_time=/entry1/start_time
+#
+TablePositionX=/entry1/sample/sample_x
+TablePositionY=/entry1/sample/sample_y
+TablePositionZ=/entry1/sample/sample_lift
\ No newline at end of file
diff --git a/Code/Mantid/scripts/CMakeLists.txt b/Code/Mantid/scripts/CMakeLists.txt
index 55446b99d190f46bc1d7bbd54614ecad2f031168..780c6178ee132377ee0722f433dc0f8f34ed5c6b 100644
--- a/Code/Mantid/scripts/CMakeLists.txt
+++ b/Code/Mantid/scripts/CMakeLists.txt
@@ -10,6 +10,7 @@ set ( TEST_PY_FILES
       test/ReflectometryQuickAuxiliaryTest.py 
       test/RunDescriptorTest.py
       test/SansIsisGuiSettings.py
+      test/SANSUtilitytests.py
       test/SettingsTest.py      
       test/ReductionSettingsTest.py
       )
diff --git a/Code/Mantid/scripts/CrystalTools/PeakReport.py b/Code/Mantid/scripts/CrystalTools/PeakReport.py
index c7a28c6c3e59f6f86b21662da6c0af9a564b1cfd..f4b031dac0f5cd14b90a22ee4f383f4e1f0b5656 100644
--- a/Code/Mantid/scripts/CrystalTools/PeakReport.py
+++ b/Code/Mantid/scripts/CrystalTools/PeakReport.py
@@ -35,9 +35,9 @@ class PeakReport(object):
 
     def clean_files(self):
         # Clean up generated image files
-        for file in self.__image_files:
-            os.remove(file)
-            self.__image_files.remove(file)
+        for ifile in self.__image_files:
+            os.remove(ifile)
+            self.__image_files.remove(ifile)
 
     def __del__(self):
         self.clean_files()
@@ -100,7 +100,8 @@ class PeakReport(object):
         if  not pdf_name:
             pdf_name = md_workspace.name() + 'IntegrationReport.pdf'
 
-        doc = SimpleDocTemplate(self.__out_location +  pdf_name, pagesize=letter, leftMargin=2, rightMargin=2, topMargin=2.5, bottomMargin=2 ,showBoundary=1)
+        doc = SimpleDocTemplate(self.__out_location +  pdf_name, pagesize=letter, leftMargin=2, rightMargin=2,
+                                topMargin=2.5, bottomMargin=2 ,showBoundary=1)
         parts = list()
         styles = getSampleStyleSheet()
         title = Paragraph("Peak Integration Report for %s" % md_workspace.name(), styles["Heading1"], )
@@ -144,8 +145,10 @@ class PeakReport(object):
             # Get the peak object
             peak = peaks_workspace.getPeak(i)
 
-            infoData = [['PeakNumber:', i],['Run Number:', peak.getRunNumber()], ['Intensity:', peak.getIntensity()], ['TOF:', peak.getTOF()]]
-            coordData = [['Detector Id:', peak.getDetectorID()], ['Q Lab:', peak.getQLabFrame()], ['Q Sample:', peak.getQSampleFrame()], ['HKL:', peak.getHKL()]]
+            infoData = [['PeakNumber:', i],['Run Number:', peak.getRunNumber()], ['Intensity:', peak.getIntensity()],
+                        ['TOF:', peak.getTOF()]]
+            coordData = [['Detector Id:', peak.getDetectorID()], ['Q Lab:', peak.getQLabFrame()],
+                         ['Q Sample:', peak.getQSampleFrame()], ['HKL:', peak.getHKL()]]
             data = [[ img , Table(infoData), Table(coordData)]]
 
             colwidths = (150, 160, 160)
diff --git a/Code/Mantid/scripts/DGSPlanner/DGSPlannerGUI.py b/Code/Mantid/scripts/DGSPlanner/DGSPlannerGUI.py
index 7c89cb9629267c93ac83b2c621be16420555c18e..8c5d0a5cc2d2a9628c52824ccec5c68e41ec16d2 100644
--- a/Code/Mantid/scripts/DGSPlanner/DGSPlannerGUI.py
+++ b/Code/Mantid/scripts/DGSPlanner/DGSPlannerGUI.py
@@ -38,10 +38,9 @@ class DGSPlannerGUI(QtGui.QWidget):
         controlLayout.addWidget(self.instrumentWidget)
         self.ublayout=QtGui.QHBoxLayout()
         self.classic=ClassicUBInputWidget.ClassicUBInputWidget(self.ol)
-        self.ublayout.addWidget(self.classic)
+        self.ublayout.addWidget(self.classic,alignment=QtCore.Qt.AlignTop,stretch=1)
         self.matrix=MatrixUBInputWidget.MatrixUBInputWidget(self.ol)
-        self.ublayout.addStretch(1)
-        self.ublayout.addWidget(self.matrix)
+        self.ublayout.addWidget(self.matrix,alignment=QtCore.Qt.AlignTop,stretch=1)
         controlLayout.addLayout(self.ublayout)
         self.dimensionWidget=DimensionSelectorWidget.DimensionSelectorWidget(self)
         controlLayout.addWidget(self.dimensionWidget)
diff --git a/Code/Mantid/scripts/DGSPlanner/InstrumentSetupWidget.py b/Code/Mantid/scripts/DGSPlanner/InstrumentSetupWidget.py
index 51de7ddea24e269d5d79b52d527d8c8e22ae4c6f..f05ec54cbfef436f1e053026f88cba90c1eb5d79 100644
--- a/Code/Mantid/scripts/DGSPlanner/InstrumentSetupWidget.py
+++ b/Code/Mantid/scripts/DGSPlanner/InstrumentSetupWidget.py
@@ -5,7 +5,7 @@ import mantid
 import numpy
 import matplotlib
 matplotlib.use('Qt4Agg')
-matplotlib.rcParams['backend.qt4']='PyQt4' 
+matplotlib.rcParams['backend.qt4']='PyQt4'
 from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
 from matplotlib.figure import Figure
 from mpl_toolkits.mplot3d import Axes3D
diff --git a/Code/Mantid/scripts/FilterEvents/Ui_ErrorMessage.py b/Code/Mantid/scripts/FilterEvents/Ui_ErrorMessage.py
index 19d9b11778f4dc8a5c6668166f6846e7e5e52a02..797064eeeb6319194c1b86bbd89768d111b25b61 100644
--- a/Code/Mantid/scripts/FilterEvents/Ui_ErrorMessage.py
+++ b/Code/Mantid/scripts/FilterEvents/Ui_ErrorMessage.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,line-too-long,too-many-instance-attributes
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'ErrorMessage.ui'
diff --git a/Code/Mantid/scripts/FilterEvents/Ui_MainWindow.py b/Code/Mantid/scripts/FilterEvents/Ui_MainWindow.py
index dce63f3d90f9fb60e357a51b6909b077edfd07a4..ee26094c1a816eba014015c2cbeb8486a3778603 100644
--- a/Code/Mantid/scripts/FilterEvents/Ui_MainWindow.py
+++ b/Code/Mantid/scripts/FilterEvents/Ui_MainWindow.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name,attribute-defined-outside-init
+#pylint: disable=invalid-name,attribute-defined-outside-init,too-many-locals, too-many-statements,too-many-instance-attributes,line-too-long
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'MainWindow.ui'
diff --git a/Code/Mantid/scripts/FilterEvents/eventFilterGUI.py b/Code/Mantid/scripts/FilterEvents/eventFilterGUI.py
index eec342adbde464590c847830ec922310f2a7260b..c065473b1188eeaa872b83ec073d038986c68369 100644
--- a/Code/Mantid/scripts/FilterEvents/eventFilterGUI.py
+++ b/Code/Mantid/scripts/FilterEvents/eventFilterGUI.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name, too-many-lines, too-many-instance-attributes
 import numpy
 
 from FilterEvents.Ui_MainWindow import Ui_MainWindow #import line for the UI python class
@@ -292,8 +292,6 @@ class MainWindow(QtGui.QMainWindow):
     def computeMock(self):
         """ Compute vecx and vecy as mocking
         """
-        import random, math
-
         x0 = 0.
         xf = 1.
         dx = 0.1
@@ -672,10 +670,10 @@ class MainWindow(QtGui.QMainWindow):
         filename = str(self.ui.lineEdit.text())
 
         # Find out it is relative path or absolute path
-        if os.path.abspath(filename) == filename:
-            isabspath = True
-        else:
-            isabspath = False
+        #if os.path.abspath(filename) == filename:
+        #    isabspath = True
+        #else:
+        #    isabspath = False
 
         dataws = self._loadFile(str(filename))
         if dataws is None:
@@ -1018,12 +1016,6 @@ class MainWindow(QtGui.QMainWindow):
 
         title = str(self.ui.lineEdit_title.text())
 
-        """ Debug
-        for k in kwargs.keys():
-            print k, kwargs[k], type(kwargs[k])
-        print "Input workspace = ", str(self._dataWS)
-         END DB """
-
         splitws, infows = api.GenerateEventsFilter(\
                 InputWorkspace      = self._dataWS,\
                 UnitOfTime          = "Seconds",\
@@ -1171,7 +1163,7 @@ class MainWindow(QtGui.QMainWindow):
         tablewsnames = []
         for wsname in wsnames:
             wksp = AnalysisDataService.retrieve(wsname)
-            if isinstance(wksp, mantid.api._api.ITableWorkspace):
+            if isinstance(wksp, mantid.api.ITableWorkspace):
                 tablewsnames.append(wsname)
         # ENDFOR
 
diff --git a/Code/Mantid/scripts/HFIRPowderReduction/HfirPDReductionControl.py b/Code/Mantid/scripts/HFIRPowderReduction/HfirPDReductionControl.py
new file mode 100644
index 0000000000000000000000000000000000000000..88226ad34a11c22924985cfd96d86437d97978f3
--- /dev/null
+++ b/Code/Mantid/scripts/HFIRPowderReduction/HfirPDReductionControl.py
@@ -0,0 +1,1038 @@
+#pylint: disable=too-many-lines,relative-import,invalid-name,too-many-instance-attributes,too-many-arguments
+############################################################################
+#
+# HFIR powder reduction control class
+# Key Words: FUTURE
+#
+############################################################################
+import sys
+import os
+import urllib2
+import math
+
+import numpy
+
+import HfirUtility as hutil
+
+# Import mantid
+curdir = os.getcwd()
+libpath = os.path.join(curdir.split('Code')[0], 'Code/debug/bin')
+if os.path.exists(libpath) is False:
+    libpath = os.path.join(curdir.split('Code')[0], 'Code/release/bin')
+sys.path.append(libpath)
+import mantid.simpleapi as api
+from mantid.simpleapi import AnalysisDataService
+#from mantid.kernel import ConfigService
+
+
+VanadiumPeakPositions = [0.5044,0.5191,0.5350,0.5526,0.5936,0.6178,0.6453,0.6768,
+        0.7134,0.7566,0.8089,0.8737,0.9571,1.0701,1.2356,1.5133,2.1401]
+
+class PDRManager(object):
+    """ Powder diffraction reduction workspace manager
+    """
+    def __init__(self, exp, scan):
+        """ Initialization
+        """
+        try:
+            self.exp = int(exp)
+            self.scan = int(scan)
+        except ValueError:
+            raise NotImplementedError("Set non-integer value as Exp and Scan to PDRManager.")
+
+        self.unit = None
+        self.datamdws = None
+        self.monitormdws = None
+        self.reducedws = None
+        self.binsize = 1E10
+
+        self._rawSpiceTableWS = None
+        self._rawLogInfoWS = None
+
+        # vanadium only
+        self._processedVanWS = None
+        self._processedVanWSTemp = None
+        self._processVanNote = ""
+        self._applySmoothVan = False
+        self._vanadiumPeakPosList = []
+
+        self._wavelength = None
+
+        return
+
+    def applySmoothVanadium(self, smoothaccept):
+        """ Apply the smoothing effect of to vanadium data
+        """
+        if isinstance(smoothaccept, bool) is False:
+            raise NotImplementedError('Input for applySmoothVanadium() is not boolean!')
+
+        self._applySmoothVan = smoothaccept
+
+        return
+
+    def getProcessedVanadiumWS(self):
+        """
+        """
+        return self._processedVanWS
+
+    def getProcessedVanadiumWSTemp(self):
+        """
+        """
+        return self._processedVanWSTemp
+
+
+    def getRawSpiceTable(self):
+        """
+        """
+        return self._rawSpiceTableWS
+
+
+    def getRawInfoMatrixWS(self):
+        """
+        """
+        return self._rawLogInfoWS
+
+
+    def getVanadiumPeaks(self):
+        """
+        """
+        return self._vanadiumPeakPosList[:]
+
+
+    def getWavelength(self):
+        """
+        """
+        return self._wavelength
+
+    def isSmoothApplied(self):
+        """
+        """
+        return self._applySmoothVan
+
+    def setup(self, datamdws, monitormdws, reducedws=None, unit=None, binsize=None):
+        """ Set up
+        """
+        self.datamdws = datamdws
+        self.monitormdws = monitormdws
+        if reducedws is not None:
+            self.reducedws = reducedws
+        if unit is not None:
+            self.unit = unit
+        try:
+            self.binsize = float(binsize)
+        except TypeError as e:
+            print e
+
+        return
+
+    def setRawWorkspaces(self, spicetablews, logmatrixws):
+        """ Set 2 raw SPICE workspaces
+        """
+        # Validate
+        if  spicetablews.id() != 'TableWorkspace' or logmatrixws.id() != 'Workspace2D':
+            raise NotImplementedError("Input workspaces for setRawWorkspaces() are not of correct types.")
+
+        self._rawSpiceTableWS =  spicetablews
+        self._rawLogInfoWS = logmatrixws
+
+        return
+
+    def setupMDWrokspaces(self, datamdws, monitormdws):
+        """
+        """
+        self.datamdws = datamdws
+        self.monitormdws = monitormdws
+
+        return
+
+    def setProcessedVanadiumData(self, wksp):
+        """ Set tempory processed vanadium data
+        Arguments:
+         - vanws :: workspace
+         - note  :: string as note
+        """
+        self._processedVanWS = wksp
+
+        return
+
+    def setProcessedVanadiumDataTemp(self, vanws, note):
+        """ Set tempory processed vanadium data
+        Arguments:
+         - vanws :: workspace
+         - note  :: string as note
+        """
+        self._processedVanWSTemp = vanws
+        self._processVanNote = note
+
+        return
+
+    def setVanadiumPeaks(self, vanpeakposlist):
+        """ Set up vanadium peaks in 2theta
+        """
+        # Validate input
+        if isinstance(vanpeakposlist, list) is False:
+            raise NotImplementedError("Input must be a list.  Now it it is %s." % (str(type(vanpeakposlist))))
+        elif len(vanpeakposlist) == 0:
+            raise NotImplementedError("Input must be a non-empty list.")
+
+        vanpeakposlist = sorted(vanpeakposlist)
+        if vanpeakposlist[0] < 5.:
+            raise NotImplementedError("Check whether the list %s is in unit of 2theta" % (str(vanpeakposlist)))
+
+        # Set up
+        self._vanadiumPeakPosList = vanpeakposlist[:]
+
+        return
+
+
+    def setWavelength(self, wavelength):
+        """ Set wavelength for this run
+        """
+        self._wavelength = float(wavelength)
+        if wavelength <= 0:
+            raise NotImplementedError("It is not physical to have negative neutron wavelength")
+
+        return
+
+#pylint: disable=too-many-public-methods
+class HFIRPDRedControl(object):
+    """ Class for controlling HFIR powder reduction
+    """
+    def __init__(self):
+        """ Initialization
+        """
+        self._myWorkspaceDict = {}  # dictionary to manage all the workspaces reduced
+                                    # key = Exp/Scan
+        self._myMergedWSDict = {}   # key = Exp/Scan list
+
+        self._myWavelengthDict = {}
+
+        self._lastWkspToMerge = []
+
+        return
+
+    def applySmoothVanadium(self, expno, scanno, applysmooth):
+        """ Apply smoothed vanadium
+        """
+        if self._myWorkspaceDict.has_key((expno, scanno)) is False:
+            raise NotImplementedError("Exp %d Scan %d does not have reduced \
+                    workspace." % (exp, scan))
+        else:
+            rmanager = self._myWorkspaceDict[(expno, scanno)]
+            rmanager.applySmoothVanadium(applysmooth)
+
+        return
+
+
+    def getIndividualDetCounts(self, exp, scan, detid, xlabel):
+        """ Get individual detector counts
+        """
+        # Check and get data
+        exp = int(exp)
+        scan = int(scan)
+        detid = int(detid)
+
+        if self._myWorkspaceDict.has_key((exp, scan)) is False:
+            raise NotImplementedError("Exp %d Scan %d does not have reduced \
+                    workspace." % (exp, scan))
+        else:
+            rmanager = self._myWorkspaceDict[(exp, scan)]
+
+            datamdws = rmanager.datamdws
+            monitormdws = rmanager.monitormdws
+
+            if datamdws is None or monitormdws is None:
+                raise NotImplementedError('Reduction manager has no MDEventWorkspaces setup.')
+        # END-IF-ELSE
+
+        # Get raw counts
+        # FUTURE: use **args
+        if xlabel is None:
+            tempoutws = \
+                    api.GetSpiceDataRawCountsFromMD(InputWorkspace=datamdws,
+                                                    MonitorWorkspace=monitormdws,
+                                                    Mode='Detector',
+                                                    DetectorID = detid)
+        else:
+            tempoutws = \
+                    api.GetSpiceDataRawCountsFromMD(InputWorkspace=datamdws,
+                                                    MonitorWorkspace=monitormdws,
+                                                    Mode='Detector',
+                                                    DetectorID = detid,
+                                                    XLabel=xlabel)
+
+        vecx = tempoutws.readX(0)[:]
+        vecy = tempoutws.readY(0)[:]
+
+        return (vecx, vecy)
+
+
+    def getRawDetectorCounts(self, exp, scan, ptnolist=None):
+        """ Return raw detector counts as a list of 3-tuples
+        """
+        # Check and get data
+        exp = int(exp)
+        scan = int(scan)
+
+        if self._myWorkspaceDict.has_key((exp, scan)) is False:
+            raise NotImplementedError("Exp %d Scan %d does not have reduced \
+                    workspace." % (exp, scan))
+        else:
+            rmanager = self._myWorkspaceDict[(exp, scan)]
+            datamdws = rmanager.datamdws
+            monitormdws = rmanager.monitormdws
+
+            if datamdws is None or monitormdws is None:
+                raise NotImplementedError('Reduction manager has no MDEventWorkspaces setup.')
+        # END-IF-ELSE
+
+        # get the complete list of Pt. number
+        if ptnolist is None:
+            ptnolist = self._getRunNumberList(datamdws=rmanager.datamdws)
+
+        rlist = []
+        # Loop over all Pt. number
+        for ptno in ptnolist:
+            # get data
+            tempoutws = api.GetSpiceDataRawCountsFromMD(InputWorkspace=datamdws,
+                                                        MonitorWorkspace=monitormdws,
+                                                        Mode='Pt.',
+                                                        Pt = ptno)
+
+            vecx = tempoutws.readX(0)[:]
+            vecy = tempoutws.readY(0)[:]
+
+            rlist.append((ptno, vecx, vecy))
+        # ENDFOR
+
+        return rlist
+
+
+    def getSampleLogNames(self, expno, scanno):
+        """ Get the list of sample logs' names if they are
+        of float data type
+        """
+        # check
+        if self._myWorkspaceDict.has_key((expno, scanno)) is False:
+            raise NotImplementedError("Exp %d Scan %d does not have reduced \
+                    workspace." % (exp, scan))
+
+        # get data
+        rmanager = self._myWorkspaceDict[(expno, scanno)]
+        datamdws = rmanager.datamdws
+
+        info0 = datamdws.getExperimentInfo(0)
+        run = info0.run()
+        plist = run.getProperties()
+        lognamelist = []
+        for prop in plist:
+            if prop.__class__.__name__.lower().count('float') == 1:
+                lognamelist.append(prop.name)
+
+        return lognamelist
+
+
+    def getSampleLogValue(self, expno, scanno, samplelogname, xlabel):
+        """ Get vecx and vecy for sample log
+        """
+        # Check and get data
+        exp = int(expno)
+        scan = int(scanno)
+
+        if self._myWorkspaceDict.has_key((exp, scan)) is False:
+            raise NotImplementedError("Exp %d Scan %d does not have reduced \
+                    workspace." % (exp, scan))
+        else:
+            rmanager = self._myWorkspaceDict[(exp, scan)]
+            datamdws = rmanager.datamdws
+            monitormdws = rmanager.monitormdws
+
+            if datamdws is None or monitormdws is None:
+                raise NotImplementedError('Reduction manager has no MDEventWorkspaces setup.')
+        # END-IF-ELSE
+
+        # get the complete list of Pt. number
+        # ptnolist = self._getRunNumberList(datamdws=rmanager.datamdws)
+
+        # get data
+        tempoutws = api.GetSpiceDataRawCountsFromMD(InputWorkspace=datamdws,
+                                                    MonitorWorkspace=monitormdws,
+                                                    Mode='Sample Log',
+                                                    SampleLogName=samplelogname,
+                                                    XLabel=xlabel)
+
+        vecx = tempoutws.readX(0)[:]
+        vecy = tempoutws.readY(0)[:]
+
+        return (vecx, vecy)
+
+
+
+    def getVectorToPlot(self, exp, scan):
+        """ Get vec x and vec y of the reduced workspace to plot
+        """
+        # get on hold of reduced workspace
+        wsmanager = self.getWorkspace(exp, scan, raiseexception=True)
+        reducedws = wsmanager.reducedws
+        if reducedws is None:
+            raise NotImplementedError("Exp %d Scan %d does not have reduced workspace." % (exp, scan))
+
+        # convert to point data if necessary
+        if len(reducedws.readX(0)) != len(reducedws.readY(0)):
+            wsname = reducedws.name() + "_pd"
+            api.ConvertToPointData(InputWorkspace=reducedws, OutputWorkspace=wsname)
+            outws = AnalysisDataService.retrieve(wsname)
+        else:
+            outws = reducedws
+
+        # get vectors
+        return outws.readX(0), outws.readY(0)
+
+
+    def getVectorProcessVanToPlot(self, exp, scan, tempdata=False):
+        """ Get vec x and y for the processed vanadium spectrum
+        """
+        # get on hold of processed vanadium data workspace
+        wsmanager = self.getWorkspace(exp, scan, raiseexception=True)
+
+        if tempdata is True:
+            procVanWs = wsmanager.getProcessedVanadiumWSTemp()
+        else:
+            procVanWs = wsmanager.getProcessedVanadiumWS()
+            #procVanWs = wsmanager._processedVanWS
+
+        if procVanWs is None:
+            raise NotImplementedError("Exp %d Scan %d does not have processed vanadium workspace." % (exp, scan))
+
+        # convert to point data if necessary
+        if len(procVanWs.readX(0)) != len(procVanWs.readY(0)):
+            wsname = procVanWs.name() + "_pd"
+            api.ConvertToPointData(InputWorkspace=procVanWs, OutputWorkspace=wsname)
+            outws = AnalysisDataService.retrieve(wsname)
+        else:
+            outws = procVanWs
+
+        # get vectors
+        return outws.readX(0), outws.readY(0)
+
+
+    def getMergedVector(self, mkey):
+        """ Get vector X and Y from merged scans
+        """
+        if self._myMergedWSDict.has_key(mkey) is True:
+            wksp = self._myMergedWSDict[mkey]
+
+            # convert to point data if necessary
+            if len(wksp.readX(0)) != len(wksp.readY(0)):
+                wsname = wksp.name() + "_pd"
+                api.ConvertToPointData(InputWorkspace=wksp, OutputWorkspace=wsname)
+                wksp = AnalysisDataService.retrieve(wsname)
+
+            vecx = wksp.readX(0)
+            vecy = wksp.readY(0)
+        else:
+            raise NotImplementedError("No merged workspace for key = %s." % (str(mkey)))
+
+        return (vecx, vecy)
+
+
+    def getVanadiumPeaksPos(self, exp, scan):
+        """ Convert vanadium peaks from d-spacing to 2theta
+        Arguments
+         - exp
+         - scan
+
+        Return :: list of peak positions in 2-theta (Degrees)
+        """
+        wsmanager = self.getWorkspace(exp, scan, raiseexception=True)
+        if wsmanager.datamdws is None:
+            self._logError("Unable to rebin the data for exp=%d, scan=%d because either data MD workspace and \
+                monitor MD workspace is not present."  % (exp, scan))
+            return False
+
+        wavelength = wsmanager.getWavelength()
+
+        # Convert the vanadium peaks' position from dSpacing to 2theta
+        vanpeakpos2theta = []
+        for peakpos in VanadiumPeakPositions:
+            lambda_over_2d =  wavelength/2./peakpos
+            if abs(lambda_over_2d) <= 1.:
+                twotheta = math.asin(lambda_over_2d)*2.*180/math.pi
+                vanpeakpos2theta.append(twotheta)
+            else:
+                print "Vanadium peak %f is out of d-Spacing range." % (peakpos)
+
+        vanpeakpos2theta = sorted(vanpeakpos2theta)
+        wsmanager.setVanadiumPeaks(vanpeakpos2theta)
+
+        return vanpeakpos2theta
+
+    def getWavelength(self, exp, scan):
+        """ Get wavelength
+        """
+        exp = int(exp)
+        scan = int(scan)
+        return self._myWavelengthDict[(exp, scan)]
+
+    def getWkspToMerge(self):
+        """ Get the individual workspaces that are used for merging in the last
+        merging-run activities
+        """
+        wslist = []
+        for wsmanager in self._lastWkspToMerge:
+            outws = wsmanager.reducedws
+            wslist.append(outws)
+        # ENDFOR (wsmanager)
+
+        return wslist
+
+
+    def getWorkspace(self, exp, scan, raiseexception):
+        """
+        """
+        # get on hold of data
+        if self._myWorkspaceDict.has_key((exp, scan)) is False:
+            if raiseexception is True:
+                raise NotImplementedError("Exp %d Scan %d has not been processed. " % (exp, scan))
+            else:
+                return None
+        # ENDIF
+
+        return self._myWorkspaceDict[(exp, scan)]
+
+
+    def hasDataLoaded(self, exp, scan):
+        """ Check whether an experiment data set (defined by exp No. and scan No.)
+        has been loaded or not.
+        """
+        if self._myWorkspaceDict.has_key((exp, scan)):
+            return True
+        else:
+            return False
+
+
+    def hasReducedWS(self, exp, scan):
+        """ Check whether an Exp/Scan has a reduced workspace
+        """
+        if self._myWorkspaceDict.has_key((exp, scan)) is False:
+            print self._myWorkspaceDict.keys()
+            return False
+
+        if self._myWorkspaceDict[(exp, scan)].reducedws is None:
+            return False
+
+        return True
+
+
+    def loadSpicePDData(self, expno, scanno, datafilename):
+        """ Load SPICE powder diffraction data to MDEventsWorkspaces
+        """
+        # Create base workspace name
+        try:
+            basewsname = os.path.basename(datafilename).split(".")[0]
+        except AttributeError as e:
+            raise NotImplementedError("Unable to parse data file name due to %s." % (str(e)))
+
+        # load SPICE
+        tablewsname = basewsname + "_RawTable"
+        infowsname  = basewsname + "ExpInfo"
+        api.LoadSpiceAscii(Filename=datafilename,
+                OutputWorkspace=tablewsname, RunInfoWorkspace=infowsname)
+
+        tablews = AnalysisDataService.retrieve(tablewsname)
+        infows  = AnalysisDataService.retrieve(infowsname)
+
+        # Create a reduction manager and add workspaces to it
+        wsmanager = PDRManager(expno, scanno)
+        wsmanager.setRawWorkspaces(tablews, infows)
+        self._myWorkspaceDict[ (int(expno), int(scanno) )] = wsmanager
+
+        return
+
+
+    def mergeReduceSpiceData(self, expno, scannolist, unit, xmin, xmax, binsize):
+        """ Merge and reduce SPICE data files
+        Arguements:
+         - expscanfilelist: list of 3 tuples: expnumber, scannumber and file name
+        """
+        # Collect data MD workspaces and monitor MD workspaces
+        datamdwslist = []
+        monitormdwslist = []
+        self._lastWkspToMerge = []
+
+        print "[Checkpoint 0] Scans = ", str(scannolist)
+        for scanno in sorted(scannolist):
+            try:
+                wsmanager = self.getWorkspace(expno, scanno, True)
+                datamdwslist.append(wsmanager.datamdws)
+                monitormdwslist.append(wsmanager.monitormdws)
+                self._lastWkspToMerge.append(wsmanager)
+            except KeyError as ne:
+                print '[Error] Unable to retrieve MDWorkspaces for Exp %d Scan %d due to %s.' % (
+                    expno, scanno, str(ne))
+                scannolist.remove(scanno)
+        # ENDFOR
+
+        print "[Checkpoing 1] Scans = ", str(scannolist)
+
+        # Merge and binning
+        if len(datamdwslist) > 1:
+            mg_datamdws = datamdwslist[0] +  datamdwslist[1]
+            mg_monitormdws = monitormdwslist[0] + monitormdwslist[1]
+        else:
+            mg_datamdws = datamdwslist[0]
+            mg_monitormdws = monitormdwslist[0]
+        for iw in xrange(2, len(datamdwslist)):
+            mg_datamdws += datamdwslist[iw]
+            mg_monitormdws += monitormdwslist[iw]
+
+        # Set up binning parameters
+        if xmin is None or xmax is None:
+            binpar = "%.7f" % (binsize)
+        else:
+            binpar = "%.7f, %.7f, %.7f" % (xmin, binsize, xmax)
+
+        # set up output workspace's name
+        scannolist = sorted(scannolist)
+        outwsname = "Merged_Exp%d_Scan%s_%s" % (expno, scannolist[0], scannolist[-1])
+
+        # Merge
+        wavelength = self.getWavelength(expno, scannolist[0])
+        api.ConvertCWPDMDToSpectra(InputWorkspace=mg_datamdws,
+                                   InputMonitorWorkspace=mg_monitormdws,
+                                   OutputWorkspace=outwsname,
+                                   BinningParams=binpar,
+                                   UnitOutput=unit,
+                                   NeutronWaveLength=wavelength)
+        moutws = AnalysisDataService.retrieve(outwsname)
+        if moutws is None:
+            raise NotImplementedError("Merge failed.")
+
+        key = (expno, str(scannolist))
+        self._myMergedWSDict[key] = moutws
+
+        return key
+
+
+    def parseDetEffCorrFile(self, instrument, vancorrfname):
+        """ Parse detector efficiency correction file='HB2A
+
+        Return :: 2-tuple (table workspace and or
+        """
+        if instrument.upper() == 'HB2A':
+            vancorrdict, errmsg = hutil.parseDetEffCorrFile(vancorrfname)
+            if len(vancorrdict) > 0:
+                detefftablews = self._generateTableWS(vancorrdict)
+            else:
+                detefftablews = None
+        else:
+            detefftablews = None
+            errmsg = "Instrument %s is not supported for parsing vanadium (detector efficiency) correction."
+
+        return (detefftablews, errmsg)
+
+
+    def parseExcludedDetFile(self, instrument, excldetfname):
+        """ Parse excluded detectors file
+
+        Return :: 2 -tuple (list/None, error message)
+        """
+        if instrument.upper() == 'HB2A':
+            excldetlist, errmsg = hutil.parseDetExclusionFile(excldetfname)
+        else:
+            raise NotImplementedError('Instrument %s is not supported for parsing excluded detectors file.'%(instrument))
+
+        return excldetlist, errmsg
+
+
+    def parseSpiceData(self, expno, scanno, detefftablews=None):
+        """ Load SPICE data to MDWorkspaces
+        """
+        # Get reduction manager
+        try:
+            wsmanager = self._myWorkspaceDict[ (int(expno), int(scanno) )]
+        except KeyError:
+            raise NotImplementedError("Exp %d Scan %d has not been loaded yet." % (int(expno),
+                int(scanno)))
+
+        # Convert to MDWorkspace
+        tablews = wsmanager.getRawSpiceTable()
+        infows  = wsmanager.getRawInfoMatrixWS()
+
+        basewsname = tablews.name().split('_RawTable')[0]
+        datamdwsname = basewsname + "_DataMD"
+        monitorwsname = basewsname + "_MonitorMD"
+        api.ConvertSpiceDataToRealSpace(InputWorkspace=tablews,
+                                        RunInfoWorkspace=infows,
+                                        OutputWorkspace=datamdwsname,
+                                        OutputMonitorWorkspace=monitorwsname,
+                                        DetectorEfficiencyTableWorkspace=detefftablews)
+
+        datamdws = AnalysisDataService.retrieve(datamdwsname)
+        monitormdws = AnalysisDataService.retrieve(monitorwsname)
+
+        if datamdws is None or monitormdws is None:
+            raise NotImplementedError("Failed to convert SPICE data to MDEventWorkspaces \
+                    for experiment %d and scan %d." % (expno, scanno))
+
+        # Manager:
+        wsmanager.setupMDWrokspaces(datamdws, monitormdws)
+        self._myWorkspaceDict[(expno, scanno)] = wsmanager
+
+        return True
+
+
+    def reduceSpicePDData(self, exp, scan, unit, xmin, xmax, binsize, wavelength=None, excludeddetlist=None,scalefactor=None):
+        """ Reduce SPICE powder diffraction data.
+        Return - Boolean as reduction is successful or not
+        """
+        # Default
+        if excludeddetlist is None:
+            excludeddetlist = None
+
+        # Get reduction manager
+        try:
+            wsmanager = self._myWorkspaceDict[(int(exp), int(scan))]
+        except KeyError:
+            raise NotImplementedError("SPICE data for Exp %d Scan %d has not been loaded." % (
+                int(exp), int(scan)))
+
+        datamdws = wsmanager.datamdws
+        monitormdws = wsmanager.monitormdws
+
+        # binning from MD to single spectrum ws
+        # set up binning parameters
+        if xmin is None or xmax is None:
+            binpar = "%.7f" % (binsize)
+        else:
+            binpar = "%.7f, %.7f, %.7f" % (xmin, binsize, xmax)
+
+        # scale-factor
+        if scalefactor is None:
+            scalefactor = 1.
+        else:
+            scalefactor = float(scalefactor)
+
+        basewsname = datamdws.name().split("_DataMD")[0]
+        outwsname = basewsname + "_Reduced"
+        print "[DB]", numpy.array(excludeddetlist)
+        api.ConvertCWPDMDToSpectra(InputWorkspace=datamdws,
+                InputMonitorWorkspace=monitormdws,
+                OutputWorkspace=outwsname,
+                BinningParams=binpar,
+                UnitOutput = unit,
+                NeutronWaveLength=wavelength,
+                ExcludedDetectorIDs=numpy.array(excludeddetlist),
+                ScaleFactor=scalefactor)
+
+        print "[DB] Reduction is finished.  Data is in workspace %s. " % (outwsname)
+
+        # Set up class variable for min/max and
+        outws = AnalysisDataService.retrieve(outwsname)
+        if outws is None:
+            raise NotImplementedError("Failed to bin the MDEventWorkspaces to MatrixWorkspace.")
+
+        # Manager:
+        wsmanager = PDRManager(exp, scan)
+        wsmanager.setup(datamdws, monitormdws, outws, unit, binsize)
+        wsmanager.setWavelength(wavelength)
+
+        self._myWorkspaceDict[(exp, scan)] = wsmanager
+
+        return True
+
+
+    def retrieveCorrectionData(self, instrument, exp, scan, localdatadir):
+        """ Retrieve including dowloading and/or local locating
+        powder diffraction's correction files
+
+        Arguments:
+         - instrument :: name of powder diffractometer in upper case
+         - exp :: integer as epxeriment number
+         - scan :: integer as scan number
+
+        Return :: 2-tuple (True, list of returned file names) or (False, error reason)
+        """
+        if instrument.upper() == 'HB2A':
+            # For HFIR HB2A only
+
+            try:
+                wsmanager = self._myWorkspaceDict[(exp, scan)]
+            except KeyError as e:
+                raise e
+
+            # Get parameter m1 and colltrans
+            m1 = self._getValueFromTable(wsmanager.getRawSpiceTable(), 'm1')
+            colltrans = self._getValueFromTable(wsmanager.getRawSpiceTable(), 'colltrans')
+
+            # detector efficiency file
+            try:
+                detefffname, deteffurl, wavelength = hutil.makeHB2ADetEfficiencyFileName(exp, m1, colltrans)
+            except NotImplementedError as e:
+                raise e
+            if detefffname is not None:
+                localdetefffname = os.path.join(localdatadir, detefffname)
+                print "[DB] Detector efficiency file name: %s From %s" % (detefffname, deteffurl)
+                if os.path.exists(localdetefffname) is False:
+                    downloadFile(deteffurl, localdetefffname)
+                else:
+                    print "[Info] Detector efficiency file %s exists in directory %s." % (detefffname, localdatadir)
+            else:
+                localdetefffname = None
+            # ENDIF
+
+            # excluded detectors file
+            excldetfname, exclurl = hutil.makeExcludedDetectorFileName(exp)
+            localexcldetfname = os.path.join(localdatadir, excldetfname)
+            print "[DB] Excluded det file name: %s From %s" % (excldetfname, exclurl)
+            if os.path.exists(localexcldetfname) is False:
+                downloadstatus, errmsg = downloadFile(exclurl, localexcldetfname)
+                if downloadstatus is False:
+                    localexcldetfname = None
+                    print "[Error] %s" % (errmsg)
+            else:
+                print "[Info] Detector exclusion file %s exists in directory %s." % (excldetfname, localdatadir)
+
+            # Set to ws manager
+            wsmanager.setWavelength(wavelength)
+            # wsmanager.setDetEfficencyFile()
+            # wsmanager.setExcludedDetFile()
+
+        else:
+            # Other instruments
+            raise NotImplementedError("Instrument %s is not supported to retrieve correction file." % (instrument))
+
+
+        return (True, [wavelength, localdetefffname, localexcldetfname])
+
+
+    def saveMergedScan(self, sfilename, mergeindex):
+        """ Save the current merged scan
+        """
+        if self._myMergedWSDict.has_key(mergeindex) is True:
+            wksp = self._myMergedWSDict[mergeindex]
+        else:
+            raise NotImplementedError('Unable to locate the merged scan workspace.')
+
+        api.SaveFocusedXYE(InputWorkspace=wksp,
+                           StartAtBankNumber=1,
+                           Filename=sfilename)
+
+        return
+
+
+    def savePDFile(self, exp, scan, filetype, sfilename):
+        """ Save a reduced workspace to gsas/fullprof/topaz data file
+        """
+        # get workspace
+        wsmanager = self.getWorkspace(exp, scan, raiseexception=True)
+        if wsmanager.reducedws is None:
+            raise NotImplementedError("Unable to rebin the data for exp=%d, scan=%d because \
+                    either data MD workspace and monitor MD workspace is not present."  % (exp, scan))
+        else:
+            wksp = wsmanager.reducedws
+
+        # save
+        filetype = filetype.lower()
+        if "gsas" in filetype:
+            if sfilename.endswith('.dat') is True:
+                sfilename.replace('.dat', '.gsa')
+
+            api.SaveGSS(InputWorkspace=wksp,
+                        Filename=sfilename,
+                        SplitFiles=False, Append=False,
+                        MultiplyByBinWidth=False,
+                        Bank=1,
+                        Format="SLOG",
+                        ExtendedHeader=True)
+        # ENDIF
+
+        if "fullprof" in filetype:
+            if sfilename.endswith('.gsa') is True:
+                sfilename.replace('.gsa', '.dat')
+
+            api.SaveFocusedXYE(InputWorkspace=wksp,
+                               StartAtBankNumber=1,
+                               Filename=sfilename)
+        # ENDIF
+
+        if "topas" in filetype:
+            sfilename = sfilename[:-4]+".xye"
+            api.SaveFocusedXYE(InputWorkspace=wksp,
+                               StartAtBankNumber=info["bank"],
+                               Filename=sfilename,
+                               Format="TOPAS")
+        # ENDIF
+
+        return
+
+
+    def saveProcessedVanadium(self, expno, scanno, savefilename):
+        """ Save processed vanadium data
+        """
+        # Get workspace
+        wsmanager = self.getWorkspace(expno, scanno, raiseexception=True)
+
+        if wsmanager.isSmoothApplied() is True:
+            wksp = wsmanager.getProcessedVanadiumWSTemp()
+        else:
+            wksp = wsmanager.getProcessedVanadiumWS()
+
+        # Save
+        api.SaveFocusedXYE(InputWorkspace=wksp,
+                   StartAtBankNumber=1,
+                   Filename=savefilename)
+
+        return
+
+
+    def setWavelength(self, exp, scan, wavelength):
+        """ Set wavelength for a specific scan
+        """
+        exp = int(exp)
+        scan = int(scan)
+        if wavelength == None:
+            self._myWavelengthDict[(exp, scan)] = None
+        else:
+            self._myWavelengthDict[(exp, scan)] = float(wavelength)
+
+        return
+
+
+    def smoothVanadiumSpectrum(self, expno, scanno, smoothparams_str):
+        """
+        """
+        # Get reduced workspace
+        wsmanager = self.getWorkspace(expno, scanno, raiseexception=True)
+        vanRun = wsmanager.getProcessedVanadiumWS()
+        outws = vanRun.name()+"_smooth"
+
+        outws = api.FFTSmooth(InputWorkspace=vanRun,
+                              OutputWorkspace=outws,
+                              Filter="Butterworth",
+                              Params=smoothparams_str,
+                              IgnoreXBins=True,
+                              AllSpectra=True)
+
+        if outws is not None:
+            wsmanager.setProcessedVanadiumDataTemp(outws, "FFT smooth")
+
+        return True
+
+
+    def stripVanadiumPeaks(self, exp, scan, binparams, vanpeakposlist=None):
+        """ Strip vanadium peaks
+
+        Arguments:
+         - binparams :: string as the list of xmin, binsize, xmax or just binsize
+         - vanpeakposlist :: list of peak positions.  If none, then using default
+
+        Return ::
+        """
+        # Get reduced workspace
+        wsmanager = self.getWorkspace(exp, scan, raiseexception=True)
+        wksp = wsmanager.reducedws
+        if wksp is None:
+            raise NotImplementedError("Unable to rebin the data for exp=%d, scan=%d because either data MD workspace and \
+                monitor MD workspace is not present."  % (exp, scan))
+
+        # Convert unit to Time-of-flight by rebinning
+        xaxis_unit = wksp.getAxis(0).getUnit().unitID()
+        if xaxis_unit != 'Degrees':
+            wksp = api.ConvertCWPDToSpectra(InputWorkspace=wksp,
+                                            OutputWorkspace=wksp.name(),
+                                            Params=binparams)
+
+        # Vanadium peaks positions
+        if vanpeakposlist is None or len(vanpeakposlist) == 0:
+            vanpeakposlist = wsmanager.getVanadiumPeaks()
+            if vanpeakposlist is None:
+                raise NotImplementedError('No vanadium peaks has been set up.')
+        # ENDIF
+
+        outwsname = wksp.name()+"_rmVan"
+        wksp = api.StripPeaks(InputWorkspace=wksp,
+                              OutputWorkspace=outwsname,
+                              PeakPositions=numpy.array(vanpeakposlist))
+
+        # Store
+        wsmanager.setProcessedVanadiumData(wksp)
+
+        return True
+
+
+    def _generateTableWS(self, vancorrdict):
+        """ Create table workspace
+        """
+        tablews = api.CreateEmptyTableWorkspace(OutputWorkspace="tempcorrtable")
+        tablews.addColumn('int', 'DetID')
+        tablews.addColumn('double', 'Correction')
+
+        for detid in sorted(vancorrdict.keys()):
+            tablews.addRow( [detid, vancorrdict[detid]] )
+
+        return tablews
+
+
+    def _getRunNumberList(self, datamdws):
+        """ Get list of run number (i.e., Pt) from an MDEventWorkspace
+
+        Return :: list of MDEventWrokspace
+        """
+        ptnolist = []
+
+        numexpinfo = datamdws.getNumExperimentInfo()
+        for i in xrange(numexpinfo):
+            expinfo = datamdws.getExperimentInfo(i)
+            runid = expinfo.run().getProperty('run_number').value
+            if runid >= 0:
+                ptnolist.append(runid)
+        # ENDFOR
+
+        return sorted(ptnolist)
+
+
+    def _getValueFromTable(self, tablews, colname, rowindex=0):
+        """ Get value from a table workspace
+        """
+        colnames = tablews.getColumnNames()
+        try:
+            colindex = colnames.index(colname)
+            rvalue = tablews.cell(rowindex, colindex)
+        except ValueError:
+            rvalue = None
+
+        return rvalue
+
+#-------------------------------------------------------------------------------
+# External Methods
+#-------------------------------------------------------------------------------
+def downloadFile(url, localfilepath):
+    """
+    Test: 'http://neutron.ornl.gov/user_data/hb2a/exp400/Datafiles/HB2A_exp0400_scan0001.dat'
+
+    Arguments:
+     - localfilepath :: local data file name with full path.
+    """
+    # open URL
+    try:
+        response = urllib2.urlopen(url)
+        wbuf = response.read()
+    except urllib2.HTTPError as e:
+        # Unable to download file
+        if str(e).count('HTTP Error 404') == 1:
+            return (False, str(e))
+        else:
+            raise NotImplementedError("Unable to download file from %s\n\tCause: %s." % (url, str(e)))
+    # ENDIFELSE
+
+    if wbuf.count('not found') > 0:
+        return (False, "File cannot be found at %s." % (url))
+
+    ofile = open(localfilepath, 'w')
+    ofile.write(wbuf)
+    ofile.close()
+
+    return (True, "")
+
+
diff --git a/Code/Mantid/scripts/HFIRPowderReduction/HfirPDReductionGUI.py b/Code/Mantid/scripts/HFIRPowderReduction/HfirPDReductionGUI.py
new file mode 100644
index 0000000000000000000000000000000000000000..c7e6b62dd0daebcf9d755af23e0128a703976278
--- /dev/null
+++ b/Code/Mantid/scripts/HFIRPowderReduction/HfirPDReductionGUI.py
@@ -0,0 +1,2295 @@
+#pylint: disable=invalid-name, relative-import, too-many-lines,too-many-instance-attributes
+################################################################################
+# Main class for HFIR powder reduction GUI
+# Key word for future developing: FUTURE, NEXT, REFACTOR, RELEASE 2.0
+################################################################################
+
+import numpy
+import os
+
+from Ui_MainWindow import Ui_MainWindow #import line for the UI python class
+from PyQt4 import QtCore, QtGui
+try:
+    _fromUtf8 = QtCore.QString.fromUtf8
+except AttributeError:
+    def _fromUtf8(s):
+        return s
+
+import mantid
+from HfirPDReductionControl import *
+
+#----- default configuration ---------------
+DEFAULT_SERVER = 'http://neutron.ornl.gov/user_data'
+DEFAULT_INSTRUMENT = 'hb2a'
+DEFAULT_WAVELENGTH = 2.4100
+#-------------------------------------------
+
+class EmptyError(Exception):
+    """ Exception for finding empty input for integer or float
+    """
+    def __init__(self, value):
+        """ Init
+        """
+        Exception.__init__(self)
+        self.value = value
+
+    def __str__(self):
+        return repr(self.value)
+
+#pylint: disable=too-many-public-methods,too-many-branches,too-many-locals,too-many-arguments
+class MainWindow(QtGui.QMainWindow):
+    """ Class of Main Window (top)
+    """
+
+    # Copy to ui.setupUI
+    # # Version 3.0 + Import for Ui_MainWindow.py
+    #     from MplFigureCanvas import Qt4MplCanvas
+
+    #     # Replace 'self.graphicsView = QtGui.QtGraphicsView' with the following
+    #     self.graphicsView = Qt4MplCanvas(self.centralwidget)
+    #     self.mainplot = self.graphicsView.getPlot()
+
+    def __init__(self, parent=None):
+        """ Intialization and set up
+        """
+        # Base class
+        QtGui.QMainWindow.__init__(self,parent)
+
+        # UI Window (from Qt Designer)
+        self.ui = Ui_MainWindow()
+        self.ui.setupUi(self)
+
+        # Define gui-event handling
+
+        # menu
+        self.connect(self.ui.actionQuit, QtCore.SIGNAL('triggered()'),
+                self.doExist)
+        self.connect(self.ui.actionFind_Help, QtCore.SIGNAL('triggered()'),
+                self.doHelp)
+
+        # main
+        self.connect(self.ui.comboBox_wavelength, QtCore.SIGNAL('currentIndexChanged(int)'),
+                self.doUpdateWavelength)
+        self.connect(self.ui.pushButton_browseExcludedDetFile, QtCore.SIGNAL('clicked'),
+                self.doBrowseExcludedDetetorFile)
+
+        # tab 'Raw Detectors'
+        self.connect(self.ui.pushButton_plotRaw, QtCore.SIGNAL('clicked()'),
+                self.doPlotRawPtMain)
+        self.connect(self.ui.pushButton_ptUp, QtCore.SIGNAL('clicked()'),
+                self.doPlotRawPtPrev)
+        self.connect(self.ui.pushButton_ptDown, QtCore.SIGNAL('clicked()'),
+                self.doPlotRawPtNext)
+        self.connect(self.ui.pushButton_clearRawDets, QtCore.SIGNAL('clicked()'),
+                self.doClearRawDetCanvas)
+
+        # tab 'Individual Detectors'
+        self.connect(self.ui.pushButton_plotIndvDet, QtCore.SIGNAL('clicked()'),
+                self.doPlotIndvDetMain)
+        self.connect(self.ui.pushButton_plotPrevDet, QtCore.SIGNAL('clicked()'),
+                self.doPlotIndvDetPrev)
+        self.connect(self.ui.pushButton_plotNextDet, QtCore.SIGNAL('clicked()'),
+                self.doPlotIndvDetNext)
+        self.connect(self.ui.pushButton_clearCanvasIndDet, QtCore.SIGNAL('clicked()'),
+                self.doClearIndDetCanvas)
+        self.connect(self.ui.pushButton_plotLog , QtCore.SIGNAL('clicked()'),
+                self.doPlotSampleLog)
+
+        # tab 'Normalized'
+        self.connect(self.ui.pushButton_loadData, QtCore.SIGNAL('clicked()'),
+                self.doLoadData)
+        self.connect(self.ui.pushButton_prevScan, QtCore.SIGNAL('clicked()'),
+                self.doLoadReduceScanPrev)
+        self.connect(self.ui.pushButton_nextScan, QtCore.SIGNAL('clicked()'),
+                self.doLoadReduceScanNext)
+        self.connect(self.ui.pushButton_unit2theta, QtCore.SIGNAL('clicked()'),
+                self.doReduce2Theta)
+        self.connect(self.ui.pushButton_unitD, QtCore.SIGNAL('clicked()'),
+                self.doReduceDSpacing)
+        self.connect(self.ui.pushButton_unitQ, QtCore.SIGNAL('clicked()'),
+                self.doReduceQ)
+        self.connect(self.ui.pushButton_saveData, QtCore.SIGNAL('clicked()'),
+                self.doSaveData)
+        self.connect(self.ui.pushButton_clearTab2Canvas, QtCore.SIGNAL('clicked()'),
+                self.doClearCanvas)
+
+        # tab 'Multiple Scans'
+        self.connect(self.ui.pushButton_loadMultData, QtCore.SIGNAL('clicked()'),
+                self.doLoadSetData)
+        self.connect(self.ui.pushButton_mscanBin, QtCore.SIGNAL('clicked()'),
+                self.doReduceSetData)
+        self.connect(self.ui.pushButton_mergeScans, QtCore.SIGNAL('clicked()'),
+                self.doMergeScans)
+        self.connect(self.ui.pushButton_viewMScan1D, QtCore.SIGNAL('clicked()'),
+                self.doMergeScanView1D)
+        self.connect(self.ui.pushButton_view2D, QtCore.SIGNAL('clicked()'),
+                self.doMergeScanView2D)
+        self.connect(self.ui.pushButton_viewMerge, QtCore.SIGNAL('clicked()'),
+                self.doMergeScanViewMerged)
+        self.connect(self.ui.pushButton_clearMultCanvas, QtCore.SIGNAL('clicked()'),
+                self.doClearMultiRunCanvas)
+        self.connect(self.ui.pushButton_saveAllIndScans, QtCore.SIGNAL('clicked()'),
+                self.doSaveMultipleScans)
+        self.connect(self.ui.pushButton_saveMerge, QtCore.SIGNAL('clicked()'),
+                self.doSaveMergedScan)
+
+        # tab 'Vanadium'
+        self.connect(self.ui.pushButton_stripVanPeaks, QtCore.SIGNAL('clicked()'),
+                self.doStripVandiumPeaks)
+        self.connect(self.ui.pushButton_saveVanRun, QtCore.SIGNAL('clicked()'),
+                self.doSaveVanRun)
+        self.connect(self.ui.pushButton_rebin2Theta, QtCore.SIGNAL('clicked()'),
+                self.doReduceVanadium2Theta)
+        self.connect(self.ui.pushButton_smoothVanData, QtCore.SIGNAL('clicked()'),
+                self.doSmoothVanadiumData)
+        self.connect(self.ui.pushButton_applySmooth, QtCore.SIGNAL('clicked()'),
+                self.doSmoothVanadiumApply)
+        self.connect(self.ui.pushButton_undoSmooth, QtCore.SIGNAL('clicked()'),
+                self.doSmoothVanadiumUndo)
+
+        # tab 'Advanced Setup'
+        self.connect(self.ui.pushButton_browseCache, QtCore.SIGNAL('clicked()'),
+                self.doBrowseCache)
+        self.connect(self.ui.radioButton_useServer, QtCore.SIGNAL('clicked()'),
+                self.doChangeSrcLocation)
+        self.connect(self.ui.radioButton_useLocal, QtCore.SIGNAL('clicked()'),
+                self.doChangeSrcLocation)
+        self.connect(self.ui.pushButton_browseLocalSrc, QtCore.SIGNAL('clicked()'),
+                self.doBrowseLocalDataSrc)
+        self.connect(self.ui.pushButton_chkServer, QtCore.SIGNAL('clicked()'),
+                self.doCheckSrcServer)
+
+        # Define signal-event handling
+
+        # define event handlers for matplotlib canvas
+        self.ui.graphicsView_mergeRun.canvas.mpl_connect('button_press_event', \
+                self.on_mouseDownEvent)
+        self.ui.graphicsView_mergeRun.canvas.mpl_connect('motion_notify_event', \
+                self.on_mouseMotion)
+
+        # Widget type definition
+        validator0 = QtGui.QIntValidator(self.ui.lineEdit_expNo)
+        validator0.setBottom(1)
+        self.ui.lineEdit_expNo.setValidator(validator0)
+
+        validator1 = QtGui.QIntValidator(self.ui.lineEdit_expNo)
+        validator1.setBottom(1)
+        self.ui.lineEdit_scanNo.setValidator(validator1)
+
+        validator2 = QtGui.QDoubleValidator(self.ui.lineEdit_wavelength)
+        validator2.setBottom(0.)
+        self.ui.lineEdit_wavelength.setValidator(validator2)
+
+        validator3 = QtGui.QDoubleValidator(self.ui.lineEdit_xmin)
+        validator3.setBottom(0.)
+        self.ui.lineEdit_xmin.setValidator(validator3)
+
+        validator4 = QtGui.QDoubleValidator(self.ui.lineEdit_xmax)
+        validator4.setBottom(0.)
+        self.ui.lineEdit_xmax.setValidator(validator4)
+
+        validator5 = QtGui.QDoubleValidator(self.ui.lineEdit_binsize)
+        validator5.setBottom(0.)
+        self.ui.lineEdit_binsize.setValidator(validator5)
+
+        validator6 = QtGui.QDoubleValidator(self.ui.lineEdit_ptNo)
+        validator6.setBottom(0)
+        self.ui.lineEdit_ptNo.setValidator(validator6)
+
+        validator7 = QtGui.QDoubleValidator(self.ui.lineEdit_detID)
+        validator7.setBottom(0)
+        self.ui.lineEdit_detID.setValidator(validator7)
+
+        validator8 = QtGui.QDoubleValidator(self.ui.lineEdit_min2Theta)
+        validator8.setBottom(0.)
+        self.ui.lineEdit_min2Theta.setValidator(validator8)
+
+        validator9 = QtGui.QDoubleValidator(self.ui.lineEdit_max2Theta)
+        validator9.setBottom(0.)
+        self.ui.lineEdit_max2Theta.setValidator(validator9)
+
+        validator10 = QtGui.QDoubleValidator(self.ui.lineEdit_binsize2Theta)
+        validator10.setBottom(0.)
+        self.ui.lineEdit_binsize2Theta.setValidator(validator10)
+
+        validator11 = QtGui.QIntValidator(self.ui.lineEdit_scanStart)
+        validator11.setBottom(1)
+        self.ui.lineEdit_scanStart.setValidator(validator11)
+
+        validator12 = QtGui.QIntValidator(self.ui.lineEdit_scanEnd)
+        validator12.setBottom(1)
+        self.ui.lineEdit_scanEnd.setValidator(validator12)
+
+        validator13 = QtGui.QDoubleValidator(self.ui.lineEdit_normalizeMonitor)
+        validator13.setBottom(0.)
+        self.ui.lineEdit_normalizeMonitor.setValidator(validator13)
+
+        validator14 = QtGui.QDoubleValidator(self.ui.lineEdit_mergeMinX)
+        validator14.setBottom(0.)
+        self.ui.lineEdit_mergeMinX.setValidator(validator14)
+
+        validator15 = QtGui.QDoubleValidator(self.ui.lineEdit_mergeMaxX)
+        validator15.setBottom(0.)
+        self.ui.lineEdit_mergeMaxX.setValidator(validator15)
+
+        validator16 = QtGui.QDoubleValidator(self.ui.lineEdit_mergeBinSize)
+        validator16.setBottom(0.)
+        self.ui.lineEdit_mergeBinSize.setValidator(validator16)
+
+        # Get initial setup
+        # RELEASE 2.0 - This part will be implemented soon as default configuration is made
+        # Mantid configuration
+        self._instrument = str(self.ui.comboBox_instrument.currentText())
+
+        # UI widgets setup
+        self.ui.comboBox_outputFormat.addItems(['Fullprof']) # Supports Fullprof only now, 'GSAS', 'Fullprof+GSAS'])
+
+        # RELEASE 2.0 : Need to disable some widgets... consider to refactor the code
+        self.ui.radioButton_useServer.setChecked(True)
+        self.ui.radioButton_useLocal.setChecked(False)
+
+        self.ui.comboBox_wavelength.setCurrentIndex(0)
+        self.ui.lineEdit_wavelength.setText('2.41')
+
+        self.ui.pushButton_unit2theta.setText(r'$2\theta$')
+
+        # vanadium spectrum smooth parameters
+        self.ui.lineEdit_smoothParams.setText('20,2')
+
+        # Set up data source
+        self._serverAddress = DEFAULT_SERVER
+        self._srcFromServer = True
+        self._localSrcDataDir = None
+        self._srcAtLocal = False
+
+        self._currUnit = '2theta'
+
+        # Workspaces
+        self._myControl = HFIRPDRedControl()
+
+        # Interactive graphics
+        self._viewMerge_X = None
+        self._viewMerge_Y = None
+
+        # Control of plots: key = canvas, value = list of 2-integer-tuple (expno, scanno)
+        self._tabLineDict = {}
+        self._tabBinParamDict = {}
+        for key in [2]:
+            self._tabLineDict[key] = []
+        for key in [2, 3, 4]:
+            self._tabBinParamDict[key] = [None, None, None]
+
+        self._lastMergeLabel = ""
+        self._lastMergeIndex = -1
+
+        self._expNo = None
+        self._scanNo = None
+        self._detID = None
+        self._indvXLabel = None
+
+        self._rawDetExpNo = None
+        self._rawDetScanNo = None
+        self._rawDetPlotMode = None
+        self._rawDetPtNo = None
+
+        self._indvDetCanvasMode = 'samplelog'
+
+        #help
+        self.assistantProcess = QtCore.QProcess(self)
+        # pylint: disable=protected-access
+        self.collectionFile=os.path.join(mantid._bindir,'../docs/qthelp/MantidProject.qhc')
+        version = ".".join(mantid.__version__.split(".")[:2])
+        self.qtUrl='qthelp://org.sphinx.mantidproject.'+version+'/doc/interfaces/HFIRPowderReduction.html'
+        self.externalUrl='http://docs.mantidproject.org/nightly/interfaces/HFIRPowderReduction.html'
+
+        return
+
+
+    #-- Event Handling ----------------------------------------------------
+
+    def doBrowseCache(self):
+        """ Pop out a dialog to let user specify the directory to
+        cache downloaded data
+        """
+        # home directory
+        homedir = str(self.ui.lineEdit_cache.text()).strip()
+        if len(homedir) > 0 and os.path.exists(homedir):
+            home = homedir
+        else:
+            home = os.getcwd()
+
+        # pop out a dialog
+        dirs = str(QtGui.QFileDialog.getExistingDirectory(self,'Get Directory',home))
+
+        # set to line edit
+        if dirs != home:
+            self.ui.lineEdit_cache.setText(dirs)
+
+        return
+
+    def doBrowseExcludedDetetorFile(self):
+        """ Browse excluded detector's file
+        Return :: None
+        """
+        # Get file name
+        filefilter = "Text (*.txt);;Data (*.dat);;All files (*.*)"
+        curDir = os.getcwd()
+        excldetfnames = QtGui.QFileDialog.getOpenFileNames(self, 'Open File(s)', curDir, filefilter)
+        try:
+            excldetfname = excldetfnames[0]
+            self.ui.lineEdit_excludedDetFileName.setText(excldetfname)
+        except IndexError:
+            # return if there is no file selected
+            return
+
+        # Parse det exclusion file
+        print "Detector exclusion file name is %s." % (excldetfname)
+        excludedetlist, errmsg = self._myControl.parseExcludedDetFile('HB2A', excldetfname)
+        if len(errmsg) > 0:
+            self._logError(errmsg)
+        textbuf = ""
+        for detid in excludedetlist:
+            textbuf += "%d," % (detid)
+        if len(textbuf) > 0:
+            textbuf = textbuf[:-1]
+            self.ui.lineEdit_detExcluded.setText(textbuf)
+        # ENDIF
+
+        return
+
+    def doBrowseLocalDataSrc(self):
+        """ Browse local data storage
+        """
+        print "Browse local data storage location."
+
+        return
+
+
+    def doChangeSrcLocation(self):
+        """ Source file location is changed
+        """
+        useserver = self.ui.radioButton_useServer.isChecked()
+        uselocal = self.ui.radioButton_useLocal.isChecked()
+
+        print "Use Server: ", useserver
+        print "Use Local : ", uselocal
+
+        if (useserver is True and uselocal is True) or \
+            (useserver is False and uselocal is False):
+            raise NotImplementedError("Impossible for radio buttons")
+
+        self._srcAtLocal = uselocal
+        self._srcFromServer = useserver
+
+        if uselocal is True:
+            self.ui.lineEdit_dataIP.setDisabled(True)
+            self.ui.pushButton_chkServer.setDisabled(True)
+            self.ui.lineEdit_localSrc.setDisabled(False)
+            self.ui.pushButton_browseLocalSrc.setDisabled(False)
+
+        else:
+            self.ui.lineEdit_dataIP.setDisabled(False)
+            self.ui.pushButton_chkServer.setDisabled(False)
+            self.ui.lineEdit_localSrc.setDisabled(True)
+            self.ui.pushButton_browseLocalSrc.setDisabled(True)
+
+        return
+
+
+    def doCheckSrcServer(self):
+        """" Check source data server's availability
+        """
+
+        print "Check source data server!"
+
+        return
+
+    def doClearCanvas(self):
+        """ Clear canvas
+        """
+        itab = self.ui.tabWidget.currentIndex()
+        if itab == 2:
+            self.ui.graphicsView_reducedData.clearAllLines()
+            self._tabLineDict[itab] = []
+
+        return
+
+    def doClearIndDetCanvas(self):
+        """ Clear the canvas in tab 'Individual Detector' and current plotted lines
+        in managing dictionary
+        """
+        self.ui.graphicsView_indvDet.clearAllLines()
+        if self._tabLineDict.has_key(self.ui.graphicsView_indvDet):
+            self._tabLineDict[self.ui.graphicsView_indvDet] = []
+
+        return
+
+
+    def doClearMultiRunCanvas(self):
+        """ Clear the canvas in tab 'Multiple Run'
+
+        This canvas is applied to both 1D and 2D image.
+        Clear-all-lines might be not enough to clear 2D image
+        """
+        self.ui.graphicsView_mergeRun.clearCanvas()
+
+        return
+
+
+    def doClearRawDetCanvas(self):
+        """ Clear the canvas in tab 'Raw Detector':
+        only need to clear lines
+        """
+        self.ui.graphicsView_Raw.clearAllLines()
+        self._tabLineDict[self.ui.graphicsView_Raw] = []
+
+        return
+
+
+    def doClearVanadiumCanvas(self):
+        """ Clear the canvas in tab 'Vanadium'
+        """
+        self.ui.graphicsView_vanPeaks.clearAllLines()
+
+        return
+
+
+    def doExist(self):
+        """ Exist the application
+        """
+        clearcache = self.ui.checkBox_delCache.isChecked()
+
+        if clearcache is True:
+            delAllFile(self._cache)
+
+        self.close()
+
+        return
+
+    def doHelp(self):
+        """ Show help
+        Copied from DGSPlanner
+        """
+        self.assistantProcess.close()
+        self.assistantProcess.waitForFinished()
+        helpapp = QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.BinariesPath) + QtCore.QDir.separator()
+        helpapp += 'assistant'
+        args = ['-enableRemoteControl', '-collectionFile',self.collectionFile,'-showUrl',self.qtUrl]
+        if os.path.isfile(helpapp):
+            self.assistantProcess.close()
+            self.assistantProcess.waitForFinished()
+            self.assistantProcess.start(helpapp, args)
+            print "Show help from (app) ", helpapp
+        else:
+            QtGui.QDesktopServices.openUrl(QtCore.QUrl(self.externalUrl))
+            print "Show help from (url)", QtCore.QUrl(self.externalUrl)
+
+        return
+
+    def doLoadData(self, exp=None, scan=None):
+        """ Load and reduce data
+        It does not support for tab 'Multiple Scans' and 'Advanced Setup'
+        For tab 'Raw Detector' and 'Individual Detector', this method will load data to MDEventWorkspaces
+        For tab 'Normalized' and 'Vanadium', this method will load data to MDEVentWorkspaces but NOT reduce to single spectrum
+        """
+        # Kick away unsupported tabs
+        itab = self.ui.tabWidget.currentIndex()
+        tabtext = str(self.ui.tabWidget.tabText(itab))
+        print "[DB] Current active tab is No. %d as %s." % (itab, tabtext)
+
+        #if itab == 3:
+        #    # 'multiple scans'
+        #    self._logNotice("Tab %s does not support 'Load Data'.  Use 'Load All' instead." % (tabtext))
+        #    return
+
+        if itab == 5:
+            # 'advanced'
+            self._logNotice("Tab %s does not support 'Load Data'. Request is ambiguous." % (tabtext))
+            return
+
+        # Get exp number and scan number
+        if isinstance(exp, int) is True and isinstance(scan, int) is True:
+            # use input
+            expno = exp
+            scanno = scan
+        else:
+            # read from GUI
+            try:
+                expno, scanno = self._uiGetExpScanNumber()
+                self._logDebug("Attending to load Exp %d Scan %d." % (expno, scanno))
+            except NotImplementedError as ne:
+                self._logError("Error to get Exp and Scan due to %s." % (str(ne)))
+                return
+        # ENDIF
+
+        # Form data file name and download data
+        status, datafilename = self._uiDownloadDataFile(exp=expno, scan=scanno)
+        if status is False:
+            self._logError("Unable to download or locate local data file for Exp %d \
+                Scan %d." % (expno, scanno))
+        # ENDIF(status)
+
+        # (Load data for tab 0, 1, 2 and 4)
+        if itab not in [0, 1, 2, 3, 4]:
+            # Unsupported Tabs: programming error!
+            errmsg = "%d-th tab should not get this far.\n"%(itab)
+            errmsg += 'GUI has been changed, but the change has not been considered! iTab = %d' % (itab)
+            raise NotImplementedError(errmsg)
+
+        # Load SPICE data to raw table (step 1)
+        try:
+            execstatus = self._myControl.loadSpicePDData(expno, scanno, datafilename)
+            if execstatus is False:
+                cause = "Load data failed."
+            else:
+                cause = None
+        except NotImplementedError as ne:
+            execstatus = False
+            cause = str(ne)
+        # END-TRY-EXCEPT
+
+        # Return as failed to load data
+        if execstatus is False:
+            self._logError(cause)
+            return
+
+        # Obtain the correction file names and wavelength from SPICE file
+        wavelengtherror = False
+        errmsg = ""
+        localdir = os.path.dirname(datafilename)
+        try:
+            status, returnbody = self._myControl.retrieveCorrectionData(instrument='HB2A',
+                                                                    exp=expno, scan=scanno,
+                                                                    localdatadir=localdir)
+        except NotImplementedError as e:
+            errmsg = str(e)
+            if errmsg.count('m1') > 0:
+                # error is about wavelength
+                status = False
+                wavelengtherror = True
+            else:
+                # other error
+                raise e
+        # ENDTRY
+
+        if status is True:
+            autowavelength = returnbody[0]
+            vancorrfname = returnbody[1]
+            excldetfname = returnbody[2]
+
+            if vancorrfname is not None:
+                self.ui.lineEdit_vcorrFileName.setText(vancorrfname)
+            if excldetfname is not None:
+                self.ui.lineEdit_excludedDetFileName.setText(excldetfname)
+        else:
+            autowavelength = None
+            vancorrfname = None
+            excldetfname = None
+        # ENDIF
+
+        # Set wavelength to GUI except 'multiple scans'
+        if autowavelength is None:
+            # unable to get wavelength from SPICE data
+            self.ui.comboBox_wavelength.setCurrentIndex(4)
+            if wavelengtherror is True:
+                self.ui.lineEdit_wavelength.setText(errmsg)
+            else:
+                self.ui.lineEdit_wavelength.setText(self.ui.comboBox_wavelength.currentText())
+            self._myControl.setWavelength(expno, scanno, wavelength=None)
+        else:
+            # get wavelength from SPICE data.  set value to GUI
+            self.ui.lineEdit_wavelength.setText(str(autowavelength))
+            allowedwavelengths = [2.41, 1.54, 1.12]
+            numitems = self.ui.comboBox_wavelength.count()
+            good = False
+            for ic in xrange(numitems-1):
+                if abs(autowavelength - allowedwavelengths[ic]) < 0.01:
+                    good = True
+                    self.ui.comboBox_wavelength.setCurrentIndex(ic)
+            # ENDFOR
+
+            if good is False:
+                self.ui.comboBox_wavelength.setCurrentIndex(numitems-1)
+            # ENDIF
+
+            self._myControl.setWavelength(expno, scanno, wavelength=autowavelength)
+        # ENDIFELSE
+
+        # Optionally obtain and parse det effecient file
+        if self.ui.checkBox_useDetEffCorr.isChecked() is True:
+            # Apply detector efficiency correction
+            if vancorrfname is None:
+                # browse vanadium correction file
+                filefilter = "Text (*.txt);;Data (*.dat);;All files (*.*)"
+                curDir = os.getcwd()
+                vancorrfnames = QtGui.QFileDialog.getOpenFileNames(self, 'Open File(s)', curDir, filefilter)
+                if len(vancorrfnames) > 0:
+                    vancorrfname = vancorrfnames[0]
+                    self.ui.lineEdit_vcorrFileName.setText(str(vancorrfname))
+                else:
+                    self._logError("User does not specify any vanadium correction file.")
+                    self.ui.checkBox_useDetEffCorr.setChecked(False)
+                # ENDIF-len()
+            # ENDIF vancorrfname
+
+            # Parse if it is not None
+            if vancorrfname is not None:
+                detefftablews, errmsg = self._myControl.parseDetEffCorrFile('HB2A', vancorrfname)
+                if detefftablews is None:
+                    print "Parsing detectors efficiency file error: %s." % (errmsg)
+            else:
+                detefftablews = None
+            # ENDIF
+
+        else:
+            # Not chosen to apply detector efficiency correction:w
+            detefftablews = None
+        # ENDIF
+
+        # Parse SPICE data to MDEventWorkspaces
+        try:
+            print "Det EFF Table WS: ", str(detefftablews)
+            execstatus = self._myControl.parseSpiceData(expno, scanno, detefftablews)
+            if execstatus is False:
+                cause = "Parse data failed."
+            else:
+                cause = None
+        except NotImplementedError as e:
+            execstatus = False
+            cause = str(e)
+        # END-TRY-EXCEPT-FINALLY
+
+        # Return if data parsing is error
+        if execstatus is False:
+            self._logError(cause)
+            return
+
+        # Optionally parse detector exclusion file and set to line text
+        if excldetfname is not None:
+            excludedetlist, errmsg = self._myControl.parseExcludedDetFile('HB2A', excldetfname)
+
+            textbuf = ""
+            for detid in excludedetlist:
+                textbuf += "%d," % (detid)
+            if len(textbuf) > 0:
+                textbuf = textbuf[:-1]
+                self.ui.lineEdit_detExcluded.setText(textbuf)
+        # ENDIF
+
+        # Set up some widgets for raw detector data.  Won't be applied to tab 3
+        if itab != 3:
+            floatsamplelognamelist = self._myControl.getSampleLogNames(expno, scanno)
+            self.ui.comboBox_indvDetXLabel.clear()
+            self.ui.comboBox_indvDetXLabel.addItems(floatsamplelognamelist)
+            self.ui.comboBox_indvDetYLabel.clear()
+            self.ui.comboBox_indvDetYLabel.addItems(floatsamplelognamelist)
+
+        return True
+
+    def doLoadSetData(self):
+        """ Load a set of data
+        This is the first step of doing multiple scans processing
+        """
+        # Get inputs for exp number and scans
+        try:
+            rtup = self._uiGetExpScanTabMultiScans()
+            expno = rtup[0]
+            scanlist = rtup[1]
+        except NotImplementedError as nie:
+            self._logError("Unable to load data set in multiple scans due to %s." % (str(nie)))
+
+        # Load and reduce data
+        loadstatus = True
+        for scan in sorted(scanlist):
+            tempstatus = self.doLoadData(expno, scan)
+            if tempstatus is False:
+                self.ui.label_mergeMessage.setText('Error to load Exp %d Scan %d.'%(expno, scan))
+                loadstatus = False
+            else:
+                message = 'Loaded Exp %d Scan %d.' % (expno, scan)
+                self.ui.label_mergeMessage.setText(message)
+        # ENDFOR
+
+        # Load status
+        if loadstatus is True:
+            self.ui.label_mergeMessage.setText('All data files are loaded')
+        else:
+            self.ui.label_mergeMessage.setText('Not all data files are loaded')
+
+        # Wave length
+        haswavelength = True
+        for scan in scanlist:
+            if self._myControl.getWavelength(expno, scan) is None:
+                self._logNotice("Exp %d Scan %d has no wavelength set up." % (expno, scan))
+                haswavelength = False
+                break
+        # ENDFOR
+
+        # Set unit box
+        if haswavelength is True:
+            self.ui.comboBox_mscanUnit.clear()
+            self.ui.comboBox_mscanUnit.addItems(['2theta', 'dSpacing', 'Momentum Transfer (Q)'])
+        else:
+            self.ui.comboBox_mscanUnit.clear()
+            self.ui.comboBox_mscanUnit.addItems(['2theta'])
+
+        return
+
+
+    def doLoadReduceScanPrev(self):
+        """ Load and reduce previous scan for tab 'Normalized'
+        """
+        # Reduce scan number by 1
+        try:
+            scanno = int(self.ui.lineEdit_scanNo.text())
+        except ValueError:
+            self._logError("Either Exp No or Scan No is not set up right as integer.")
+            return
+        else:
+            scanno = scanno - 1
+            if scanno < 1:
+                self._logWarning("Scan number is 1 already.  Cannot have previous scan")
+                return
+            self.ui.lineEdit_scanNo.setText(str(scanno))
+
+        # Load data
+        self.ui.lineEdit_scanNo.setText(str(scanno))
+        self.doLoadData()
+
+        # Reduce data
+        self._uiReducePlotNoramlized(self._currUnit)
+
+        return
+
+
+    def doLoadReduceScanNext(self):
+        """ Load and reduce next scan for tab 'Normalized'
+        """
+        # Advance scan number by 1
+        try:
+            scanno = int(self.ui.lineEdit_scanNo.text())
+        except ValueError:
+            self._logError("Either Exp No or Scan No is not set up right as integer.")
+            return False
+        else:
+            scanno = scanno + 1
+            if scanno < 1:
+                self._logWarning("Scan number is 1 already.  Cannot have previous scan")
+                return False
+
+        # Load data
+        self.ui.lineEdit_scanNo.setText(str(scanno))
+        execstatus = self.doLoadData()
+        print "[DB] Load data : ", execstatus
+
+        # Reduce data
+        self._uiReducePlotNoramlized(self._currUnit)
+
+        return
+
+
+    def doMergeScans(self):
+        """ Merge several scans for tab 'merge'
+        """
+        # Get exp number and list of scans
+        try:
+            r = self._uiGetExpScanTabMultiScans()
+            expno = r[0]
+            scanlist = r[1]
+        except NotImplementedError as ne:
+            self._logError(str(ne))
+            return False
+
+        # Check whether the wavelengths are same to merge
+        try:
+            wl_list = []
+            for scanno in scanlist:
+                print "Exp %d Scan %d. Wavelength = %s." % (expno, scanno, str(self._myControl.getWavelength(expno, scanno)))
+                wl_list.append(float(self._myControl.getWavelength(expno, scanno)))
+
+            wl_list = sorted(wl_list)
+            min_wl = wl_list[0]
+            max_wl = wl_list[-1]
+            if max_wl - min_wl > 1.0:
+                self._logWarning("All scans do not have same wavelengths!")
+        except TypeError:
+            self._logError('Not all scans have wavelength set up.  Unable to merge scans.')
+            return
+
+        # Check!
+        try:
+            unit = str(self.ui.comboBox_mscanUnit.currentText())
+            xmin, binsize, xmax = self._uiGetBinningParams(itab=3)
+            #wavelength = min_wl
+            mindex = self._myControl.mergeReduceSpiceData(expno, scanlist, unit, xmin, xmax, binsize)
+        except Exception as e:
+            raise e
+
+        label = "Exp %d, Scan %s." % (expno, str(scanlist))
+        self._plotMergedReducedData(mindex, label)
+        self._lastMergeIndex = mindex
+        self._lastMergeLabel = label
+
+        return
+
+
+    def doMergeScanView1D(self):
+        """ Change the multiple runs to 1D
+        """
+        # Highlight the button's color
+        self.ui.pushButton_view2D.setStyleSheet('QPushButton {background-color: yellow; color: red;}')
+        self.ui.pushButton_view2D.setEnabled(True)
+        self.ui.pushButton_viewMScan1D.setStyleSheet('QPushButton {background-color: white; color: gray;}')
+        self.ui.pushButton_viewMScan1D.setEnabled(False)
+
+        # Process input experiment number and scan list
+        try:
+            r = self._uiGetExpScanTabMultiScans()
+            expno = r[0]
+            scanlist = r[1]
+        except NotImplementedError as e:
+            self._logError(str(e))
+            return False
+
+        # Clear image
+        canvas = self.ui.graphicsView_mergeRun
+        canvas.clearAllLines()
+        canvas.clearCanvas()
+
+        # Plot data
+        unit = str(self.ui.comboBox_mscanUnit.currentText())
+        xlabel = self._getXLabelFromUnit(unit)
+
+        for scanno in scanlist:
+            label = "Exp %s Scan %s"%(str(expno), str(scanno))
+            self._plotReducedData(expno, scanno, canvas, xlabel, label=label, clearcanvas=False)
+        # ENDFOR
+
+        return
+
+    def doMergeScanView2D(self):
+        """ Change the merged run's view to 2D plot
+        """
+        # Highlight button color and change the color of another one
+        self.ui.pushButton_view2D.setStyleSheet('QPushButton {background-color: white; color: gray;}')
+        self.ui.pushButton_view2D.setEnabled(False)
+        self.ui.pushButton_viewMScan1D.setStyleSheet('QPushButton {background-color: yellow; color: red;}')
+        self.ui.pushButton_viewMScan1D.setEnabled(True)
+
+        # Get list of data to plot
+        r = self._uiGetExpScanTabMultiScans()
+        expno = r[0]
+        scanlist = r[1]
+
+        # Convert the workspaces to 2D vector
+        vecylist = []
+        yticklabels = []
+        xmin = None
+        xmax = None
+        for scanno in scanlist:
+            # put y values to list for constructing 2D array
+            vecx, vecy = self._myControl.getVectorToPlot(expno, scanno)
+
+            vecylist.append(vecy)
+            yticklabels.append('Exp %d Scan %d' % (expno, scanno))
+            #print "[DB] Scan ", scanno, ": X range: ", vecx[0], vecx[-1], " Size X = ", len(vecx)
+
+            # set up range of x
+            if xmin is None:
+                xmin = vecx[0]
+                xmax = vecx[-1]
+            # ENDIF
+        # ENDFOR
+
+        dim2array = numpy.array(vecylist)
+
+        #print "2D vector: \n",  dim2array
+        #print "x range: %f, %f" % (xmin, xmax)
+        #print "y labels: ", yticklabels
+
+        # Plot
+        holdprev=False
+        self.ui.graphicsView_mergeRun.clearAllLines()
+        self.ui.graphicsView_mergeRun.addPlot2D(dim2array, xmin=xmin, xmax=xmax, ymin=0, \
+            ymax=len(vecylist), holdprev=holdprev, yticklabels=yticklabels)
+
+        return
+
+    def doMergeScanViewMerged(self):
+        """ Change the merged run's view to 1D plot
+        """
+        # Highlight the button's color
+        self.ui.pushButton_view2D.setStyleSheet('QPushButton {color: red;}')
+        self.ui.pushButton_view2D.setEnabled(True)
+        self.ui.pushButton_viewMScan1D.setStyleSheet('QPushButton {color: red;}')
+        self.ui.pushButton_viewMScan1D.setEnabled(True)
+
+        # Clear image
+        self.ui.graphicsView_mergeRun.clearCanvas()
+
+        # Plot
+        self._plotMergedReducedData(mkey=self._lastMergeIndex, label=self._lastMergeLabel)
+
+        return
+
+
+    def doPlotIndvDetMain(self):
+        """ Plot individual detector
+        """
+        # Get exp and scan numbers and check whether the data has been loaded
+        try:
+            expno = self._getInteger(self.ui.lineEdit_expNo)
+            scanno = self._getInteger(self.ui.lineEdit_scanNo)
+        except EmptyError as e:
+            self._logError(str(e))
+            return
+
+        # Get detector ID and x-label option
+        try:
+            detid = self._getInteger(self.ui.lineEdit_detID)
+        except EmptyError:
+            self._logError("Detector ID must be specified for plotting individual detector.")
+            return
+
+        # Over plot previous or clear
+        overplot = self.ui.checkBox_overPlotIndvDet.isChecked()
+        if overplot is False:
+            self.doClearIndDetCanvas()
+
+        xlabel = str(self.ui.comboBox_indvDetXLabel.currentText()).strip()
+        if xlabel != "" and xlabel != "Pt.":
+            self._logNotice("X-label %s is not supported for plotting individual detector's counts.  Set to detector angle." % (xlabel))
+            xlabel = ""
+        else:
+            self._logNotice("X-label for individual detectror is %s." % (xlabel))
+
+        # plot
+        try:
+            self._plotIndividualDetCounts(expno, scanno, detid, xlabel)
+            self._expNo = expno
+            self._scanNo = scanno
+            self._detID = detid
+            self._indvXLabel = xlabel
+        except NotImplementedError as e:
+            self._logError(str(e))
+
+        return
+
+    def doPlotIndvDetNext(self):
+        """ Plot next raw detector signals for tab 'Individual Detector'
+        """
+        # Plot
+        try:
+            currdetid = self._detID + 1
+
+            # Over plot previous or clear
+            overplot = self.ui.checkBox_overPlotIndvDet.isChecked()
+            if overplot is False:
+                self.doClearIndDetCanvas()
+
+            self._plotIndividualDetCounts(self._expNo, self._scanNo, currdetid,
+                    self._indvXLabel)
+        except KeyError as e:
+            self._logError(str(e))
+        else:
+            self._detID = currdetid
+
+        # Update widget
+        self.ui.lineEdit_detID.setText(str(self._detID))
+
+        return
+
+    def doPlotIndvDetPrev(self):
+        """ Plot previous individual detector's signal for tab 'Individual Detector'
+        """
+        # Plot
+        try:
+            currdetid = self._detID - 1
+
+            # Over plot previous or clear
+            overplot = self.ui.checkBox_overPlotIndvDet.isChecked()
+            if overplot is False:
+                self.doClearIndDetCanvas()
+
+            self._plotIndividualDetCounts(self._expNo, self._scanNo, currdetid,
+                    self._indvXLabel)
+        except KeyError as e:
+            self._logError(str(e))
+        else:
+            self._detID = currdetid
+
+        # Update widget
+        self.ui.lineEdit_detID.setText(str(self._detID))
+
+        return
+
+
+    def doPlotRawPtMain(self):
+        """ Plot current raw detector signal for a specific Pt.
+        """
+        # Get experiment number and scan number for data file
+        try:
+            expno = self._getInteger(self.ui.lineEdit_expNo)
+            scanno = self._getInteger(self.ui.lineEdit_scanNo)
+        except EmptyError as e:
+            self._logError(str(e))
+            return
+
+        # plot options
+        doOverPlot = bool(self.ui.checkBox_overpltRawDet.isChecked())
+        plotmode = str(self.ui.comboBox_rawDetMode.currentText())
+        try:
+            ptNo = self._getInteger(self.ui.lineEdit_ptNo)
+        except EmptyError:
+            ptNo = None
+
+        # plot
+        print "[DB] Plot Raw Detector: PlotMode = %s." % (plotmode)
+        execstatus = self._plotRawDetSignal(expno, scanno, plotmode, ptNo, doOverPlot)
+
+        # set global values if good
+        if execstatus is True:
+            self._rawDetPtNo = ptNo
+            self._rawDetExpNo = expno
+            self._rawDetScanNo = scanno
+            self._rawDetPlotMode = plotmode
+        else:
+            print "[Error] Execution fails with signal %s. " % (str(execstatus))
+
+        return
+
+
+    def doPlotRawPtNext(self):
+        """ Plot next raw detector signals
+        """
+        # Check
+        if self._rawDetPtNo is not None:
+            ptno = self._rawDetPtNo + 1
+        else:
+            self._logError("Unable to plot previous raw detector \
+                    because Pt. or Detector ID has not been set up yet.")
+            return
+        # ENDIFELSE
+
+        # Get plot mode and plot
+        plotmode = str(self.ui.comboBox_rawDetMode.currentText())
+        overplot = bool(self.ui.checkBox_overpltRawDet.isChecked())
+        execstatus = self._plotRawDetSignal(self._rawDetExpNo, self._rawDetScanNo, plotmode,
+                ptno, overplot)
+
+        # update if it is good to plot
+        if execstatus is True:
+            self._rawDetPtNo = ptno
+            self.ui.lineEdit_ptNo.setText(str(ptno))
+
+        return
+
+
+    def doPlotRawPtPrev(self):
+        """ Plot previous raw detector
+        """
+        # Validate input
+        if self._rawDetPtNo is not None:
+            ptno = self._rawDetPtNo - 1
+        else:
+            self._logError("Unable to plot previous raw detector \
+                    because Pt. or Detector ID has not been set up yet.")
+            return
+
+        # get plot mode and do plt
+        plotmode = str(self.ui.comboBox_rawDetMode.currentText())
+        overplot = bool(self.ui.checkBox_overpltRawDet.isChecked())
+        execstatus = self._plotRawDetSignal(self._rawDetExpNo, self._rawDetScanNo, plotmode,
+                ptno, overplot)
+
+        # update if it is good to plot
+        if execstatus is True:
+            self._rawDetPtNo = ptno
+            self.ui.lineEdit_ptNo.setText(str(ptno))
+
+        return
+
+    def doPlotSampleLog(self):
+        """ Plot sample log vs. Pt. in tab 'Individual Detector'
+        """
+        expno =  int(self.ui.lineEdit_expNo.text())
+        scanno = int(self.ui.lineEdit_scanNo.text())
+        logname = str(self.ui.comboBox_indvDetYLabel.currentText())
+        self._plotSampleLog(expno, scanno, logname)
+
+        return
+
+
+    def doReduce2Theta(self):
+        """ Rebin the data and plot in 2theta for tab 'Normalized'
+        """
+        unit = '2theta'
+        self._uiReducePlotNoramlized(unit)
+
+        return
+
+
+    def doReduceDSpacing(self):
+        """ Rebin the data and plot in d-spacing for tab 'Normalized'
+        """
+        # new unit and information
+        unit = "dSpacing"
+        self._uiReducePlotNoramlized(unit)
+
+        return
+
+
+    def doReduceQ(self):
+        """ Rebin the data and plot in momentum transfer Q for tab 'Normalized'
+        """
+        unit = 'Momentum Transfer (Q)'
+        self._uiReducePlotNoramlized(unit)
+
+        return
+
+
+    def doReduceSetData(self):
+        """ Reduce multiple data
+        """
+        # Get exp number and list of scans
+        try:
+            r = self._uiGetExpScanTabMultiScans()
+            expno = r[0]
+            scanlist = r[1]
+        except NotImplementedError as e:
+            self._logError(str(e))
+            return False
+
+        # Reduce and plot data
+        unit = str(self.ui.comboBox_mscanUnit.currentText())
+        xlabel = self._getXLabelFromUnit(unit)
+
+        canvas = self.ui.graphicsView_mergeRun
+        canvas.clearAllLines()
+        canvas.clearCanvas()
+
+        for scan in scanlist:
+            r = self._uiReduceData(3, unit, expno, scan)
+            good = r[0]
+            expno = r[1]
+            scanno = r[2]
+
+            if good is True:
+                label = "Exp %s Scan %s"%(str(expno), str(scanno))
+                self._plotReducedData(expno, scanno, canvas, xlabel, label=label, clearcanvas=False)
+            else:
+                self._logError('Failed to reduce Exp %s Scan %s'%(str(expno), str(scanno)))
+            # ENDIF
+        # ENDFOR
+
+        return
+
+
+    def doReduceVanadium2Theta(self):
+        """ Rebin MDEventWorkspaces in 2-theta. for pushButton_rebinD
+        in vanadium peak strip tab
+
+        Suggested workflow
+        1. Rebin data
+        2. Calculate vanadium peaks in 2theta
+        3.
+        """
+        # Reduce data
+        unit = '2theta'
+        itab = 4
+        r = self._uiReduceData(itab, unit)
+        good = r[0]
+        expno = r[1]
+        scanno = r[2]
+
+        # Plot reduced data and vanadium peaks
+        if good is True:
+            canvas = self.ui.graphicsView_vanPeaks
+            xlabel = self._getXLabelFromUnit(unit)
+            label = "Exp %s Scan %s"%(str(expno), str(scanno))
+            self._plotReducedData(expno, scanno, canvas, xlabel, label=label, clearcanvas=True)
+
+            # plot vanadium peaks
+            vanpeakpos = self._myControl.getVanadiumPeaksPos(expno, scanno)
+            self.ui.lineEdit_stripVPeaks.setText(str(vanpeakpos))
+            self._plotPeakIndicators(self.ui.graphicsView_vanPeaks, vanpeakpos)
+
+        return good
+
+
+    def doSaveData(self):
+        """ Save data
+        """
+        # get exp number and scan number
+        try:
+            # exp and scan
+            expno, scanno = self._uiGetExpScanNumber()
+            # file type
+            filetype = str(self.ui.comboBox_outputFormat.currentText())
+            # file name
+            savedatadir = str(self.ui.lineEdit_outputFileName.text()).strip()
+            if savedatadir != None and os.path.exists(savedatadir) is True:
+                homedir = savedatadir
+            else:
+                homedir = os.getcwd()
+            # launch a dialog to get data
+            filefilter = "All files (*.*);;Fullprof (*.dat);;GSAS (*.gsa)"
+            sfilename = str(QtGui.QFileDialog.getSaveFileName(self, 'Save File', homedir, filefilter))
+        except NotImplementedError as e:
+            self._logError(str(e))
+        else:
+            self._myControl.savePDFile(expno, scanno, filetype, sfilename)
+
+        return
+
+    def doSaveMergedScan(self):
+        """ Save merged scan
+        """
+        homedir = os.getcwd()
+        filefilter = "Fullprof (*.dat)"
+        sfilename = str(QtGui.QFileDialog.getSaveFileName(self, 'Save File In Fullprof', homedir, filefilter))
+
+        self._myControl.saveMergedScan(sfilename, mergeindex=self._lastMergeIndex)
+
+        return
+
+
+    def doSaveMultipleScans(self):
+        """ Save multiple scans
+        """
+        # Get experiment number and scans
+        r = self._uiGetExpScanTabMultiScans()
+        expno = r[0]
+        scanslist = r[1]
+
+        # Get base file name
+        homedir = os.getcwd()
+        savedir = str(QtGui.QFileDialog.getExistingDirectory(self,'Get Directory To Save Fullprof',homedir))
+
+        for scanno in scanslist:
+            sfilename = os.path.join(savedir, "HB2A_Exp%d_Scan%d_FP.dat"%(expno, scanno))
+            self._myControl.savePDFile(expno, scanno, 'fullprof', sfilename)
+        # ENDFOR
+
+        return
+
+
+    def doSaveVanRun(self):
+        """ Save the vanadium run with peaks removed
+        """
+        # Get experiment number and scan number
+        try:
+            expno, scanno = self._uiGetExpScanNumber()
+        except NotImplementedError as e:
+            self._logError("Unable to get exp number and scan number for smoothing vanadium data due to %s." % (
+                str(e)))
+            return False
+
+        homedir = os.getcwd()
+        filefilter = "Fullprof (*.dat)"
+        sfilename = str(QtGui.QFileDialog.getSaveFileName(self, 'Save File In Fullprof', homedir, filefilter))
+
+        self._myControl.saveProcessedVanadium(expno, scanno, sfilename)
+
+        return
+
+
+    def doSmoothVanadiumData(self):
+        """ Smooth vanadium spectrum
+        """
+        # Get experiment number and scan number
+        try:
+            expno, scanno = self._uiGetExpScanNumber()
+        except NotImplementedError as e:
+            self._logError("Unable to get exp number and scan number for smoothing vanadium data due to %s." % (
+                str(e)))
+            return False
+
+        smoothparams_str = str(self.ui.lineEdit_smoothParams.text())
+        # Smooth data
+        status = self._myControl.smoothVanadiumSpectrum(expno, scanno, smoothparams_str)
+        if status is False:
+            self._logError("Failed to smooth vanadium data")
+
+        # Plot
+        unit = '2theta'
+        xlabel = self._getXLabelFromUnit(unit)
+        label = "Vanadium Exp %d Scan %d FFT-Smooth by %s" % (expno, scanno, smoothparams_str)
+        self._plotVanadiumRun(expno, scanno, xlabel, label, False, True)
+
+        return
+
+    def doSmoothVanadiumApply(self):
+        """ Apply smoothing effect to vanadium data
+        """
+        # Get experiment number and scan number
+        try:
+            expno, scanno = self._uiGetExpScanNumber()
+        except NotImplementedError as e:
+            self._logError("Unable to get exp number and scan number for smoothing vanadium data due to %s." % (
+                str(e)))
+            return False
+
+        self._myControl.applySmoothVanadium(expno, scanno, True)
+
+        return
+
+
+    def doSmoothVanadiumUndo(self):
+        """ Undo smoothing vanadium
+        """
+        try:
+            expno, scanno = self._uiGetExpScanNumber()
+        except NotImplementedError as e:
+            self._logError("Unable to get exp number and scan number for smoothing vanadium data due to %s." % (
+                str(e)))
+            return False
+
+        self._myControl.applySmoothVanadium(expno, scanno, False)
+
+        return
+
+    def doStripVandiumPeaks(self):
+        """ Strip vanadium peaks
+        """
+        # Get exp number an scan number
+        try:
+            expno, scanno = self._uiGetExpScanNumber()
+        except NotImplementedError as e:
+            self._logError("Error to get Exp and Scan due to %s." % (str(e)))
+            return False
+
+        # Default unit
+        unit = '2theta'
+
+        # Get and build binning parameter
+        xmin, binsize, xmax = self._uiGetBinningParams(itab=4)
+        if xmin is None:
+            binparams = '%f'%(binsize)
+        else:
+            binparams = '%f,%f,%f'%(xmin, binsize, xmax)
+
+        # Strip vanadium peak
+        good = self._myControl.stripVanadiumPeaks(expno, scanno, binparams, vanpeakposlist=None)
+
+        # Plot
+        if good is True:
+            xlabel = self._getXLabelFromUnit(unit)
+            label="Exp %d Scan %d Bin = %.5f Vanadium Stripped" % (expno, scanno, binsize)
+            self._plotVanadiumRun(expno, scanno, xlabel, label, False)
+
+
+        return
+
+
+    def doUpdateWavelength(self):
+        """ Update the wavelength to line edit
+        """
+        index = self.ui.comboBox_wavelength.currentIndex()
+
+        print "Update wavelength to ", index
+
+        if index == 0:
+            wavelength = 2.41
+        elif index == 1:
+            wavelength = 1.54
+        elif index == 2:
+            wavelength = 1.12
+        else:
+            wavelength = None
+
+        self.ui.lineEdit_wavelength.setText(str(wavelength))
+
+        return
+
+    def on_mouseDownEvent(self, event):
+        """ Respond to pick up a value with mouse down event
+        Definition of button_press_event is:
+          button_press_event(x, y, button, dblclick=False, guiEvent=None)
+        Thus event has x, y and button.
+
+        event.button has 3 values:
+         1: left
+         2: middle
+         3: right
+        """
+        # FUTURE: Need to make this work
+        x = event.xdata
+        y = event.ydata
+        button = event.button
+
+
+        if x is not None and y is not None:
+
+            if button == 1:
+                msg = "You've clicked on a bar with coords:\n %f, %f\n and button %d" % (x, y, button)
+                QtGui.QMessageBox.information(self, "Click!", msg)
+
+            elif button == 3:
+                # right click of mouse will pop up a context-menu
+                # menu should be self.ui.menu?
+                menu = QtGui.QMenu(self)
+
+                addAction = QtGui.QAction('Add', self)
+                addAction.triggered.connect(self.addSomething)
+                menu.addAction(addAction)
+
+                rmAction = QtGui.QAction('Remove', self)
+                rmAction.triggered.connect(self.rmSomething)
+                menu.addAction(rmAction)
+
+                # add other required actions
+                menu.popup(QtGui.QCursor.pos())
+        # ENDIF
+
+        return
+
+
+
+    def on_mouseMotion(self, event):
+        """
+        """
+        #prex = self._viewMerge_X
+        prey = self._viewMerge_Y
+
+        curx = event.xdata
+        cury = event.ydata
+        if curx is None or cury  is None:
+            return
+
+        self._viewMerge_X = event.xdata
+        self._viewMerge_Y = event.ydata
+
+        if prey is None or int(prey) != int(self._viewMerge_Y):
+            print "Mouse is moving to ", event.xdata, event.ydata
+
+        return
+
+
+    def addSomething(self):
+        """
+        """
+        print "Add scan back to merge"
+
+        return
+
+
+    def rmSomething(self):
+        """
+        """
+        print "Remove a scan from mergin."
+
+        return
+
+    #--------------------------------------------------------------------------
+    # Private methods to plot data
+    #--------------------------------------------------------------------------
+
+    def _plotIndividualDetCounts(self, expno, scanno, detid, xaxis):
+        """ Plot a specific detector's counts along all experiment points (pt)
+        """
+        # Validate input
+        expno = int(expno)
+        scanno = int(scanno)
+        detid = int(detid)
+
+        # Reject if data is not loaded
+        if self._myControl.hasDataLoaded(expno, scanno) is False:
+            self._logError("Data file for Exp %d Scan %d has not been loaded." % (expno, scanno))
+            return False
+
+        # Canvas and line information
+        canvas = self.ui.graphicsView_indvDet
+        if self._tabLineDict.has_key(canvas) is False:
+            self._tabLineDict[canvas] = []
+
+        # get data
+        self._logNotice("X-axis is %s."%(xaxis))
+        vecx, vecy = self._myControl.getIndividualDetCounts(expno, scanno, detid, xaxis)
+
+        # Plot to canvas
+        marker, color = canvas.getNextLineMarkerColorCombo()
+        if xaxis == "":
+            xlabel = r'$2\theta$'
+        else:
+            xlabel = "Pt."
+
+        label = "Detector ID: %d" % (detid)
+
+        if self._tabLineDict[canvas].count( (expno, scanno, detid) ) == 0:
+            canvas.addPlot(vecx, vecy, marker=marker, color=color, xlabel=xlabel, \
+                ylabel='Counts',label=label)
+            self._tabLineDict[canvas].append( (expno, scanno, detid) )
+
+            # auto setup for image boundary
+            xmin = min(min(vecx), canvas.getXLimit()[0])
+            xmax = max(max(vecx), canvas.getXLimit()[1])
+            ymin = min(min(vecy), canvas.getYLimit()[0])
+            ymax = max(max(vecy), canvas.getYLimit()[1])
+
+            dx = xmax-xmin
+            dy = ymax-ymin
+            canvas.setXYLimit(xmin-dx*0.0001, xmax+dx*0.0001, ymin-dy*0.0001, ymax+dy*0.0001)
+
+        return True
+
+
+    def _plotPeakIndicators(self, canvas, peakposlist):
+        """ Plot indicators for peaks
+        """
+        print "[DB] Peak indicators are at ", peakposlist
+
+        rangey = canvas.getYLimit()
+        rangex = canvas.getXLimit()
+
+        for pos in peakposlist:
+            if pos >= rangex[0] and pos <= rangex[1]:
+                vecx = numpy.array([pos, pos])
+                vecy = numpy.array([rangey[0], rangey[1]])
+                canvas.addPlot(vecx, vecy, color='black', linestyle='--')
+        # ENDFOR
+
+        return
+
+
+    def _plotRawDetSignal(self, expno, scanno, plotmode, ptno, dooverplot):
+        """ Plot the counts of all detectors of a certain Pt. in an experiment
+        """
+        # Validate input
+        expno = int(expno)
+        scanno = int(scanno)
+
+        # Set up canvas and dictionary
+        canvas = self.ui.graphicsView_Raw
+        if self._tabLineDict.has_key(canvas) is False:
+            self._tabLineDict[canvas] = []
+
+        # Check whether data exists
+        if self._myControl.hasDataLoaded(expno, scanno) is False:
+            self._logError("File has not been loaded for Exp %d Scan %d.  Load data first!" % (expno, scanno))
+            return
+
+        # Get vecx and vecy
+        if plotmode == "All Pts.":
+            # Plot all Pts.
+            vecxylist = self._myControl.getRawDetectorCounts(expno, scanno)
+
+            # Clear previous
+            self.ui.graphicsView_Raw.clearAllLines()
+            self.ui.graphicsView_Raw.setLineMarkerColorIndex(0)
+            self._tabLineDict[canvas] = []
+
+        elif plotmode == "Single Pts.":
+            # Plot plot
+            ptno = int(ptno)
+
+            if dooverplot is False:
+                self.ui.graphicsView_Raw.clearAllLines()
+                self.ui.graphicsView_Raw.setLineMarkerColorIndex(0)
+                self._tabLineDict[canvas] = []
+
+            # Plot one pts.
+            vecxylist = self._myControl.getRawDetectorCounts(expno, scanno, [ptno])
+
+        else:
+            # Raise exception
+            raise NotImplementedError("Plot mode %s is not supported." % (plotmode))
+
+        # Set up unit/x-label
+        unit = r"$2\theta$"
+
+        # plot
+        xmin = None
+        xmax = None
+        ymin = None
+        ymax = None
+        for ptno, vecx, vecy in vecxylist:
+            # FUTURE: Label is left blank as there can be too many labels
+            label = 'Pt %d' % (ptno)
+
+            # skip if this plot has existed
+            if self._tabLineDict[canvas].count( (expno, scanno, ptno) ) == 1:
+                continue
+
+            marker, color = canvas.getNextLineMarkerColorCombo()
+            canvas.addPlot(vecx, vecy, marker=marker, color=color, xlabel=unit, \
+                    ylabel='intensity',label=label)
+
+            # set up line tuple
+            self._tabLineDict[canvas].append( (expno, scanno, ptno) )
+
+            # auto setup for image boundary
+            xmin = min(min(vecx), canvas.getXLimit()[0])
+            xmax = max(max(vecx), canvas.getXLimit()[1])
+            ymin = min(min(vecy), canvas.getYLimit()[0])
+            ymax = max(max(vecy), canvas.getYLimit()[1])
+        # ENDFOR
+
+        # Reset canvas x-y limit
+        if xmin is not None:
+            dx = xmax-xmin
+            dy = ymax-ymin
+            canvas.setXYLimit(xmin-dx*0.0001, xmax+dx*0.0001, ymin-dy*0.0001, ymax+dy*0.0001)
+
+        return True
+
+
+    def _plotMergedReducedData(self, mkey, label):
+        """ Plot the reduced data from merged ...
+        """
+        # get the data
+        try:
+            vecx, vecy = self._myControl.getMergedVector(mkey)
+        except KeyError as e:
+            self._logError("Unable to retrieve merged reduced data due to %s." % (str(e)))
+            return
+
+        canvas = self.ui.graphicsView_mergeRun
+
+        # Clear canvas
+        canvas.clearAllLines()
+        canvas.clearCanvas()
+
+        # Plot
+        marker, color = canvas.getNextLineMarkerColorCombo()
+        xlabel = self._getXLabelFromUnit(self.ui.comboBox_mscanUnit.currentText())
+
+        canvas.addPlot(vecx, vecy, marker=marker, color=color,
+            xlabel=xlabel, ylabel='intensity',label=label)
+
+        xmax = max(vecx)
+        xmin = min(vecx)
+        dx = xmax-xmin
+
+        ymax = max(vecy)
+        ymin = min(vecy)
+        dy = ymax-ymin
+
+        canvas.setXYLimit(xmin-dx*0.1, xmax+dx*0.1, ymin-dy*0.1, ymax+dy*0.1)
+
+        return
+
+
+
+    def _plotReducedData(self, exp, scan, canvas, xlabel, label=None, clearcanvas=True,
+        spectrum=0):
+        """ Plot reduced data for exp and scan
+         self._plotReducedData(exp, scan, self.ui.canvas1, clearcanvas, xlabel=self._currUnit, 0, clearcanvas)
+        """
+        if spectrum != 0:
+            raise NotImplementedError("Unable to support spectrum = %d case."%(spectrum))
+
+        # whether the data is load
+        if self._myControl.hasReducedWS(exp, scan) is False:
+            self._logWarning("No data to plot!")
+            return
+
+        # get to know whether it is required to clear the image
+        if clearcanvas is True:
+            canvas.clearAllLines()
+            canvas.setLineMarkerColorIndex(0)
+            #self.ui.graphicsView_reducedData.clearAllLines()
+            #self._myLineMarkerColorIndex = 0
+
+        # plot
+        vecx, vecy = self._myControl.getVectorToPlot(exp, scan)
+
+
+        # get the marker color for the line
+        marker, color = canvas.getNextLineMarkerColorCombo()
+
+        # plot
+        if label is None:
+            label = "Exp %d Scan %d" % (exp, scan)
+
+        canvas.addPlot(vecx, vecy, marker=marker, color=color,
+            xlabel=xlabel, ylabel='intensity',label=label)
+
+        if clearcanvas is True:
+            xmax = max(vecx)
+            xmin = min(vecx)
+            dx = xmax-xmin
+
+            ymax = max(vecy)
+            ymin = min(vecy)
+            dy = ymax-ymin
+
+            canvas.setXYLimit(xmin-dx*0.1, xmax+dx*0.1, ymin-dy*0.1, ymax+dy*0.1)
+
+        return
+
+    def _plotSampleLog(self, expno, scanno, samplelogname):
+        """ Plot the value of a sample log among all Pt.
+        """
+        # Validate input
+        expno = int(expno)
+        scanno = int(scanno)
+        samplelogname = str(samplelogname)
+
+        # Reject if data is not loaded
+        if self._myControl.hasDataLoaded(expno, scanno) is False:
+            self._logError("Data file for Exp %d Scan %d has not been loaded." % (expno, scanno))
+            return False
+
+        # Canvas and line information
+        self._indvDetCanvasMode = 'samplelog'
+
+        # pop out the xlabel list
+        # REFACTOR - Only need to set up once if previous plot has the same setup
+        floatsamplelognamelist = self._myControl.getSampleLogNames(expno, scanno)
+        self.ui.comboBox_indvDetXLabel.clear()
+        self.ui.comboBox_indvDetXLabel.addItems(floatsamplelognamelist)
+
+        xlabel=str(self.ui.comboBox_indvDetXLabel.currentText())
+
+        # get data
+        vecx, vecy = self._myControl.getSampleLogValue(expno, scanno, samplelogname, xlabel)
+
+        # Plot to canvas
+        canvas = self.ui.graphicsView_indvDet
+        canvas.clearAllLines()
+
+        marker, color = canvas.getNextLineMarkerColorCombo()
+        if xlabel is None:
+            xlabel = r'Pt'
+
+        label = samplelogname
+
+        canvas.addPlot(vecx, vecy, marker=marker, color=color, xlabel=xlabel, \
+            ylabel='Counts',label=label)
+
+        # auto setup for image boundary
+        xmin = min(vecx)
+        xmax = max(vecx)
+        ymin = min(vecy)
+        ymax = max(vecy)
+
+        dx = xmax-xmin
+        dy = ymax-ymin
+        canvas.setXYLimit(xmin-dx*0.0001, xmax+dx*0.0001, ymin-dy*0.0001, ymax+dy*0.0001)
+
+        return True
+
+
+    def _plotVanadiumRun(self, exp, scan, xlabel, label, clearcanvas=False, TempData=False):
+        """ Plot processed vanadium data
+
+        Arguments:
+         - TempData :: flag whether the vanadium run is a temporary data set
+        """
+        # Check whether the data is load
+        exp = int(exp)
+        scan = int(scan)
+
+        if self._myControl.hasReducedWS(exp, scan) is False:
+            self._logWarning("No data to plot!")
+            return
+
+        # Get data to plot
+        try:
+            vecx, vecy = self._myControl.getVectorProcessVanToPlot(exp, scan, TempData)
+            if TempData is False:
+                vecx, vecyOrig = self._myControl.getVectorToPlot(exp, scan)
+                diffY = vecyOrig - vecy
+        except NotImplementedError as e:
+            print '[Error] Unable to retrieve processed vanadium spectrum for exp %d scan %d.  \
+                    Reason: %s' % (exp, scan, str(e))
+            return
+
+        # Get to know whether it is required to clear the image
+        canvas = self.ui.graphicsView_vanPeaks
+        if TempData is True:
+            clearcanvas = False
+        if clearcanvas is True:
+            canvas.clearAllLines()
+            canvas.setLineMarkerColorIndex(0)
+
+        # get the marker color for the line
+        if TempData is True:
+            marker = None
+            color = 'blue'
+        else:
+            marker, color = canvas.getNextLineMarkerColorCombo()
+
+        # plot
+        canvas.addPlot(vecx, vecy, marker=marker, color=color,
+            xlabel=xlabel, ylabel='intensity',label=label)
+
+        if TempData is False:
+            canvas.addPlot(vecx, diffY, marker='+', color='green',
+                xlabel=xlabel, ylabel='intensity',label='Diff')
+
+        # reset canvas limits
+        if clearcanvas is True:
+            xmax = max(vecx)
+            xmin = min(vecx)
+            dx = xmax-xmin
+
+            ymax = max(vecy)
+            ymin = min(diffY)
+            dy = ymax-ymin
+
+            canvas.setXYLimit(xmin-dx*0.1, xmax+dx*0.1, ymin-dy*0.1, ymax+dy*0.1)
+        # ENDIF
+
+        return
+
+
+    def _uiDownloadDataFile(self, exp, scan):
+        """ Download data file according to its exp and scan
+        Either download the data from a server or copy the data file from local
+        disk
+        """
+        # Get on hold of raw data file
+        useserver = self.ui.radioButton_useServer.isChecked()
+        uselocal = self.ui.radioButton_useLocal.isChecked()
+        if (useserver and uselocal) is False:
+            self._logError("It is logically wrong to set up server/local dir for data.")
+            useserver = True
+            uselocal = False
+            self.ui.radioButton_useServer.setChecked(True)
+            self.ui.radioButton_useLocal.setChecked(False)
+        # ENDIF
+
+        rvalue = False
+        if self._srcFromServer is True:
+            # Use server: build the URl to download data
+            if self._serverAddress.endswith('/') is False:
+                self._serverAddress += '/'
+            fullurl = "%s%s/exp%d/Datafiles/%s_exp%04d_scan%04d.dat" % (self._serverAddress,
+                    self._instrument.lower(), exp, self._instrument.upper(), exp, scan)
+            print "URL: ", fullurl
+
+            cachedir = str(self.ui.lineEdit_cache.text()).strip()
+            if os.path.exists(cachedir) is False:
+                invalidcache = cachedir
+                cachedir = os.getcwd()
+                self.ui.lineEdit_cache.setText(cachedir)
+                self._logWarning("Cache directory %s is not valid. \
+                    Using current workspace directory %s as cache." % (invalidcache, cachedir) )
+
+            filename = '%s_exp%04d_scan%04d.dat' % (self._instrument.upper(), exp, scan)
+            srcFileName = os.path.join(cachedir, filename)
+            status, errmsg = downloadFile(fullurl, srcFileName)
+            if status is False:
+                self._logError(errmsg)
+                srcFileName = None
+            else:
+                rvalue = True
+
+        elif self._srcAtLocal is True:
+            # Data from local
+            srcFileName = os.path.join(self._localSrcDataDir, "%s/Exp%d_Scan%04d.dat" % (self._instrument, exp, scan))
+            if os.path.exists(srcFileName) is True:
+                rvalue = True
+
+        else:
+            raise NotImplementedError("Logic error.  Neither downloaded from server.\
+                Nor from local drive")
+
+        return (rvalue,srcFileName)
+
+
+    def _uiGetBinningParams(self, itab):
+        """ Get binning parameters
+
+        Return:
+         - xmin, binsize, xmax
+        """
+        # Get value
+        if itab == 2:
+            xmin = str(self.ui.lineEdit_xmin.text())
+            xmax = str(self.ui.lineEdit_xmax.text())
+            binsize = str(self.ui.lineEdit_binsize.text())
+        elif itab == 3:
+            xmin = str(self.ui.lineEdit_mergeMinX.text())
+            xmax = str(self.ui.lineEdit_mergeMaxX.text())
+            binsize = str(self.ui.lineEdit_mergeBinSize.text())
+        elif itab == 4:
+            xmin = str(self.ui.lineEdit_min2Theta.text())
+            xmax = str(self.ui.lineEdit_max2Theta.text())
+            binsize = str(self.ui.lineEdit_binsize2Theta.text())
+        else:
+            raise NotImplementedError("Binning parameters are not used for %d-th tab."%(itab))
+
+        # Parse values
+        try:
+            xmin = float(xmin)
+            xmax = float(xmax)
+        except ValueError:
+            xmin = None
+            xmax = None
+        else:
+            if xmin >= xmax:
+                raise NotImplementedError("set minimum X = %.5f is larger than \
+                    maximum X = %.5f" % (xmin, xmax))
+
+        try:
+            binsize = float(binsize)
+        except ValueError:
+            raise NotImplementedError("Error:  bins size '%s' is not a float number." % (binsize))
+
+        # Fix for merging as xmin and xmax must be same for all scans
+        if itab == 3 and xmin is None:
+            xmin = 5.
+            xmax = 150.
+
+        return (xmin, binsize, xmax)
+
+
+    def _uiGetExcludedDetectors(self):
+        """ Get excluded detectors from input line edit
+
+        Return :: list of detector IDs to exclude from reduction
+        """
+        excludedetidlist = []
+
+        if self.ui.checkBox_useDetExcludeFile.isChecked():
+            detids_str = str(self.ui.lineEdit_detExcluded.text()).strip()
+            status, excludedetidlist = self._getIntArray(detids_str)
+            if status is False:
+                self._logError("Extra scans are not a list of integers: %s." % (
+                    str(self.ui.lineEdit_extraScans.text())))
+                excludedetidlist = []
+            # ENDIF
+        # ENDIF
+
+        return excludedetidlist
+
+
+
+    def _uiGetExpScanNumber(self):
+        """ Get experiment number and scan number from widgets for merged
+        """
+        expnostr = self.ui.lineEdit_expNo.text()
+        scannostr = self.ui.lineEdit_scanNo.text()
+        try:
+            expno = int(expnostr)
+            scanno = int(scannostr)
+        except ValueError:
+            raise NotImplementedError("Either Exp No '%s' or Scan No '%s \
+                is not set up right as integer." % (expnostr, scannostr))
+
+        return (expno, scanno)
+
+
+    def _uiGetExpScanTabMultiScans(self):
+        """ Get exp number and scans from tab 3
+        """
+        try:
+            expno = int(self.ui.lineEdit_expNo.text())
+            startscan = int(self.ui.lineEdit_scanStart.text())
+            endscan = int(self.ui.lineEdit_scanEnd.text())
+        except ValueError as e:
+            raise RuntimeError("For merging scans, Exp No, Starting scan number and \
+                    end scan number must be given: %s" % (str(e)))
+
+        # scans = [startscan, endscan] + [others] - [excluded]
+        status, extrascanlist = self._getIntArray(str(self.ui.lineEdit_extraScans.text()))
+        if status is False:
+            raise RuntimeError(extrascanlsit)
+
+        status, excludedlist = self._getIntArray(str(self.ui.lineEdit_exclScans.text()))
+        self._logDebug("Excluded list: %s" %(str(excludedlist)))
+        if status is False:
+            self._logError(excludedlist)
+            return
+
+        scanslist = range(startscan, endscan+1)
+        scanslist.extend(extrascanlist)
+        scanslist = list(set(scanslist))
+        for scan in excludedlist:
+            scanslist.remove(scan)
+
+        return (expno, sorted(scanslist))
+
+
+    def _uiIsBinParamsChange(self, itab, binparams):
+        """ Check whether current bin parameters are same
+        as given value
+        """
+        xmin,binsize,xmax = self._uiGetBinningParams(itab)
+        newbinparams = [xmin, binsize, xmax]
+
+        # check binning
+        same = True
+        for i in xrange(3):
+            par_0 = binparams[i]
+            par_1 = newbinparams[i]
+
+            try:
+                if abs(float(par_0)-float(par_1)) > 1.0E-6:
+                    same = False
+            except TypeError:
+                if par_0 is not None or par_1 is not None:
+                    same = False
+
+            if same is False:
+                break
+        # ENDFOR
+
+        change = not same
+        if change is True:
+            print "[D...............B]",
+            print "%s vs %s "  % (str(xmin), str(self._tabBinParamDict[itab][0])),
+            print "%s vs %s "  % (str(xmax), str(self._tabBinParamDict[itab][2])),
+            print "%s vs %s "  % (str(binsize), str(self._tabBinParamDict[itab][1]))
+        else:
+            print "[DB] Rebin = False"
+
+        return change
+
+
+    def _uiReduceData(self, itab, unit, expno=None, scanno=None):
+        """ Rebin and plot by reading GUI widgets' value
+
+        Arguments:
+         - itab : index of the tab.  Only 2m 3 and 4 are allowed
+         - unit : string for target unit
+        """
+        # Experiment number and Scan number
+        if isinstance(expno, int) and isinstance(scanno, int):
+            # Call from tab-3 multiple scan
+            pass
+        else:
+            try:
+                expno, scanno = self._uiGetExpScanNumber()
+            except NotImplementedError as e:
+                self._logError(str(e))
+                return
+        # ENDIF
+
+        # Get binning parameter
+        xmin, binsize, xmax = self._uiGetBinningParams(itab)
+
+        # Get wavelength
+        try:
+            if itab == 3:
+                wavelength = float(self._myControl.getWavelength(expno, scanno))
+            else:
+                wavelength = float(str(self.ui.lineEdit_wavelength.text()))
+        except TypeError:
+            if unit != '2theta':
+                raise NotImplementedError('Wavelength must be specified for unit %s.'%(unit))
+
+        # Get scale factor
+        try:
+            scalefactor = self._getFloat(self.ui.lineEdit_normalizeMonitor)
+        except EmptyError:
+            scalefactor = None
+        except ValueError as valueerror:
+            raise ValueError("Unable to get normalization factor due to %s."%(str(valueerror)))
+
+        # Rebin
+        try:
+            # rebinned = self._myControl.rebin(expno, scanno, unit, wavelength, xmin, binsize, xmax)
+            excludeddetlist = self._uiGetExcludedDetectors()
+            self._myControl.reduceSpicePDData(expno, scanno, \
+                    unit, xmin, xmax, binsize, wavelength, excludeddetlist, scalefactor)
+
+            # Record binning
+            self._tabBinParamDict[itab] = [xmin, binsize, xmax]
+        except NotImplementedError as e:
+            self._logError(str(e))
+            return (False, expno, scanno)
+
+        return (True, expno, scanno)
+
+
+    def _uiReducePlotNoramlized(self, unit):
+        """ Support Reduce2Theta, ReduceDspacing and ReduceQ
+        """
+        itab = 2
+        canvas = self.ui.graphicsView_reducedData
+        expno, scanno = self._uiGetExpScanNumber()
+
+        change = self._uiIsBinParamsChange(itab, self._tabBinParamDict[itab])
+        # check whether line record
+        if unit == self._currUnit and \
+                self._tabLineDict[itab].count((expno, scanno)) > 0 and change is False:
+            # there is no need to plot again as line exists
+            return
+
+        # reduce
+        r = self._uiReduceData(2, unit)
+        good = r[0]
+        expno = r[1]
+        scanno = r[2]
+
+        # failed to reduce
+        if good is False:
+            self._logError("Failed to reduce Exp %d Scan %d" % (expno, scanno))
+            return
+
+        # clear canvas???
+        if unit != self._currUnit:
+            clearcanvas = True
+        elif self.ui.checkBox_clearPrevious.isChecked() is False:
+            # NOTE: naming of the widget is VERY confusing.  Should be changed to keepPrevious
+            clearcanvas = True
+        else:
+            clearcanvas = False
+
+        # reset record dictionary if unit is different from present
+        if clearcanvas is True:
+            self._tabLineDict[itab] = []
+
+        self._currUnit = unit
+        self._tabLineDict[itab].append((expno, scanno))
+
+        xlabel = self._getXLabelFromUnit(unit)
+        label = "Exp %s Scan %s"%(str(expno), str(scanno))
+        self._plotReducedData(expno, scanno, canvas, xlabel, label=label, clearcanvas=clearcanvas)
+
+        return
+
+
+
+    def _logDebug(self, dbinfo):
+        """ Log debug information
+        """
+        print dbinfo
+
+
+    def _logError(self, errinfo):
+        """ Log error information
+        """
+        print "Log(Error): %s" % (errinfo)
+
+
+    def _logNotice(self, errinfo):
+        """ Log error information
+        """
+        print "Log(Notice): %s" % (errinfo)
+
+
+    def _logWarning(self, errinfo):
+        """ Log error information
+        """
+        print "Log(Warning): %s" % (errinfo)
+
+        return
+
+
+    def _getFloat(self, lineedit):
+        """ Get integer from line edit
+        Exception: ValueError if empty or no input
+        """
+        valuestr = str(lineedit.text()).strip()
+        if len(valuestr) == 0:
+            raise EmptyError("Input is empty. It cannot be converted to float.")
+
+        try:
+            value = float(valuestr)
+        except ValueError as e:
+            raise e
+
+        return value
+
+
+    def _getInteger(self, lineedit):
+        """ Get integer from line edit
+        """
+        valuestr = str(lineedit.text()).strip()
+        if len(valuestr) == 0:
+            raise EmptyError("Input is empty. It cannot be converted to integer.")
+
+        try:
+            value = int(valuestr)
+        except ValueError as e:
+            raise e
+
+        return value
+
+
+    def _getIntArray(self, intliststring):
+        """ Validate whether the string can be divided into integer strings.
+        Allowed: a, b, c-d, e, f
+
+        Return :: 2-tuple (status, list/error message)
+        """
+        intliststring = str(intliststring)
+        if intliststring == "":
+            return (True, [])
+
+        # Split by ","
+        termlevel0s = intliststring.split(",")
+        intlist = []
+
+        # For each term
+        errmsg = ""
+        returnstatus = True
+
+        for level0term in termlevel0s:
+            level0term = level0term.strip()
+
+            # split upon dash -
+            numdashes = level0term.count("-")
+            if numdashes == 0:
+                # one integer
+                valuestr = level0term
+                try:
+                    intvalue = int(valuestr)
+                    if str(intvalue) != valuestr:
+                        returnstatus = False
+                        errmsg =  "Contains non-integer string %s." % (valuestr)
+                except ValueError:
+                    returnstatus = False
+                    errmsg = "String %s is not an integer." % (valuestr)
+                else:
+                    intlist.append(intvalue)
+
+            elif numdashes == 1:
+                # Integer range
+                twoterms = level0term.split("-")
+                templist = []
+                for i in xrange(2):
+                    valuestr = twoterms[i]
+                    try:
+                        intvalue = int(valuestr)
+                        if str(intvalue) != valuestr:
+                            returnstatus = False
+                            errmsg = "Contains non-integer string %s." % (valuestr)
+                    except ValueError:
+                        returnstatus = False
+                        errmsg = "String %s is not an integer." % (valuestr)
+                    else:
+                        templist.append(intvalue)
+
+                    # break loop
+                    if returnstatus is False:
+                        break
+                # ENDFOR
+                intlist.extend(range(templist[0], templist[1]+1))
+
+            else:
+                # Undefined siutation
+                returnstatus = False
+                errmsg = "Term %s contains more than 1 dash." % (level0terms)
+            # ENDIFELSE
+
+            # break loop if something is wrong
+            if returnstatus is False:
+                break
+        # ENDFOR
+
+        # Return with false
+        if returnstatus is False:
+            return (False, errmsg)
+
+        return (True, intlist)
+
+
+    def _getXLabelFromUnit(self, unit):
+        """ Get X-label from unit
+        """
+        if unit == '2theta':
+            xlabel = r'$2\theta$ (Degrees)'
+        elif unit == 'dSpacing':
+            xlabel = r"d $(\AA)$"
+        elif unit == 'Momentum Transfer (Q)':
+            xlabel = r"Q $(\AA^{-1})$"
+        else:
+            xlabel = 'Wacky Unknown'
+
+        return xlabel
diff --git a/Code/Mantid/scripts/HFIRPowderReduction/HfirUtility.py b/Code/Mantid/scripts/HFIRPowderReduction/HfirUtility.py
new file mode 100644
index 0000000000000000000000000000000000000000..58e2bfc7ed16537114b2c57b54674882a0c8d264
--- /dev/null
+++ b/Code/Mantid/scripts/HFIRPowderReduction/HfirUtility.py
@@ -0,0 +1,141 @@
+#pylint: disable=invalid-name
+################################################################################
+#
+# Utility methods for HFIR powder reduction
+#
+################################################################################
+
+
+def makeHB2ADetEfficiencyFileName(expno, m1, colltrans):
+    """ Fabricate the detector's efficiency file name for HB2A
+    Example: HB2A_exp0400__Ge_113_IN_vcorr.txt
+
+   * Ge 113: lambda = 2.41 A, m1 = 9.45
+   * Ge 115: lambda = 1.54 A, m1 = 0
+   * Ge 117  lambda = 1.12 A, No used
+
+    Arguments:
+     - expno :: experiment number
+     - m1 :: Ge setup for neutron wavelength (m1)
+     - colltrans :: for In/Out
+
+    Return :: 3-tuple (filename, filename with URL, wavelength)
+    """
+    # Determine wavelength setup
+    wavelengthsetup = None
+    m1 = float(m1)
+    if abs(m1 - 9.45) < 0.1:
+        # m1 = 9.45
+        wavelength = 2.41
+        wavelengthsetup = 'Ge_113'
+    elif abs(m1) < 0.1:
+        # m1 = 0.
+        wavelength = 1.54
+        wavelengthsetup = 'Ge_115'
+    else:
+        # not defined
+        raise NotImplementedError("'m1' value %f is not defined for wavelength setup." % (m1))
+
+    # Determine In/Out, i.e., collimator trans
+    if colltrans is not None:
+        # colltrans is in sample log
+        colltrans = int(colltrans)
+        if abs(colltrans) == 80:
+            collimator = 'OUT'
+        elif colltrans == 0:
+            collimator = 'IN'
+        else:
+            raise NotImplementedError("'colltrans' equal to %d is not defined for IN/OUT." % (colltrans))
+
+        # Make the detector efficiency file name
+        expno = int(expno)
+        defefffilename = 'HB2A_exp%04d__%s_%s_vcorr.txt' % (expno, wavelengthsetup, collimator)
+        url = 'http://neutron.ornl.gov/user_data/hb2a/exp%d/Datafiles/%s' % (expno, defefffilename)
+    else:
+        # old style, no colltrans
+        defefffilename = None
+        url = None
+    # ENDIFELSE
+
+    return (defefffilename, url, wavelength)
+
+
+def makeExcludedDetectorFileName(expno):
+    """ Make the excluded detectors' file name
+
+    Return :: 2-tuple (file name, URL)
+    """
+    expno = int(expno)
+    excludeddetfilename = 'HB2A_exp%04d__exclude_detectors.txt' % (expno)
+    url = 'http://neutron.ornl.gov/user_data/hb2a/exp%d/Datafiles/%s' % (expno, excludeddetfilename)
+
+    return (excludeddetfilename, url)
+
+
+def makeDetGapFileName(expno):
+    """ Make the detectors' gap file name
+
+    Return :: 2-tuple (file name, URL)
+    """
+    expno = int(expno)
+    detgapfilename = 'HB2A_exp04d__gaps.txt' % (expno)
+    url = 'http://neutron.ornl.gov/user_data/hb2a/exp%d/Datafiles/%s' % (expno, detgapfilename)
+
+    return (detgapfilename, url)
+
+
+def parseDetEffCorrFile(vancorrfname):
+    """ Parse HB2A vanadium correction (detector efficiency correction) file
+    Return :: dictionary : key = det id, value = factor
+    """
+    try:
+        cfile = open(vancorrfname, 'r')
+        lines = cfile.readlines()
+        cfile.close()
+    except IOError:
+        return (False, 'Unable to read vanadium correction file %s.'%(vancorrfname))
+
+    corrdict = {}
+    detid = 1
+    for line in lines:
+        line = line.strip()
+        if len(line) == 0 or line[0] == '#':
+            continue
+
+        terms = line.split()
+        factor = float(terms[0])
+        corrdict[detid] = factor
+
+        detid += 1
+    # ENDFOR
+
+    return (corrdict, '')
+
+
+def parseDetExclusionFile(detexludefilename):
+    """ Parse excluded detectors file
+    """
+    try:
+        defile = open(detexludefilename)
+        lines = defile.readlines()
+        defile.close()
+    except IOError:
+        return (None, 'Unable to read excluded detector file %s.'%(detexludefilename))
+
+    detexcludelist = []
+    for line in lines:
+        line = line.strip()
+        if len(line) == 0 or line[0] == '#':
+            continue
+
+        terms = line.split()
+        for term in terms:
+            try:
+                detid = int(term)
+                detexcludelist.append(detid)
+            except ValueError:
+                break
+        # ENDFOR
+    # ENDFOR
+
+    return (detexcludelist, '')
diff --git a/Code/Mantid/scripts/HFIRPowderReduction/MplFigureCanvas.py b/Code/Mantid/scripts/HFIRPowderReduction/MplFigureCanvas.py
new file mode 100644
index 0000000000000000000000000000000000000000..cec7d4282d3e0150c94d6d4033770370b0193712
--- /dev/null
+++ b/Code/Mantid/scripts/HFIRPowderReduction/MplFigureCanvas.py
@@ -0,0 +1,585 @@
+#pylint: disable=invalid-name,too-many-public-methods,too-many-arguments,non-parent-init-called
+import os
+
+from PyQt4 import QtGui
+
+from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
+from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
+from matplotlib.figure import Figure
+
+MplLineStyles = ['-' , '--' , '-.' , ':' , 'None' , ' ' , '']
+MplLineMarkers = [
+        ". (point         )",
+        "* (star          )",
+        "x (x             )",
+        "o (circle        )",
+        "s (square        )",
+        "D (diamond       )",
+        ", (pixel         )",
+        "v (triangle_down )",
+        "^ (triangle_up   )",
+        "< (triangle_left )",
+        "> (triangle_right)",
+        "1 (tri_down      )",
+        "2 (tri_up        )",
+        "3 (tri_left      )",
+        "4 (tri_right     )",
+        "8 (octagon       )",
+        "p (pentagon      )",
+        "h (hexagon1      )",
+        "H (hexagon2      )",
+        "+ (plus          )",
+        "d (thin_diamond  )",
+        "| (vline         )",
+        "_ (hline         )",
+        "None (nothing    )"]
+
+MplBasicColors = [
+        "black",
+        "red",
+        "blue",
+        "green",
+        "cyan",
+        "magenta",
+        "yellow",
+        "white"]
+
+
+class Qt4MplPlotView(QtGui.QWidget):
+    """ A combined graphics view including matplotlib canvas and
+    a navigation tool bar
+    """
+    def __init__(self, parent):
+        """ Initialization
+        """
+        # instantianize parent
+        QtGui.QWidget.__init__(self, parent)
+
+        # set up canvas
+        self.canvas = Qt4MplCanvas(self)
+        self.toolbar = MyNavigationToolbar(self.canvas, self.canvas)
+
+        # set up layout
+        self.vbox = QtGui.QVBoxLayout(self)
+        self.vbox.addWidget(self.canvas)
+        self.vbox.addWidget(self.toolbar)
+
+        # auto line's maker+color list
+        self._myLineMarkerColorList = []
+        self._myLineMarkerColorIndex = 0
+        self.setAutoLineMarkerColorCombo()
+
+        return
+
+    def addPlot(self, x, y, color=None, label="", xlabel=None, ylabel=None, marker=None, linestyle=None, linewidth=1):
+        """ Add a new plot
+        """
+        self.canvas.addPlot(x, y, color, label, xlabel, ylabel, marker, linestyle, linewidth)
+
+        return
+
+
+    def addPlot2D(self, array2d, xmin, xmax, ymin, ymax, holdprev=True, yticklabels=None):
+        """ Plot a 2D image
+        Arguments
+         - array2d :: numpy 2D array
+        """
+        self.canvas.addPlot2D(array2d, xmin, xmax, ymin, ymax, holdprev, yticklabels)
+
+        return
+
+
+    def addImage(self, imagefilename):
+        """ Add an image by file
+        """
+        # check
+        if os.path.exists(imagefilename) is False:
+            raise NotImplementedError("Image file %s does not exist." % (imagefilename))
+
+        self.canvas.addImage(imagefilename)
+
+        return
+
+
+    def clearAllLines(self):
+        """
+        """
+        self.canvas.clearAllLines()
+
+    def clearCanvas(self):
+        """ Clear canvas
+        """
+        return self.canvas.clearCanvas()
+
+    def draw(self):
+        """ Draw to commit the change
+        """
+        return self.canvas.draw()
+
+    def getPlot(self):
+        """
+        """
+        return self.canvas.getPlot()
+
+    def getLastPlotIndexKey(self):
+        """ Get ...
+        """
+        return self.canvas.getLastPlotIndexKey()
+
+    def getXLimit(self):
+        """ Get limit of Y-axis
+        """
+        return self.canvas.getXLimit()
+
+    def getYLimit(self):
+        """ Get limit of Y-axis
+        """
+        return self.canvas.getYLimit()
+
+    def removePlot(self, ikey):
+        """
+        """
+        return self.canvas.removePlot(ikey)
+
+    def setXYLimits(self, xmin=None, xmax=None, ymin=None, ymax=None):
+        """
+        """
+        return self.canvas.setXYLimit(xmin, xmax, ymin, ymax)
+
+
+    def updateLine(self, ikey, vecx, vecy, linestyle=None, linecolor=None, marker=None, markercolor=None):
+        """
+        """
+        return self.canvas.updateLine(ikey, vecx, vecy, linestyle, linecolor, marker, markercolor)
+
+
+    def getLineStyleList(self):
+        """
+        """
+        return MplLineStyles
+
+
+    def getLineMarkerList(self):
+        """
+        """
+        return MplLineMarkers
+
+    def getLineBasicColorList(self):
+        """
+        """
+        return MplBasicColors
+
+    def getDefaultColorMarkerComboList(self):
+        """ Get a list of line/marker color and marker style combination
+        as default to add more and more line to plot
+        """
+        return self.canvas.getDefaultColorMarkerComboList()
+
+    def getNextLineMarkerColorCombo(self):
+        """ As auto line's marker and color combo list is used,
+        get the NEXT marker/color combo
+        """
+        # get from list
+        marker, color = self._myLineMarkerColorList[self._myLineMarkerColorIndex]
+        # process marker if it has information
+        if marker.count(' (') > 0:
+            marker = marker.split(' (')[0]
+        print "[DB] Print line %d: marker = %s, color = %s" % (self._myLineMarkerColorIndex, marker, color)
+
+        # update the index
+        self._myLineMarkerColorIndex += 1
+        if self._myLineMarkerColorIndex == len(self._myLineMarkerColorList):
+            self._myLineMarkerColorIndex = 0
+
+        return (marker, color)
+
+    def setXYLimit(self, xmin, xmax, ymin, ymax):
+        """ Set X-Y limit automatically
+        """
+        self.canvas.axes.set_xlim([xmin, xmax])
+        self.canvas.axes.set_ylim([ymin, ymax])
+
+        self.canvas.draw()
+
+        return
+
+    def setAutoLineMarkerColorCombo(self):
+        """
+        """
+        self._myLineMarkerColorList = []
+        for marker in MplLineMarkers:
+            for color in MplBasicColors:
+                self._myLineMarkerColorList.append( (marker, color) )
+
+        return
+
+    def setLineMarkerColorIndex(self, newindex):
+        """
+        """
+        self._myLineMarkerColorIndex = newindex
+
+        return
+
+class Qt4MplCanvas(FigureCanvas):
+    """  A customized Qt widget for matplotlib figure.
+    It can be used to replace GraphicsView of QtGui
+    """
+    def __init__(self, parent):
+        """  Initialization
+        """
+        # Instantialize matplotlib Figure
+        self.fig = Figure()
+        self.fig.patch.set_facecolor('white')
+        self.axes = self.fig.add_subplot(111) # return: matplotlib.axes.AxesSubplot
+
+        # Initialize parent class and set parent
+        FigureCanvas.__init__(self, self.fig)
+        self.setParent(parent)
+
+        # Set size policy to be able to expanding and resizable with frame
+        FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding,\
+                QtGui.QSizePolicy.Expanding)
+
+        FigureCanvas.updateGeometry(self)
+
+        # Variables to manage all lines/subplot
+        self._lineDict = {}
+        self._lineIndex = 0
+
+        self.colorbar = None
+
+        return
+
+    def addPlot(self, x, y, color=None, label="", xlabel=None, ylabel=None, marker=None, linestyle=None, linewidth=1):
+        """ Plot a set of data
+        Argument:
+        - x: numpy array X
+        - y: numpy array Y
+        """
+        # Hold previous data
+        self.axes.hold(True)
+
+        # process inputs and defaults
+        self.x = x
+        self.y = y
+
+        if color is None:
+            color = (0,1,0,1)
+        if marker is None:
+            marker = 'o'
+        if linestyle is None:
+            linestyle = '-'
+
+        # color must be RGBA (4-tuple)
+        r = self.axes.plot(x, y, color=color, marker=marker, linestyle=linestyle,
+                label=label, linewidth=linewidth) # return: list of matplotlib.lines.Line2D object
+
+        self.axes.set_aspect('auto')
+
+        # set x-axis and y-axis label
+        if xlabel is not None:
+            self.axes.set_xlabel(xlabel, fontsize=20)
+        if ylabel is not None:
+            self.axes.set_ylabel(ylabel, fontsize=20)
+
+        # set/update legend
+        self._setupLegend()
+
+        # Register
+        if len(r) == 1:
+            self._lineDict[self._lineIndex] = r[0]
+        else:
+            print "Impoooooooooooooooosible!"
+        self._lineIndex += 1
+
+        # Flush/commit
+        self.draw()
+
+        return
+
+
+    def addPlot2D(self, array2d, xmin, xmax, ymin, ymax, holdprev, yticklabels=None):
+        """ Add a 2D plot
+
+        Arguments:
+         - yticklabels :: list of string for y ticks
+        """
+        # Release the current image
+        self.axes.hold(holdprev)
+
+        # Do plot
+        # y ticks will be shown on line 1, 4, 23, 24 and 30
+        # yticks = [1, 4, 23, 24, 30]
+        # self.axes.set_yticks(yticks)
+
+        # show image
+        imgplot = self.axes.imshow(array2d, extent=[xmin,xmax,ymin,ymax], interpolation='none')
+        # set y ticks as an option:
+        if yticklabels is not None:
+            # it will always label the first N ticks even image is zoomed in
+            print "--------> [FixMe]: Set up the Y-axis ticks is erroreous"
+            #self.axes.set_yticklabels(yticklabels)
+
+        # explicitly set aspect ratio of the image
+        self.axes.set_aspect('auto')
+
+        # Set color bar.  plt.colorbar() does not work!
+        if self.colorbar is None:
+            # set color map type
+            imgplot.set_cmap('spectral')
+            self.colorbar = self.fig.colorbar(imgplot)
+        else:
+            self.colorbar.update_bruteforce(imgplot)
+
+        # Flush...
+        self._flush()
+
+        return
+
+    def addImage(self, imagefilename):
+        """ Add an image by file
+        """
+        #import matplotlib.image as mpimg
+
+        # set aspect to auto mode
+        self.axes.set_aspect('auto')
+
+        img = mpimg.imread(str(imagefilename))
+        # lum_img = img[:,:,0]
+        # FUTURE : refactor for image size, interpolation and origin
+        imgplot = self.axes.imshow(img, extent=[0, 1000, 800, 0], interpolation='none', origin='lower')
+
+        # Set color bar.  plt.colorbar() does not work!
+        if self.colorbar is None:
+            # set color map type
+            imgplot.set_cmap('spectral')
+            self.colorbar = self.fig.colorbar(imgplot)
+        else:
+            self.colorbar.update_bruteforce(imgplot)
+
+        self._flush()
+
+        return
+
+
+    def clearAllLines(self):
+        """ Remove all lines from the canvas
+        """
+        for ikey in self._lineDict.keys():
+            plot = self._lineDict[ikey]
+            if plot is not None:
+                self.axes.lines.remove(plot)
+                self._lineDict[ikey] = None
+            # ENDIF(plot)
+        # ENDFOR
+
+        self.draw()
+
+        return
+
+
+    def clearCanvas(self):
+        """ Clear data from canvas
+        """
+        # clear the image for next operation
+        self.axes.hold(False)
+
+        # clear image
+        self.axes.cla()
+
+        # flush/commit
+        self._flush()
+
+        return
+
+
+    def getLastPlotIndexKey(self):
+        """ Get the index/key of the last added line
+        """
+        return self._lineIndex-1
+
+
+    def getPlot(self):
+        """ reture figure's axes to expose the matplotlib figure to PyQt client
+        """
+        return self.axes
+
+    def getXLimit(self):
+        """ Get limit of Y-axis
+        """
+        return self.axes.get_xlim()
+
+    def getYLimit(self):
+        """ Get limit of Y-axis
+        """
+        return self.axes.get_ylim()
+
+    def setXYLimit(self, xmin, xmax, ymin, ymax):
+        """
+        """
+        # for X
+        xlims = self.axes.get_xlim()
+        xlims = list(xlims)
+        if xmin is not None:
+            xlims[0] = xmin
+        if xmax is not None:
+            xlims[1] = xmax
+        self.axes.set_xlim(xlims)
+
+        # for Y
+        ylims = self.axes.get_ylim()
+        ylims = list(ylims)
+        if ymin is not None:
+            ylims[0] = ymin
+        if ymax is not None:
+            ylims[1] = ymax
+        self.axes.set_ylim(ylims)
+
+        # try draw
+        self.draw()
+
+        return
+
+    def removePlot(self, ikey):
+        """ Remove the line with its index as key
+        """
+        # self._lineDict[ikey].remove()
+        lines = self.axes.lines
+        print str(type(lines)), lines
+        print "ikey = ", ikey, self._lineDict[ikey]
+        self.axes.lines.remove(self._lineDict[ikey])
+        #self.axes.remove(self._lineDict[ikey])
+        print self._lineDict[ikey]
+        self._lineDict[ikey] = None
+
+        return
+
+    def updateLine(self, ikey, vecx, vecy, linestyle=None, linecolor=None, marker=None, markercolor=None):
+        """
+        """
+        line = self._lineDict[ikey]
+
+        if vecx is not None and vecy is not None:
+            line.set_xdata(vecx)
+            line.set_ydata(vecy)
+
+        if linecolor is not None:
+            line.set_color(linecolor)
+
+        if linestyle is not None:
+            line.set_linestyle(linestyle)
+
+        if marker is not None:
+            line.set_marker(marker)
+
+        if markercolor is not None:
+            line.set_markerfacecolor(markercolor)
+
+        oldlabel = line.get_label()
+        line.set_label(oldlabel)
+
+        self.axes.legend()
+
+        # commit
+        self.draw()
+
+        return
+
+    def getLineStyleList(self):
+        """
+        """
+        return MplLineStyles
+
+
+    def getLineMarkerList(self):
+        """
+        """
+        return MplLineMarkers
+
+    def getLineBasicColorList(self):
+        """
+        """
+        return MplBasicColors
+
+    def getDefaultColorMarkerComboList(self):
+        """ Get a list of line/marker color and marker style combination
+        as default to add more and more line to plot
+        """
+        combolist = []
+        nummarkers = len(MplLineMarkers)
+        numcolors = len(MplBasicColors)
+
+        for i in xrange(nummarkers):
+            marker = MplLineMarkers[i]
+            for j in xrange(numcolors):
+                color = MplBasicColors[j]
+                combolist.append( (marker, color) )
+            # ENDFOR (j)
+        # ENDFOR(i)
+
+        return combolist
+
+
+    def _flush(self):
+        """ A dirty hack to flush the image
+        """
+        w, h = self.get_width_height()
+        self.resize(w+1,h)
+        self.resize(w,h)
+
+        return
+
+
+    def _setupLegend(self, location='best'):
+        """ Set up legend
+        self.axes.legend()
+        Handler is a Line2D object. Lable maps to the line object
+        """
+        loclist = [
+            "best",
+            "upper right",
+            "upper left",
+            "lower left",
+            "lower right",
+            "right",
+            "center left",
+            "center right",
+            "lower center",
+            "upper center",
+            "center"]
+
+        # Check legend location valid or not
+        if location not in loclist:
+            location = 'best'
+
+        handles, labels = self.axes.get_legend_handles_labels()
+        self.axes.legend(handles, labels, loc=location)
+        # print handles
+        # print labels
+        #self.axes.legend(self._myLegendHandlers, self._myLegentLabels)
+
+        return
+
+
+
+class MyNavigationToolbar(NavigationToolbar):
+    """ A customized navigation tool bar attached to canvas
+    """
+    def __init__(self, parent, canvas):
+        """ Initialization
+        FUTURE: direction='h'
+        """
+        self.canvas = canvas
+        QtGui.QWidget.__init__(self, parent)
+
+        #if direction=='h' :
+        #    self.layout = QtGui.QHBoxLayout(self)
+        #else :
+        #    self.layout = QtGui.QVBoxLayout(self)
+
+        #self.layout.setMargin(2)
+        #self.layout.setSpacing(0)
+
+        NavigationToolbar.__init__( self, canvas, canvas )
+
+        return
diff --git a/Code/Mantid/scripts/HFIRPowderReduction/README.md b/Code/Mantid/scripts/HFIRPowderReduction/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..9799a0393d41e987afe4ce74c13f176ce6ee3865
--- /dev/null
+++ b/Code/Mantid/scripts/HFIRPowderReduction/README.md
@@ -0,0 +1,148 @@
+Tasks
+-----
+  
+  6. Find out why the vanadium runs (379-10/11) look funny, i.e., oscilating curves;
+  7. Talk with Clarina how to deal with vanadium spectrum with peaks striped; 
+  8. Tab *Normalized*: **Normalization Monitor** should have a default value as the average of monitor counts
+  9. Check whether a scan has been loaded as **Load** is pushed; 
+  10. Enable *SaveGSS*() work with reactor-source powder diffractometers;
+
+
+Finished Tasks
+--------------
+  
+  1. Make tab *Raw Detector* work;
+  2. Make tab *Individual Detector* work;
+  3. Implement tab *vanadium*;
+  4. (75%) Each tab with *Previous* and *Next* buttons should have a data structure to record whether a certain plot is already on canvas
+  5. Tab *Normalized*: **Normalization Monitor** is not parsed;
+  6. Tab *Normalized*: apply reduction record to binning push buttons and avoid plotting one data twice on same plot with *Prev Scan* and *Next Scan*;
+  7. Tab *Normalized*: **Save** does not work well with option *gsas and fullprof*;
+  8. Tab *vanadium*: implement **Smooth Data**;
+  9. Tab *vanadium*: implement **Save**;
+  10. Tab *Multiple Scans*: implement **Save Merged**
+  11. Tab *Multiple Scans*: implement **Save All**
+
+
+Use cases for tabs
+------------------
+
+  1. **Raw Detectors**: Visualize the reading of detectors directly coming out of the raw data
+    * Plot N lines for N Pts.;
+    * Highlight (make it thicker) the Pt that is interested;
+    * New from Mantid:  *ReadRawSpiceSignal(Pts)*;
+  2. **Individual Detector**: Visual the readings of one detector across an experiment
+    * Plot the counts of any individual detector;
+    * Able to change the X-axis from 2theta to arbitrary sample environment log;
+    * New from Mantid: *ReadRawSpiceSignal(DetectorID, XLabel)*;
+  3. **Normalized**: Reduce one scan each time
+    * Plot the reduced data
+    * Automatically locate detector efficiency file
+    * New from Mantid: *ConvertCWPDMDToSpectra(ExcludedDetectors=[])*
+    * New from Mantid: *ConvertSpiceDataToRealSpace(DetectorEfficiencyTable)*
+  4. **Multiple Scans**: Reduce a set of scans
+    * Reduce a set of scans and plot in 2D/water-fall mode;
+    * Able to merge all the scans;
+    * New from Mantid: *ConvertCWPDMDToSpectra(ExcludedDetectors=[])*
+  5. **Vanadium**: strip vanadium peaks
+    * Strip vanadium peak with unit 'Degrees' because of the binning (range and step size) must be respected;
+    * Peaks' position should be calculated and indicated auotmatically;
+    * *Mantid::StripPeaks()* will be called instread of *StripVadadiumPeaks()* because
+      the later one only works in d-spacing;
+  6. **Advanced Setup**
+    * URL for raw data files; 
+
+
+Suggested workflow for *Normalization*
+======================================
+
+Here is a typical use case for reduce data via tab *Noramlization*
+
+ 1. User specify *Exp No* and *Scan No*;
+ 2. HFIR-PDR-GUI loads SPICE data according to experiment number and scan number;
+ 3. HFIR-PDR-GUI checks whether vanadium correction file, i.e., detector efficiency file exists on server;
+ 4. HFIR-PDR-GUI checks whether excluded detectors file exists on server;
+ 5. HFIR-PDR-GUI checks log **m1** for wavelength and set to *Wavelength* ;
+ 6. User may specify detector efficient file;
+ 7. User specifies *Bin Size*; (Or auto bin size determination???)
+ 8. User pushes button *Load Data*;
+ 9. HFIR-PDF-GUI reduce data in unit of *2theta* by taking accounting of 
+   * Detector efficiency;
+   * Excluded detectors; 
+ 10. HFIR-PDR-GUI plots the reduced data;
+ 11. User may rebin by different binning parameters or unit;
+ 12. User may save the result;
+
+
+Suggested workflow for *Multiple Scans*
+=======================================
+
+It might be confusing to use the functionalities in tab *Multiple Scans*. 
+Here is the suggested workflow to reduce multiple scans and possibly merge them.
+
+ 1. Set up *Exp No* and range of scan numbers;
+ 2. Push button *Load All* to load and reduce all runs specified in previous step to single-spectrum diffraction pattern;
+ 3. Waterfall plot all reduced scans in default;
+ 4. Optinally plot all data in 2D fill plot;
+ 5. User can delete some scans from the reduced scans via GUI or input text edit;
+ 6. Push button *Merge* to merge the scans;
+ 7. Push button *Save All* to save all individual scans to files;
+ 8. Push button *Save Merged* to save the merged scans to one file; 
+
+
+Features (Implemented)
+----------------------
+
+ * Automatic wavelength mapping (in progress);
+
+
+HB2A Data Reduction
+-------------------
+
+Raw experimental data are to be corrected by (1) detector efficiency, (2) vanadium spectrum and etc. 
+Experiments are done with neutrons with various wavelengthes.  
+There information can be retrieved from HB2A's data repository accessible from internet. 
+
+Experiment setup and sample log
+===============================
+
+ 1. **Wavelength**: There are three settings for neutron wavelength, referenced by sample log *m1*. 
+   * Ge 113: :math:`\lambda = 2.41 \AA`, m1 = 9.45  (The **error** can be 0.05, such that in Exp 231 scan0001, m1=9.5)
+   * Ge 115: :math:`\lambda = 1.54 \AA`, m1 = 0
+   * Ge 117  :math:`\lambda = 1.12 \AA`, No used
+
+ 2. **Collimator translation**: There are two status for collimator, which is specified by sample log *colltrans*
+   * *IN*:  colltrans = 0
+   * *OUT*: colltrans = +/-80
+
+
+Raw data correction files
+=========================
+
+ 1. **Detector efficiency**: 
+   * File name: *HB2A_exp0IJK__GE_abc_XY_vcorr.txt* where
+    - IJK is the experiment number
+    - abc is the GE set up.  It can be 113, 115 or 117
+    - XY is either IN or OUT. 
+    - Exmaple: *HB2A_exp0400__Ge_113_IN_vcorr.txt*
+   * Web address: *http://neutron.ornl.gov/user_data/hb2a/exp400/Datafiles/HB2A_exp0IJK__Ge_abc_IN_vcorr.txt*
+    - IJK is the experiment number
+    - abc is the GE set up.  It can be 113, 115 or 117
+    - XY is either IN or OUT. 
+    - Exmaple: *http://neutron.ornl.gov/user_data/hb2a/exp400/Datafiles/HB2A_exp0400__Ge_113_IN_vcorr.txt*
+
+ 2. **Excluded detectors**:  Some detectors might be exluded from the experiment for some reason.  It is recorded in some excluded detectors' file.
+   * File name: *HB2A_exp0IJK__exclude_detectors.txt*
+    - IJK is the epxeriment number
+    - Exmaple: *HB2A_exp0400__exclude_detectors.txt*
+   * Web address: *http://neutron.ornl.gov/user_data/hb2a/expIJK/Datafiles/HB2A_exp0IJK__exclude_detectors.txt*
+    - IJK is the experiment number
+    - Example: *http://neutron.ornl.gov/user_data/hb2a/exp400/Datafiles/HB2A_exp0400__exclude_detectors.txt*
+
+ 3. Detector gaps: The 2-theta gap (in unit degrees) can be changed among cycles. 
+   * Location example: *http://neutron.ornl.gov/user_data/hb2a/exp400/Datafiles/HB2A_exp0400__gaps.txt*
+
+
+
+
+
diff --git a/Code/Mantid/scripts/HFIRPowderReduction/Ui_MainWindow.py b/Code/Mantid/scripts/HFIRPowderReduction/Ui_MainWindow.py
new file mode 100644
index 0000000000000000000000000000000000000000..e41d87f1cfafa3457809774931d842e103811360
--- /dev/null
+++ b/Code/Mantid/scripts/HFIRPowderReduction/Ui_MainWindow.py
@@ -0,0 +1,1099 @@
+#pylint: disable=invalid-name,relative-import,too-many-lines,too-many-instance-attributes,too-many-statements,line-too-long,too-many-locals,attribute-defined-outside-init
+# -*- coding: utf-8 -*-
+
+# Form implementation generated from reading ui file 'Ui_MainWindow.ui'
+#
+# Created: Mon May  4 11:12:07 2015
+#      by: PyQt4 UI code generator 4.11.2
+#
+# WARNING! All changes made in this file will be lost!
+
+from PyQt4 import QtCore, QtGui
+
+try:
+    _fromUtf8 = QtCore.QString.fromUtf8
+except AttributeError:
+    def _fromUtf8(s):
+        return s
+
+try:
+    _encoding = QtGui.QApplication.UnicodeUTF8
+    def _translate(context, text, disambig):
+        return QtGui.QApplication.translate(context, text, disambig, _encoding)
+except AttributeError:
+    def _translate(context, text, disambig):
+        return QtGui.QApplication.translate(context, text, disambig)
+
+from MplFigureCanvas import *
+class Ui_MainWindow(object):
+    def setupUi(self, MainWindow):
+        MainWindow.setObjectName(_fromUtf8("MainWindow"))
+        MainWindow.resize(1412, 1216)
+        self.centralwidget = QtGui.QWidget(MainWindow)
+        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
+        self.gridLayout = QtGui.QGridLayout(self.centralwidget)
+        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
+        self.verticalLayout = QtGui.QVBoxLayout()
+        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
+        self.horizontalLayout = QtGui.QHBoxLayout()
+        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
+        self.label_expNo = QtGui.QLabel(self.centralwidget)
+        self.label_expNo.setObjectName(_fromUtf8("label_expNo"))
+        self.horizontalLayout.addWidget(self.label_expNo)
+        self.lineEdit_expNo = QtGui.QLineEdit(self.centralwidget)
+        self.lineEdit_expNo.setObjectName(_fromUtf8("lineEdit_expNo"))
+        self.horizontalLayout.addWidget(self.lineEdit_expNo)
+        self.label_scanNo = QtGui.QLabel(self.centralwidget)
+        self.label_scanNo.setObjectName(_fromUtf8("label_scanNo"))
+        self.horizontalLayout.addWidget(self.label_scanNo)
+        self.lineEdit_scanNo = QtGui.QLineEdit(self.centralwidget)
+        self.lineEdit_scanNo.setObjectName(_fromUtf8("lineEdit_scanNo"))
+        self.horizontalLayout.addWidget(self.lineEdit_scanNo)
+        self.pushButton_loadData = QtGui.QPushButton(self.centralwidget)
+        self.pushButton_loadData.setObjectName(_fromUtf8("pushButton_loadData"))
+        self.horizontalLayout.addWidget(self.pushButton_loadData)
+        self.label_calibration = QtGui.QLabel(self.centralwidget)
+        self.label_calibration.setText(_fromUtf8(""))
+        self.label_calibration.setObjectName(_fromUtf8("label_calibration"))
+        self.horizontalLayout.addWidget(self.label_calibration)
+        self.label_wavelength = QtGui.QLabel(self.centralwidget)
+        self.label_wavelength.setObjectName(_fromUtf8("label_wavelength"))
+        self.horizontalLayout.addWidget(self.label_wavelength)
+        self.comboBox_wavelength = QtGui.QComboBox(self.centralwidget)
+        self.comboBox_wavelength.setObjectName(_fromUtf8("comboBox_wavelength"))
+        self.comboBox_wavelength.addItem(_fromUtf8(""))
+        self.comboBox_wavelength.addItem(_fromUtf8(""))
+        self.comboBox_wavelength.addItem(_fromUtf8(""))
+        self.comboBox_wavelength.addItem(_fromUtf8(""))
+        self.horizontalLayout.addWidget(self.comboBox_wavelength)
+        self.lineEdit_wavelength = QtGui.QLineEdit(self.centralwidget)
+        self.lineEdit_wavelength.setObjectName(_fromUtf8("lineEdit_wavelength"))
+        self.horizontalLayout.addWidget(self.lineEdit_wavelength)
+        spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
+        self.horizontalLayout.addItem(spacerItem)
+        self.verticalLayout.addLayout(self.horizontalLayout)
+        self.horizontalLayout_25 = QtGui.QHBoxLayout()
+        self.horizontalLayout_25.setObjectName(_fromUtf8("horizontalLayout_25"))
+        self.checkBox_useDetEffCorr = QtGui.QCheckBox(self.centralwidget)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.checkBox_useDetEffCorr.sizePolicy().hasHeightForWidth())
+        self.checkBox_useDetEffCorr.setSizePolicy(sizePolicy)
+        self.checkBox_useDetEffCorr.setMinimumSize(QtCore.QSize(250, 0))
+        self.checkBox_useDetEffCorr.setObjectName(_fromUtf8("checkBox_useDetEffCorr"))
+        self.horizontalLayout_25.addWidget(self.checkBox_useDetEffCorr)
+        spacerItem1 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
+        self.horizontalLayout_25.addItem(spacerItem1)
+        self.label_detEffFileName = QtGui.QLabel(self.centralwidget)
+        self.label_detEffFileName.setObjectName(_fromUtf8("label_detEffFileName"))
+        self.horizontalLayout_25.addWidget(self.label_detEffFileName)
+        self.lineEdit_vcorrFileName = QtGui.QLineEdit(self.centralwidget)
+        self.lineEdit_vcorrFileName.setObjectName(_fromUtf8("lineEdit_vcorrFileName"))
+        self.horizontalLayout_25.addWidget(self.lineEdit_vcorrFileName)
+        self.pushButton_browseVCorrFile = QtGui.QPushButton(self.centralwidget)
+        self.pushButton_browseVCorrFile.setObjectName(_fromUtf8("pushButton_browseVCorrFile"))
+        self.horizontalLayout_25.addWidget(self.pushButton_browseVCorrFile)
+        self.pushButton_viewVCorrection = QtGui.QPushButton(self.centralwidget)
+        self.pushButton_viewVCorrection.setObjectName(_fromUtf8("pushButton_viewVCorrection"))
+        self.horizontalLayout_25.addWidget(self.pushButton_viewVCorrection)
+        self.comboBox_effCorrect = QtGui.QComboBox(self.centralwidget)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.comboBox_effCorrect.sizePolicy().hasHeightForWidth())
+        self.comboBox_effCorrect.setSizePolicy(sizePolicy)
+        self.comboBox_effCorrect.setObjectName(_fromUtf8("comboBox_effCorrect"))
+        self.horizontalLayout_25.addWidget(self.comboBox_effCorrect)
+        spacerItem2 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
+        self.horizontalLayout_25.addItem(spacerItem2)
+        self.verticalLayout.addLayout(self.horizontalLayout_25)
+        self.horizontalLayout_24 = QtGui.QHBoxLayout()
+        self.horizontalLayout_24.setObjectName(_fromUtf8("horizontalLayout_24"))
+        self.checkBox_useDetExcludeFile = QtGui.QCheckBox(self.centralwidget)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.checkBox_useDetExcludeFile.sizePolicy().hasHeightForWidth())
+        self.checkBox_useDetExcludeFile.setSizePolicy(sizePolicy)
+        self.checkBox_useDetExcludeFile.setMinimumSize(QtCore.QSize(250, 0))
+        self.checkBox_useDetExcludeFile.setObjectName(_fromUtf8("checkBox_useDetExcludeFile"))
+        self.horizontalLayout_24.addWidget(self.checkBox_useDetExcludeFile)
+        spacerItem3 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Minimum)
+        self.horizontalLayout_24.addItem(spacerItem3)
+        self.label_excFileName = QtGui.QLabel(self.centralwidget)
+        self.label_excFileName.setObjectName(_fromUtf8("label_excFileName"))
+        self.horizontalLayout_24.addWidget(self.label_excFileName)
+        self.lineEdit_excludedDetFileName = QtGui.QLineEdit(self.centralwidget)
+        self.lineEdit_excludedDetFileName.setObjectName(_fromUtf8("lineEdit_excludedDetFileName"))
+        self.horizontalLayout_24.addWidget(self.lineEdit_excludedDetFileName)
+        self.pushButton_browseExcludedDetFile = QtGui.QPushButton(self.centralwidget)
+        self.pushButton_browseExcludedDetFile.setObjectName(_fromUtf8("pushButton_browseExcludedDetFile"))
+        self.horizontalLayout_24.addWidget(self.pushButton_browseExcludedDetFile)
+        spacerItem4 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Minimum)
+        self.horizontalLayout_24.addItem(spacerItem4)
+        self.label_detExcluded = QtGui.QLabel(self.centralwidget)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.label_detExcluded.sizePolicy().hasHeightForWidth())
+        self.label_detExcluded.setSizePolicy(sizePolicy)
+        self.label_detExcluded.setMinimumSize(QtCore.QSize(155, 0))
+        self.label_detExcluded.setObjectName(_fromUtf8("label_detExcluded"))
+        self.horizontalLayout_24.addWidget(self.label_detExcluded)
+        self.lineEdit_detExcluded = QtGui.QLineEdit(self.centralwidget)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.lineEdit_detExcluded.sizePolicy().hasHeightForWidth())
+        self.lineEdit_detExcluded.setSizePolicy(sizePolicy)
+        self.lineEdit_detExcluded.setMinimumSize(QtCore.QSize(300, 0))
+        self.lineEdit_detExcluded.setObjectName(_fromUtf8("lineEdit_detExcluded"))
+        self.horizontalLayout_24.addWidget(self.lineEdit_detExcluded)
+        spacerItem5 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
+        self.horizontalLayout_24.addItem(spacerItem5)
+        self.verticalLayout.addLayout(self.horizontalLayout_24)
+        self.horizontalLayout_2 = QtGui.QHBoxLayout()
+        self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
+        self.tabWidget = QtGui.QTabWidget(self.centralwidget)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.tabWidget.sizePolicy().hasHeightForWidth())
+        self.tabWidget.setSizePolicy(sizePolicy)
+        self.tabWidget.setObjectName(_fromUtf8("tabWidget"))
+        self.tab_3 = QtGui.QWidget()
+        self.tab_3.setObjectName(_fromUtf8("tab_3"))
+        self.gridLayout_4 = QtGui.QGridLayout(self.tab_3)
+        self.gridLayout_4.setObjectName(_fromUtf8("gridLayout_4"))
+        self.verticalLayout_7 = QtGui.QVBoxLayout()
+        self.verticalLayout_7.setObjectName(_fromUtf8("verticalLayout_7"))
+        self.horizontalLayout_13 = QtGui.QHBoxLayout()
+        self.horizontalLayout_13.setObjectName(_fromUtf8("horizontalLayout_13"))
+        self.comboBox_rawDetMode = QtGui.QComboBox(self.tab_3)
+        self.comboBox_rawDetMode.setObjectName(_fromUtf8("comboBox_rawDetMode"))
+        self.comboBox_rawDetMode.addItem(_fromUtf8(""))
+        self.horizontalLayout_13.addWidget(self.comboBox_rawDetMode)
+        self.lineEdit_ptNo = QtGui.QLineEdit(self.tab_3)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.lineEdit_ptNo.sizePolicy().hasHeightForWidth())
+        self.lineEdit_ptNo.setSizePolicy(sizePolicy)
+        self.lineEdit_ptNo.setObjectName(_fromUtf8("lineEdit_ptNo"))
+        self.horizontalLayout_13.addWidget(self.lineEdit_ptNo)
+        self.label_ptInfo = QtGui.QLabel(self.tab_3)
+        self.label_ptInfo.setObjectName(_fromUtf8("label_ptInfo"))
+        self.horizontalLayout_13.addWidget(self.label_ptInfo)
+        spacerItem6 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Minimum)
+        self.horizontalLayout_13.addItem(spacerItem6)
+        self.verticalLayout_7.addLayout(self.horizontalLayout_13)
+        self.horizontalLayout_14 = QtGui.QHBoxLayout()
+        self.horizontalLayout_14.setObjectName(_fromUtf8("horizontalLayout_14"))
+        self.graphicsView_Raw = Qt4MplPlotView(self.tab_3)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.graphicsView_Raw.sizePolicy().hasHeightForWidth())
+        self.graphicsView_Raw.setSizePolicy(sizePolicy)
+        self.graphicsView_Raw.setObjectName(_fromUtf8("graphicsView_Raw"))
+        self.horizontalLayout_14.addWidget(self.graphicsView_Raw)
+        self.verticalLayout_9 = QtGui.QVBoxLayout()
+        self.verticalLayout_9.setObjectName(_fromUtf8("verticalLayout_9"))
+        self.pushButton_plotRaw = QtGui.QPushButton(self.tab_3)
+        self.pushButton_plotRaw.setObjectName(_fromUtf8("pushButton_plotRaw"))
+        self.verticalLayout_9.addWidget(self.pushButton_plotRaw)
+        self.checkBox_overpltRawDet = QtGui.QCheckBox(self.tab_3)
+        self.checkBox_overpltRawDet.setObjectName(_fromUtf8("checkBox_overpltRawDet"))
+        self.verticalLayout_9.addWidget(self.checkBox_overpltRawDet)
+        spacerItem7 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Preferred)
+        self.verticalLayout_9.addItem(spacerItem7)
+        self.pushButton_ptUp = QtGui.QPushButton(self.tab_3)
+        self.pushButton_ptUp.setObjectName(_fromUtf8("pushButton_ptUp"))
+        self.verticalLayout_9.addWidget(self.pushButton_ptUp)
+        self.pushButton_ptDown = QtGui.QPushButton(self.tab_3)
+        self.pushButton_ptDown.setObjectName(_fromUtf8("pushButton_ptDown"))
+        self.verticalLayout_9.addWidget(self.pushButton_ptDown)
+        spacerItem8 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Preferred)
+        self.verticalLayout_9.addItem(spacerItem8)
+        self.pushButton_clearRawDets = QtGui.QPushButton(self.tab_3)
+        self.pushButton_clearRawDets.setObjectName(_fromUtf8("pushButton_clearRawDets"))
+        self.verticalLayout_9.addWidget(self.pushButton_clearRawDets)
+        self.horizontalLayout_14.addLayout(self.verticalLayout_9)
+        self.verticalLayout_7.addLayout(self.horizontalLayout_14)
+        self.horizontalLayout_12 = QtGui.QHBoxLayout()
+        self.horizontalLayout_12.setObjectName(_fromUtf8("horizontalLayout_12"))
+        self.textBrowser_RawDetInfo = QtGui.QTextBrowser(self.tab_3)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.textBrowser_RawDetInfo.sizePolicy().hasHeightForWidth())
+        self.textBrowser_RawDetInfo.setSizePolicy(sizePolicy)
+        self.textBrowser_RawDetInfo.setObjectName(_fromUtf8("textBrowser_RawDetInfo"))
+        self.horizontalLayout_12.addWidget(self.textBrowser_RawDetInfo)
+        self.verticalLayout_7.addLayout(self.horizontalLayout_12)
+        self.gridLayout_4.addLayout(self.verticalLayout_7, 0, 0, 1, 1)
+        self.tabWidget.addTab(self.tab_3, _fromUtf8(""))
+        self.tab_5 = QtGui.QWidget()
+        self.tab_5.setObjectName(_fromUtf8("tab_5"))
+        self.gridLayout_7 = QtGui.QGridLayout(self.tab_5)
+        self.gridLayout_7.setObjectName(_fromUtf8("gridLayout_7"))
+        self.verticalLayout_8 = QtGui.QVBoxLayout()
+        self.verticalLayout_8.setObjectName(_fromUtf8("verticalLayout_8"))
+        self.horizontalLayout_21 = QtGui.QHBoxLayout()
+        self.horizontalLayout_21.setObjectName(_fromUtf8("horizontalLayout_21"))
+        self.label_11 = QtGui.QLabel(self.tab_5)
+        self.label_11.setObjectName(_fromUtf8("label_11"))
+        self.horizontalLayout_21.addWidget(self.label_11)
+        self.lineEdit_detID = QtGui.QLineEdit(self.tab_5)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.lineEdit_detID.sizePolicy().hasHeightForWidth())
+        self.lineEdit_detID.setSizePolicy(sizePolicy)
+        self.lineEdit_detID.setObjectName(_fromUtf8("lineEdit_detID"))
+        self.horizontalLayout_21.addWidget(self.lineEdit_detID)
+        self.label_17 = QtGui.QLabel(self.tab_5)
+        self.label_17.setObjectName(_fromUtf8("label_17"))
+        self.horizontalLayout_21.addWidget(self.label_17)
+        spacerItem9 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
+        self.horizontalLayout_21.addItem(spacerItem9)
+        self.verticalLayout_8.addLayout(self.horizontalLayout_21)
+        self.horizontalLayout_17 = QtGui.QHBoxLayout()
+        self.horizontalLayout_17.setObjectName(_fromUtf8("horizontalLayout_17"))
+        self.horizontalLayout_23 = QtGui.QHBoxLayout()
+        self.horizontalLayout_23.setObjectName(_fromUtf8("horizontalLayout_23"))
+        self.verticalLayout_13 = QtGui.QVBoxLayout()
+        self.verticalLayout_13.setObjectName(_fromUtf8("verticalLayout_13"))
+        self.graphicsView_indvDet = Qt4MplPlotView(self.tab_5)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.graphicsView_indvDet.sizePolicy().hasHeightForWidth())
+        self.graphicsView_indvDet.setSizePolicy(sizePolicy)
+        self.graphicsView_indvDet.setObjectName(_fromUtf8("graphicsView_indvDet"))
+        self.verticalLayout_13.addWidget(self.graphicsView_indvDet)
+        self.comboBox_indvDetXLabel = QtGui.QComboBox(self.tab_5)
+        self.comboBox_indvDetXLabel.setObjectName(_fromUtf8("comboBox_indvDetXLabel"))
+        self.verticalLayout_13.addWidget(self.comboBox_indvDetXLabel)
+        self.horizontalLayout_23.addLayout(self.verticalLayout_13)
+        self.verticalLayout_12 = QtGui.QVBoxLayout()
+        self.verticalLayout_12.setObjectName(_fromUtf8("verticalLayout_12"))
+        self.pushButton_plotIndvDet = QtGui.QPushButton(self.tab_5)
+        self.pushButton_plotIndvDet.setObjectName(_fromUtf8("pushButton_plotIndvDet"))
+        self.verticalLayout_12.addWidget(self.pushButton_plotIndvDet)
+        self.checkBox_overPlotIndvDet = QtGui.QCheckBox(self.tab_5)
+        self.checkBox_overPlotIndvDet.setObjectName(_fromUtf8("checkBox_overPlotIndvDet"))
+        self.verticalLayout_12.addWidget(self.checkBox_overPlotIndvDet)
+        spacerItem10 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
+        self.verticalLayout_12.addItem(spacerItem10)
+        self.pushButton_plotAllDet = QtGui.QPushButton(self.tab_5)
+        self.pushButton_plotAllDet.setEnabled(False)
+        self.pushButton_plotAllDet.setObjectName(_fromUtf8("pushButton_plotAllDet"))
+        self.verticalLayout_12.addWidget(self.pushButton_plotAllDet)
+        spacerItem11 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
+        self.verticalLayout_12.addItem(spacerItem11)
+        self.pushButton_plotPrevDet = QtGui.QPushButton(self.tab_5)
+        self.pushButton_plotPrevDet.setObjectName(_fromUtf8("pushButton_plotPrevDet"))
+        self.verticalLayout_12.addWidget(self.pushButton_plotPrevDet)
+        self.pushButton_plotNextDet = QtGui.QPushButton(self.tab_5)
+        self.pushButton_plotNextDet.setObjectName(_fromUtf8("pushButton_plotNextDet"))
+        self.verticalLayout_12.addWidget(self.pushButton_plotNextDet)
+        spacerItem12 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
+        self.verticalLayout_12.addItem(spacerItem12)
+        self.pushButton_clearCanvasIndDet = QtGui.QPushButton(self.tab_5)
+        self.pushButton_clearCanvasIndDet.setObjectName(_fromUtf8("pushButton_clearCanvasIndDet"))
+        self.verticalLayout_12.addWidget(self.pushButton_clearCanvasIndDet)
+        spacerItem13 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
+        self.verticalLayout_12.addItem(spacerItem13)
+        self.comboBox_indvDetYLabel = QtGui.QComboBox(self.tab_5)
+        self.comboBox_indvDetYLabel.setObjectName(_fromUtf8("comboBox_indvDetYLabel"))
+        self.verticalLayout_12.addWidget(self.comboBox_indvDetYLabel)
+        self.pushButton_plotLog = QtGui.QPushButton(self.tab_5)
+        self.pushButton_plotLog.setObjectName(_fromUtf8("pushButton_plotLog"))
+        self.verticalLayout_12.addWidget(self.pushButton_plotLog)
+        spacerItem14 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
+        self.verticalLayout_12.addItem(spacerItem14)
+        self.horizontalLayout_23.addLayout(self.verticalLayout_12)
+        self.horizontalLayout_17.addLayout(self.horizontalLayout_23)
+        self.verticalLayout_8.addLayout(self.horizontalLayout_17)
+        self.gridLayout_7.addLayout(self.verticalLayout_8, 0, 0, 1, 1)
+        self.tabWidget.addTab(self.tab_5, _fromUtf8(""))
+        self.tab = QtGui.QWidget()
+        self.tab.setObjectName(_fromUtf8("tab"))
+        self.gridLayout_2 = QtGui.QGridLayout(self.tab)
+        self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))
+        self.verticalLayout_2 = QtGui.QVBoxLayout()
+        self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
+        self.horizontalLayout_3 = QtGui.QHBoxLayout()
+        self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3"))
+        self.label_normalizeMonitor = QtGui.QLabel(self.tab)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.label_normalizeMonitor.sizePolicy().hasHeightForWidth())
+        self.label_normalizeMonitor.setSizePolicy(sizePolicy)
+        self.label_normalizeMonitor.setMinimumSize(QtCore.QSize(155, 0))
+        self.label_normalizeMonitor.setObjectName(_fromUtf8("label_normalizeMonitor"))
+        self.horizontalLayout_3.addWidget(self.label_normalizeMonitor)
+        self.lineEdit_normalizeMonitor = QtGui.QLineEdit(self.tab)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.lineEdit_normalizeMonitor.sizePolicy().hasHeightForWidth())
+        self.lineEdit_normalizeMonitor.setSizePolicy(sizePolicy)
+        self.lineEdit_normalizeMonitor.setMinimumSize(QtCore.QSize(300, 0))
+        self.lineEdit_normalizeMonitor.setObjectName(_fromUtf8("lineEdit_normalizeMonitor"))
+        self.horizontalLayout_3.addWidget(self.lineEdit_normalizeMonitor)
+        spacerItem15 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
+        self.horizontalLayout_3.addItem(spacerItem15)
+        self.verticalLayout_2.addLayout(self.horizontalLayout_3)
+        self.horizontalLayout_22 = QtGui.QHBoxLayout()
+        self.horizontalLayout_22.setObjectName(_fromUtf8("horizontalLayout_22"))
+        self.label_outputFormat = QtGui.QLabel(self.tab)
+        self.label_outputFormat.setObjectName(_fromUtf8("label_outputFormat"))
+        self.horizontalLayout_22.addWidget(self.label_outputFormat)
+        self.comboBox_outputFormat = QtGui.QComboBox(self.tab)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.comboBox_outputFormat.sizePolicy().hasHeightForWidth())
+        self.comboBox_outputFormat.setSizePolicy(sizePolicy)
+        self.comboBox_outputFormat.setObjectName(_fromUtf8("comboBox_outputFormat"))
+        self.horizontalLayout_22.addWidget(self.comboBox_outputFormat)
+        self.lineEdit_outputFileName = QtGui.QLineEdit(self.tab)
+        self.lineEdit_outputFileName.setObjectName(_fromUtf8("lineEdit_outputFileName"))
+        self.horizontalLayout_22.addWidget(self.lineEdit_outputFileName)
+        self.pushButton_saveData = QtGui.QPushButton(self.tab)
+        self.pushButton_saveData.setObjectName(_fromUtf8("pushButton_saveData"))
+        self.horizontalLayout_22.addWidget(self.pushButton_saveData)
+        spacerItem16 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
+        self.horizontalLayout_22.addItem(spacerItem16)
+        self.verticalLayout_2.addLayout(self.horizontalLayout_22)
+        self.horizontalLayout_5 = QtGui.QHBoxLayout()
+        self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5"))
+        self.gridLayout_reductionView = QtGui.QGridLayout()
+        self.gridLayout_reductionView.setObjectName(_fromUtf8("gridLayout_reductionView"))
+        self.graphicsView_reducedData = Qt4MplPlotView(self.tab)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.graphicsView_reducedData.sizePolicy().hasHeightForWidth())
+        self.graphicsView_reducedData.setSizePolicy(sizePolicy)
+        self.graphicsView_reducedData.setObjectName(_fromUtf8("graphicsView_reducedData"))
+        self.gridLayout_reductionView.addWidget(self.graphicsView_reducedData, 0, 0, 1, 1)
+        self.horizontalLayout_5.addLayout(self.gridLayout_reductionView)
+        self.verticalLayout_3 = QtGui.QVBoxLayout()
+        self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3"))
+        self.horizontalLayout_6 = QtGui.QHBoxLayout()
+        self.horizontalLayout_6.setObjectName(_fromUtf8("horizontalLayout_6"))
+        self.label_18 = QtGui.QLabel(self.tab)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.label_18.sizePolicy().hasHeightForWidth())
+        self.label_18.setSizePolicy(sizePolicy)
+        self.label_18.setObjectName(_fromUtf8("label_18"))
+        self.horizontalLayout_6.addWidget(self.label_18)
+        self.verticalLayout_3.addLayout(self.horizontalLayout_6)
+        self.pushButton_unit2theta = QtGui.QPushButton(self.tab)
+        self.pushButton_unit2theta.setObjectName(_fromUtf8("pushButton_unit2theta"))
+        self.verticalLayout_3.addWidget(self.pushButton_unit2theta)
+        self.pushButton_unitD = QtGui.QPushButton(self.tab)
+        self.pushButton_unitD.setObjectName(_fromUtf8("pushButton_unitD"))
+        self.verticalLayout_3.addWidget(self.pushButton_unitD)
+        self.pushButton_unitQ = QtGui.QPushButton(self.tab)
+        self.pushButton_unitQ.setObjectName(_fromUtf8("pushButton_unitQ"))
+        self.verticalLayout_3.addWidget(self.pushButton_unitQ)
+        spacerItem17 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Preferred)
+        self.verticalLayout_3.addItem(spacerItem17)
+        self.horizontalLayout_27 = QtGui.QHBoxLayout()
+        self.horizontalLayout_27.setObjectName(_fromUtf8("horizontalLayout_27"))
+        self.label_19 = QtGui.QLabel(self.tab)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.label_19.sizePolicy().hasHeightForWidth())
+        self.label_19.setSizePolicy(sizePolicy)
+        self.label_19.setObjectName(_fromUtf8("label_19"))
+        self.horizontalLayout_27.addWidget(self.label_19)
+        self.verticalLayout_3.addLayout(self.horizontalLayout_27)
+        self.horizontalLayout_26 = QtGui.QHBoxLayout()
+        self.horizontalLayout_26.setObjectName(_fromUtf8("horizontalLayout_26"))
+        self.label_xmin = QtGui.QLabel(self.tab)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.label_xmin.sizePolicy().hasHeightForWidth())
+        self.label_xmin.setSizePolicy(sizePolicy)
+        self.label_xmin.setObjectName(_fromUtf8("label_xmin"))
+        self.horizontalLayout_26.addWidget(self.label_xmin)
+        self.lineEdit_xmin = QtGui.QLineEdit(self.tab)
+        self.lineEdit_xmin.setEnabled(True)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.lineEdit_xmin.sizePolicy().hasHeightForWidth())
+        self.lineEdit_xmin.setSizePolicy(sizePolicy)
+        self.lineEdit_xmin.setMinimumSize(QtCore.QSize(10, 0))
+        self.lineEdit_xmin.setObjectName(_fromUtf8("lineEdit_xmin"))
+        self.horizontalLayout_26.addWidget(self.lineEdit_xmin)
+        self.verticalLayout_3.addLayout(self.horizontalLayout_26)
+        self.horizontalLayout_28 = QtGui.QHBoxLayout()
+        self.horizontalLayout_28.setObjectName(_fromUtf8("horizontalLayout_28"))
+        self.label_xmax_2 = QtGui.QLabel(self.tab)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.label_xmax_2.sizePolicy().hasHeightForWidth())
+        self.label_xmax_2.setSizePolicy(sizePolicy)
+        self.label_xmax_2.setObjectName(_fromUtf8("label_xmax_2"))
+        self.horizontalLayout_28.addWidget(self.label_xmax_2)
+        self.lineEdit_xmax = QtGui.QLineEdit(self.tab)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.lineEdit_xmax.sizePolicy().hasHeightForWidth())
+        self.lineEdit_xmax.setSizePolicy(sizePolicy)
+        self.lineEdit_xmax.setMinimumSize(QtCore.QSize(10, 0))
+        self.lineEdit_xmax.setObjectName(_fromUtf8("lineEdit_xmax"))
+        self.horizontalLayout_28.addWidget(self.lineEdit_xmax)
+        self.verticalLayout_3.addLayout(self.horizontalLayout_28)
+        self.horizontalLayout_29 = QtGui.QHBoxLayout()
+        self.horizontalLayout_29.setObjectName(_fromUtf8("horizontalLayout_29"))
+        self.label_binsize = QtGui.QLabel(self.tab)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.label_binsize.sizePolicy().hasHeightForWidth())
+        self.label_binsize.setSizePolicy(sizePolicy)
+        self.label_binsize.setObjectName(_fromUtf8("label_binsize"))
+        self.horizontalLayout_29.addWidget(self.label_binsize)
+        self.lineEdit_binsize = QtGui.QLineEdit(self.tab)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.lineEdit_binsize.sizePolicy().hasHeightForWidth())
+        self.lineEdit_binsize.setSizePolicy(sizePolicy)
+        self.lineEdit_binsize.setMinimumSize(QtCore.QSize(10, 0))
+        self.lineEdit_binsize.setObjectName(_fromUtf8("lineEdit_binsize"))
+        self.horizontalLayout_29.addWidget(self.lineEdit_binsize)
+        self.verticalLayout_3.addLayout(self.horizontalLayout_29)
+        spacerItem18 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Preferred)
+        self.verticalLayout_3.addItem(spacerItem18)
+        self.pushButton_nextScan = QtGui.QPushButton(self.tab)
+        self.pushButton_nextScan.setObjectName(_fromUtf8("pushButton_nextScan"))
+        self.verticalLayout_3.addWidget(self.pushButton_nextScan)
+        self.pushButton_prevScan = QtGui.QPushButton(self.tab)
+        self.pushButton_prevScan.setObjectName(_fromUtf8("pushButton_prevScan"))
+        self.verticalLayout_3.addWidget(self.pushButton_prevScan)
+        self.checkBox_clearPrevious = QtGui.QCheckBox(self.tab)
+        self.checkBox_clearPrevious.setObjectName(_fromUtf8("checkBox_clearPrevious"))
+        self.verticalLayout_3.addWidget(self.checkBox_clearPrevious)
+        spacerItem19 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Preferred)
+        self.verticalLayout_3.addItem(spacerItem19)
+        self.pushButton_clearTab2Canvas = QtGui.QPushButton(self.tab)
+        self.pushButton_clearTab2Canvas.setObjectName(_fromUtf8("pushButton_clearTab2Canvas"))
+        self.verticalLayout_3.addWidget(self.pushButton_clearTab2Canvas)
+        spacerItem20 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
+        self.verticalLayout_3.addItem(spacerItem20)
+        self.horizontalLayout_5.addLayout(self.verticalLayout_3)
+        self.verticalLayout_2.addLayout(self.horizontalLayout_5)
+        self.gridLayout_2.addLayout(self.verticalLayout_2, 0, 0, 1, 1)
+        self.tabWidget.addTab(self.tab, _fromUtf8(""))
+        self.tab_merge = QtGui.QWidget()
+        self.tab_merge.setObjectName(_fromUtf8("tab_merge"))
+        self.gridLayout_6 = QtGui.QGridLayout(self.tab_merge)
+        self.gridLayout_6.setObjectName(_fromUtf8("gridLayout_6"))
+        self.verticalLayout_merge = QtGui.QVBoxLayout()
+        self.verticalLayout_merge.setObjectName(_fromUtf8("verticalLayout_merge"))
+        self.horizontalLayout_19 = QtGui.QHBoxLayout()
+        self.horizontalLayout_19.setObjectName(_fromUtf8("horizontalLayout_19"))
+        self.label_8 = QtGui.QLabel(self.tab_merge)
+        self.label_8.setObjectName(_fromUtf8("label_8"))
+        self.horizontalLayout_19.addWidget(self.label_8)
+        self.lineEdit_scanStart = QtGui.QLineEdit(self.tab_merge)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.lineEdit_scanStart.sizePolicy().hasHeightForWidth())
+        self.lineEdit_scanStart.setSizePolicy(sizePolicy)
+        self.lineEdit_scanStart.setObjectName(_fromUtf8("lineEdit_scanStart"))
+        self.horizontalLayout_19.addWidget(self.lineEdit_scanStart)
+        self.label_9 = QtGui.QLabel(self.tab_merge)
+        self.label_9.setObjectName(_fromUtf8("label_9"))
+        self.horizontalLayout_19.addWidget(self.label_9)
+        self.lineEdit_scanEnd = QtGui.QLineEdit(self.tab_merge)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.lineEdit_scanEnd.sizePolicy().hasHeightForWidth())
+        self.lineEdit_scanEnd.setSizePolicy(sizePolicy)
+        self.lineEdit_scanEnd.setObjectName(_fromUtf8("lineEdit_scanEnd"))
+        self.horizontalLayout_19.addWidget(self.lineEdit_scanEnd)
+        self.label_12 = QtGui.QLabel(self.tab_merge)
+        self.label_12.setObjectName(_fromUtf8("label_12"))
+        self.horizontalLayout_19.addWidget(self.label_12)
+        self.lineEdit_extraScans = QtGui.QLineEdit(self.tab_merge)
+        self.lineEdit_extraScans.setObjectName(_fromUtf8("lineEdit_extraScans"))
+        self.horizontalLayout_19.addWidget(self.lineEdit_extraScans)
+        self.label_10 = QtGui.QLabel(self.tab_merge)
+        self.label_10.setObjectName(_fromUtf8("label_10"))
+        self.horizontalLayout_19.addWidget(self.label_10)
+        self.lineEdit_exclScans = QtGui.QLineEdit(self.tab_merge)
+        self.lineEdit_exclScans.setObjectName(_fromUtf8("lineEdit_exclScans"))
+        self.horizontalLayout_19.addWidget(self.lineEdit_exclScans)
+        self.pushButton_loadMultData = QtGui.QPushButton(self.tab_merge)
+        self.pushButton_loadMultData.setObjectName(_fromUtf8("pushButton_loadMultData"))
+        self.horizontalLayout_19.addWidget(self.pushButton_loadMultData)
+        spacerItem21 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
+        self.horizontalLayout_19.addItem(spacerItem21)
+        self.verticalLayout_merge.addLayout(self.horizontalLayout_19)
+        self.horizontalLayout_18 = QtGui.QHBoxLayout()
+        self.horizontalLayout_18.setObjectName(_fromUtf8("horizontalLayout_18"))
+        self.label_15 = QtGui.QLabel(self.tab_merge)
+        self.label_15.setObjectName(_fromUtf8("label_15"))
+        self.horizontalLayout_18.addWidget(self.label_15)
+        self.lineEdit_mergeMinX = QtGui.QLineEdit(self.tab_merge)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.lineEdit_mergeMinX.sizePolicy().hasHeightForWidth())
+        self.lineEdit_mergeMinX.setSizePolicy(sizePolicy)
+        self.lineEdit_mergeMinX.setMinimumSize(QtCore.QSize(0, 0))
+        self.lineEdit_mergeMinX.setObjectName(_fromUtf8("lineEdit_mergeMinX"))
+        self.horizontalLayout_18.addWidget(self.lineEdit_mergeMinX)
+        self.label_14 = QtGui.QLabel(self.tab_merge)
+        self.label_14.setObjectName(_fromUtf8("label_14"))
+        self.horizontalLayout_18.addWidget(self.label_14)
+        self.lineEdit_mergeMaxX = QtGui.QLineEdit(self.tab_merge)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.lineEdit_mergeMaxX.sizePolicy().hasHeightForWidth())
+        self.lineEdit_mergeMaxX.setSizePolicy(sizePolicy)
+        self.lineEdit_mergeMaxX.setObjectName(_fromUtf8("lineEdit_mergeMaxX"))
+        self.horizontalLayout_18.addWidget(self.lineEdit_mergeMaxX)
+        self.label_16 = QtGui.QLabel(self.tab_merge)
+        self.label_16.setObjectName(_fromUtf8("label_16"))
+        self.horizontalLayout_18.addWidget(self.label_16)
+        self.lineEdit_mergeBinSize = QtGui.QLineEdit(self.tab_merge)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.lineEdit_mergeBinSize.sizePolicy().hasHeightForWidth())
+        self.lineEdit_mergeBinSize.setSizePolicy(sizePolicy)
+        self.lineEdit_mergeBinSize.setObjectName(_fromUtf8("lineEdit_mergeBinSize"))
+        self.horizontalLayout_18.addWidget(self.lineEdit_mergeBinSize)
+        self.comboBox_mscanUnit = QtGui.QComboBox(self.tab_merge)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.comboBox_mscanUnit.sizePolicy().hasHeightForWidth())
+        self.comboBox_mscanUnit.setSizePolicy(sizePolicy)
+        self.comboBox_mscanUnit.setMinimumSize(QtCore.QSize(140, 0))
+        self.comboBox_mscanUnit.setObjectName(_fromUtf8("comboBox_mscanUnit"))
+        self.comboBox_mscanUnit.addItem(_fromUtf8(""))
+        self.horizontalLayout_18.addWidget(self.comboBox_mscanUnit)
+        self.pushButton_mscanBin = QtGui.QPushButton(self.tab_merge)
+        self.pushButton_mscanBin.setObjectName(_fromUtf8("pushButton_mscanBin"))
+        self.horizontalLayout_18.addWidget(self.pushButton_mscanBin)
+        spacerItem22 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
+        self.horizontalLayout_18.addItem(spacerItem22)
+        self.label_mergeMessage = QtGui.QLabel(self.tab_merge)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.label_mergeMessage.sizePolicy().hasHeightForWidth())
+        self.label_mergeMessage.setSizePolicy(sizePolicy)
+        self.label_mergeMessage.setObjectName(_fromUtf8("label_mergeMessage"))
+        self.horizontalLayout_18.addWidget(self.label_mergeMessage)
+        self.verticalLayout_merge.addLayout(self.horizontalLayout_18)
+        self.horizontalLayout_16 = QtGui.QHBoxLayout()
+        self.horizontalLayout_16.setObjectName(_fromUtf8("horizontalLayout_16"))
+        self.verticalLayout_mergeView = QtGui.QVBoxLayout()
+        self.verticalLayout_mergeView.setObjectName(_fromUtf8("verticalLayout_mergeView"))
+        self.graphicsView_mergeRun = Qt4MplPlotView(self.tab_merge)
+        self.graphicsView_mergeRun.setObjectName(_fromUtf8("graphicsView_mergeRun"))
+        self.verticalLayout_mergeView.addWidget(self.graphicsView_mergeRun)
+        self.horizontalLayout_16.addLayout(self.verticalLayout_mergeView)
+        self.verticalLayout_11 = QtGui.QVBoxLayout()
+        self.verticalLayout_11.setObjectName(_fromUtf8("verticalLayout_11"))
+        spacerItem23 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Preferred)
+        self.verticalLayout_11.addItem(spacerItem23)
+        self.pushButton_viewMScan1D = QtGui.QPushButton(self.tab_merge)
+        self.pushButton_viewMScan1D.setObjectName(_fromUtf8("pushButton_viewMScan1D"))
+        self.verticalLayout_11.addWidget(self.pushButton_viewMScan1D)
+        self.pushButton_view2D = QtGui.QPushButton(self.tab_merge)
+        self.pushButton_view2D.setObjectName(_fromUtf8("pushButton_view2D"))
+        self.verticalLayout_11.addWidget(self.pushButton_view2D)
+        self.pushButton_saveAllIndScans = QtGui.QPushButton(self.tab_merge)
+        self.pushButton_saveAllIndScans.setObjectName(_fromUtf8("pushButton_saveAllIndScans"))
+        self.verticalLayout_11.addWidget(self.pushButton_saveAllIndScans)
+        spacerItem24 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
+        self.verticalLayout_11.addItem(spacerItem24)
+        self.pushButton_mergeScans = QtGui.QPushButton(self.tab_merge)
+        self.pushButton_mergeScans.setObjectName(_fromUtf8("pushButton_mergeScans"))
+        self.verticalLayout_11.addWidget(self.pushButton_mergeScans)
+        self.pushButton_viewMerge = QtGui.QPushButton(self.tab_merge)
+        self.pushButton_viewMerge.setObjectName(_fromUtf8("pushButton_viewMerge"))
+        self.verticalLayout_11.addWidget(self.pushButton_viewMerge)
+        self.pushButton_saveMerge = QtGui.QPushButton(self.tab_merge)
+        self.pushButton_saveMerge.setObjectName(_fromUtf8("pushButton_saveMerge"))
+        self.verticalLayout_11.addWidget(self.pushButton_saveMerge)
+        spacerItem25 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Preferred)
+        self.verticalLayout_11.addItem(spacerItem25)
+        self.pushButton_clearMultCanvas = QtGui.QPushButton(self.tab_merge)
+        self.pushButton_clearMultCanvas.setObjectName(_fromUtf8("pushButton_clearMultCanvas"))
+        self.verticalLayout_11.addWidget(self.pushButton_clearMultCanvas)
+        spacerItem26 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
+        self.verticalLayout_11.addItem(spacerItem26)
+        self.horizontalLayout_16.addLayout(self.verticalLayout_11)
+        self.verticalLayout_merge.addLayout(self.horizontalLayout_16)
+        self.horizontalLayout_20 = QtGui.QHBoxLayout()
+        self.horizontalLayout_20.setObjectName(_fromUtf8("horizontalLayout_20"))
+        self.label_13 = QtGui.QLabel(self.tab_merge)
+        self.label_13.setObjectName(_fromUtf8("label_13"))
+        self.horizontalLayout_20.addWidget(self.label_13)
+        self.comboBox_2 = QtGui.QComboBox(self.tab_merge)
+        self.comboBox_2.setObjectName(_fromUtf8("comboBox_2"))
+        self.horizontalLayout_20.addWidget(self.comboBox_2)
+        self.label_7 = QtGui.QLabel(self.tab_merge)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.label_7.sizePolicy().hasHeightForWidth())
+        self.label_7.setSizePolicy(sizePolicy)
+        self.label_7.setObjectName(_fromUtf8("label_7"))
+        self.horizontalLayout_20.addWidget(self.label_7)
+        self.verticalLayout_merge.addLayout(self.horizontalLayout_20)
+        self.gridLayout_6.addLayout(self.verticalLayout_merge, 0, 0, 1, 1)
+        self.tabWidget.addTab(self.tab_merge, _fromUtf8(""))
+        self.tab_4 = QtGui.QWidget()
+        self.tab_4.setObjectName(_fromUtf8("tab_4"))
+        self.gridLayout_5 = QtGui.QGridLayout(self.tab_4)
+        self.gridLayout_5.setObjectName(_fromUtf8("gridLayout_5"))
+        self.verticalLayout_5 = QtGui.QVBoxLayout()
+        self.verticalLayout_5.setObjectName(_fromUtf8("verticalLayout_5"))
+        self.horizontalLayout_15 = QtGui.QHBoxLayout()
+        self.horizontalLayout_15.setObjectName(_fromUtf8("horizontalLayout_15"))
+        self.label_2 = QtGui.QLabel(self.tab_4)
+        self.label_2.setObjectName(_fromUtf8("label_2"))
+        self.horizontalLayout_15.addWidget(self.label_2)
+        self.lineEdit_stripVPeaks = QtGui.QLineEdit(self.tab_4)
+        self.lineEdit_stripVPeaks.setEnabled(False)
+        self.lineEdit_stripVPeaks.setObjectName(_fromUtf8("lineEdit_stripVPeaks"))
+        self.horizontalLayout_15.addWidget(self.lineEdit_stripVPeaks)
+        spacerItem27 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Minimum)
+        self.horizontalLayout_15.addItem(spacerItem27)
+        self.pushButton_resetVanPeakList = QtGui.QPushButton(self.tab_4)
+        self.pushButton_resetVanPeakList.setObjectName(_fromUtf8("pushButton_resetVanPeakList"))
+        self.horizontalLayout_15.addWidget(self.pushButton_resetVanPeakList)
+        self.verticalLayout_5.addLayout(self.horizontalLayout_15)
+        self.horizontalLayout_11 = QtGui.QHBoxLayout()
+        self.horizontalLayout_11.setObjectName(_fromUtf8("horizontalLayout_11"))
+        self.graphicsView_vanPeaks = Qt4MplPlotView(self.tab_4)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.graphicsView_vanPeaks.sizePolicy().hasHeightForWidth())
+        self.graphicsView_vanPeaks.setSizePolicy(sizePolicy)
+        self.graphicsView_vanPeaks.setObjectName(_fromUtf8("graphicsView_vanPeaks"))
+        self.horizontalLayout_11.addWidget(self.graphicsView_vanPeaks)
+        self.verticalLayout_6 = QtGui.QVBoxLayout()
+        self.verticalLayout_6.setObjectName(_fromUtf8("verticalLayout_6"))
+        spacerItem28 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Preferred)
+        self.verticalLayout_6.addItem(spacerItem28)
+        self.label_3 = QtGui.QLabel(self.tab_4)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Preferred)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.label_3.sizePolicy().hasHeightForWidth())
+        self.label_3.setSizePolicy(sizePolicy)
+        self.label_3.setObjectName(_fromUtf8("label_3"))
+        self.verticalLayout_6.addWidget(self.label_3)
+        self.line = QtGui.QFrame(self.tab_4)
+        self.line.setFrameShape(QtGui.QFrame.HLine)
+        self.line.setFrameShadow(QtGui.QFrame.Sunken)
+        self.line.setObjectName(_fromUtf8("line"))
+        self.verticalLayout_6.addWidget(self.line)
+        self.lineEdit_min2Theta = QtGui.QLineEdit(self.tab_4)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.lineEdit_min2Theta.sizePolicy().hasHeightForWidth())
+        self.lineEdit_min2Theta.setSizePolicy(sizePolicy)
+        self.lineEdit_min2Theta.setObjectName(_fromUtf8("lineEdit_min2Theta"))
+        self.verticalLayout_6.addWidget(self.lineEdit_min2Theta)
+        self.label_4 = QtGui.QLabel(self.tab_4)
+        self.label_4.setObjectName(_fromUtf8("label_4"))
+        self.verticalLayout_6.addWidget(self.label_4)
+        self.lineEdit_max2Theta = QtGui.QLineEdit(self.tab_4)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.lineEdit_max2Theta.sizePolicy().hasHeightForWidth())
+        self.lineEdit_max2Theta.setSizePolicy(sizePolicy)
+        self.lineEdit_max2Theta.setObjectName(_fromUtf8("lineEdit_max2Theta"))
+        self.verticalLayout_6.addWidget(self.lineEdit_max2Theta)
+        self.label_5 = QtGui.QLabel(self.tab_4)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Preferred)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.label_5.sizePolicy().hasHeightForWidth())
+        self.label_5.setSizePolicy(sizePolicy)
+        self.label_5.setObjectName(_fromUtf8("label_5"))
+        self.verticalLayout_6.addWidget(self.label_5)
+        self.lineEdit_binsize2Theta = QtGui.QLineEdit(self.tab_4)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.lineEdit_binsize2Theta.sizePolicy().hasHeightForWidth())
+        self.lineEdit_binsize2Theta.setSizePolicy(sizePolicy)
+        self.lineEdit_binsize2Theta.setObjectName(_fromUtf8("lineEdit_binsize2Theta"))
+        self.verticalLayout_6.addWidget(self.lineEdit_binsize2Theta)
+        self.pushButton_rebin2Theta = QtGui.QPushButton(self.tab_4)
+        self.pushButton_rebin2Theta.setObjectName(_fromUtf8("pushButton_rebin2Theta"))
+        self.verticalLayout_6.addWidget(self.pushButton_rebin2Theta)
+        spacerItem29 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Preferred)
+        self.verticalLayout_6.addItem(spacerItem29)
+        self.pushButton_stripVanPeaks = QtGui.QPushButton(self.tab_4)
+        self.pushButton_stripVanPeaks.setObjectName(_fromUtf8("pushButton_stripVanPeaks"))
+        self.verticalLayout_6.addWidget(self.pushButton_stripVanPeaks)
+        spacerItem30 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
+        self.verticalLayout_6.addItem(spacerItem30)
+        self.verticalLayout_14 = QtGui.QVBoxLayout()
+        self.verticalLayout_14.setObjectName(_fromUtf8("verticalLayout_14"))
+        self.pushButton_smoothVanData = QtGui.QPushButton(self.tab_4)
+        self.pushButton_smoothVanData.setObjectName(_fromUtf8("pushButton_smoothVanData"))
+        self.verticalLayout_14.addWidget(self.pushButton_smoothVanData)
+        self.label_20 = QtGui.QLabel(self.tab_4)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Preferred)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.label_20.sizePolicy().hasHeightForWidth())
+        self.label_20.setSizePolicy(sizePolicy)
+        self.label_20.setObjectName(_fromUtf8("label_20"))
+        self.verticalLayout_14.addWidget(self.label_20)
+        self.lineEdit_smoothParams = QtGui.QLineEdit(self.tab_4)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.lineEdit_smoothParams.sizePolicy().hasHeightForWidth())
+        self.lineEdit_smoothParams.setSizePolicy(sizePolicy)
+        self.lineEdit_smoothParams.setObjectName(_fromUtf8("lineEdit_smoothParams"))
+        self.verticalLayout_14.addWidget(self.lineEdit_smoothParams)
+        self.pushButton_applySmooth = QtGui.QPushButton(self.tab_4)
+        self.pushButton_applySmooth.setObjectName(_fromUtf8("pushButton_applySmooth"))
+        self.verticalLayout_14.addWidget(self.pushButton_applySmooth)
+        self.pushButton_undoSmooth = QtGui.QPushButton(self.tab_4)
+        self.pushButton_undoSmooth.setObjectName(_fromUtf8("pushButton_undoSmooth"))
+        self.verticalLayout_14.addWidget(self.pushButton_undoSmooth)
+        self.verticalLayout_6.addLayout(self.verticalLayout_14)
+        spacerItem31 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Preferred)
+        self.verticalLayout_6.addItem(spacerItem31)
+        self.pushButton_saveVanRun = QtGui.QPushButton(self.tab_4)
+        self.pushButton_saveVanRun.setObjectName(_fromUtf8("pushButton_saveVanRun"))
+        self.verticalLayout_6.addWidget(self.pushButton_saveVanRun)
+        spacerItem32 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.MinimumExpanding)
+        self.verticalLayout_6.addItem(spacerItem32)
+        self.horizontalLayout_11.addLayout(self.verticalLayout_6)
+        self.verticalLayout_5.addLayout(self.horizontalLayout_11)
+        self.gridLayout_5.addLayout(self.verticalLayout_5, 0, 0, 1, 1)
+        self.tabWidget.addTab(self.tab_4, _fromUtf8(""))
+        self.tab_2 = QtGui.QWidget()
+        self.tab_2.setObjectName(_fromUtf8("tab_2"))
+        self.gridLayout_3 = QtGui.QGridLayout(self.tab_2)
+        self.gridLayout_3.setObjectName(_fromUtf8("gridLayout_3"))
+        self.verticalLayout_4 = QtGui.QVBoxLayout()
+        self.verticalLayout_4.setObjectName(_fromUtf8("verticalLayout_4"))
+        self.horizontalLayout_10 = QtGui.QHBoxLayout()
+        self.horizontalLayout_10.setObjectName(_fromUtf8("horizontalLayout_10"))
+        self.label_instrument = QtGui.QLabel(self.tab_2)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.label_instrument.sizePolicy().hasHeightForWidth())
+        self.label_instrument.setSizePolicy(sizePolicy)
+        self.label_instrument.setMinimumSize(QtCore.QSize(155, 0))
+        self.label_instrument.setObjectName(_fromUtf8("label_instrument"))
+        self.horizontalLayout_10.addWidget(self.label_instrument)
+        self.comboBox_instrument = QtGui.QComboBox(self.tab_2)
+        self.comboBox_instrument.setObjectName(_fromUtf8("comboBox_instrument"))
+        self.comboBox_instrument.addItem(_fromUtf8(""))
+        self.horizontalLayout_10.addWidget(self.comboBox_instrument)
+        spacerItem33 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Minimum)
+        self.horizontalLayout_10.addItem(spacerItem33)
+        self.verticalLayout_4.addLayout(self.horizontalLayout_10)
+        spacerItem34 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Preferred)
+        self.verticalLayout_4.addItem(spacerItem34)
+        self.horizontalLayout_7 = QtGui.QHBoxLayout()
+        self.horizontalLayout_7.setObjectName(_fromUtf8("horizontalLayout_7"))
+        self.label_cache = QtGui.QLabel(self.tab_2)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.label_cache.sizePolicy().hasHeightForWidth())
+        self.label_cache.setSizePolicy(sizePolicy)
+        self.label_cache.setMinimumSize(QtCore.QSize(155, 0))
+        self.label_cache.setObjectName(_fromUtf8("label_cache"))
+        self.horizontalLayout_7.addWidget(self.label_cache)
+        self.lineEdit_cache = QtGui.QLineEdit(self.tab_2)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.lineEdit_cache.sizePolicy().hasHeightForWidth())
+        self.lineEdit_cache.setSizePolicy(sizePolicy)
+        self.lineEdit_cache.setMinimumSize(QtCore.QSize(400, 0))
+        self.lineEdit_cache.setObjectName(_fromUtf8("lineEdit_cache"))
+        self.horizontalLayout_7.addWidget(self.lineEdit_cache)
+        self.pushButton_browseCache = QtGui.QPushButton(self.tab_2)
+        self.pushButton_browseCache.setObjectName(_fromUtf8("pushButton_browseCache"))
+        self.horizontalLayout_7.addWidget(self.pushButton_browseCache)
+        self.checkBox_delCache = QtGui.QCheckBox(self.tab_2)
+        self.checkBox_delCache.setObjectName(_fromUtf8("checkBox_delCache"))
+        self.horizontalLayout_7.addWidget(self.checkBox_delCache)
+        spacerItem35 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
+        self.horizontalLayout_7.addItem(spacerItem35)
+        self.verticalLayout_4.addLayout(self.horizontalLayout_7)
+        self.horizontalLayout_8 = QtGui.QHBoxLayout()
+        self.horizontalLayout_8.setObjectName(_fromUtf8("horizontalLayout_8"))
+        self.radioButton_useServer = QtGui.QRadioButton(self.tab_2)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.radioButton_useServer.sizePolicy().hasHeightForWidth())
+        self.radioButton_useServer.setSizePolicy(sizePolicy)
+        self.radioButton_useServer.setMinimumSize(QtCore.QSize(20, 0))
+        self.radioButton_useServer.setText(_fromUtf8(""))
+        self.radioButton_useServer.setObjectName(_fromUtf8("radioButton_useServer"))
+        self.horizontalLayout_8.addWidget(self.radioButton_useServer)
+        self.label = QtGui.QLabel(self.tab_2)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
+        self.label.setSizePolicy(sizePolicy)
+        self.label.setMinimumSize(QtCore.QSize(135, 0))
+        self.label.setObjectName(_fromUtf8("label"))
+        self.horizontalLayout_8.addWidget(self.label)
+        self.lineEdit_dataIP = QtGui.QLineEdit(self.tab_2)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.lineEdit_dataIP.sizePolicy().hasHeightForWidth())
+        self.lineEdit_dataIP.setSizePolicy(sizePolicy)
+        self.lineEdit_dataIP.setMinimumSize(QtCore.QSize(400, 0))
+        self.lineEdit_dataIP.setObjectName(_fromUtf8("lineEdit_dataIP"))
+        self.horizontalLayout_8.addWidget(self.lineEdit_dataIP)
+        self.pushButton_chkServer = QtGui.QPushButton(self.tab_2)
+        self.pushButton_chkServer.setObjectName(_fromUtf8("pushButton_chkServer"))
+        self.horizontalLayout_8.addWidget(self.pushButton_chkServer)
+        spacerItem36 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
+        self.horizontalLayout_8.addItem(spacerItem36)
+        self.verticalLayout_4.addLayout(self.horizontalLayout_8)
+        self.horizontalLayout_9 = QtGui.QHBoxLayout()
+        self.horizontalLayout_9.setObjectName(_fromUtf8("horizontalLayout_9"))
+        self.radioButton_useLocal = QtGui.QRadioButton(self.tab_2)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.radioButton_useLocal.sizePolicy().hasHeightForWidth())
+        self.radioButton_useLocal.setSizePolicy(sizePolicy)
+        self.radioButton_useLocal.setMinimumSize(QtCore.QSize(20, 0))
+        self.radioButton_useLocal.setText(_fromUtf8(""))
+        self.radioButton_useLocal.setObjectName(_fromUtf8("radioButton_useLocal"))
+        self.horizontalLayout_9.addWidget(self.radioButton_useLocal)
+        self.label_localSrc = QtGui.QLabel(self.tab_2)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.label_localSrc.sizePolicy().hasHeightForWidth())
+        self.label_localSrc.setSizePolicy(sizePolicy)
+        self.label_localSrc.setMinimumSize(QtCore.QSize(135, 0))
+        self.label_localSrc.setObjectName(_fromUtf8("label_localSrc"))
+        self.horizontalLayout_9.addWidget(self.label_localSrc)
+        self.lineEdit_localSrc = QtGui.QLineEdit(self.tab_2)
+        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
+        sizePolicy.setHorizontalStretch(0)
+        sizePolicy.setVerticalStretch(0)
+        sizePolicy.setHeightForWidth(self.lineEdit_localSrc.sizePolicy().hasHeightForWidth())
+        self.lineEdit_localSrc.setSizePolicy(sizePolicy)
+        self.lineEdit_localSrc.setMinimumSize(QtCore.QSize(400, 0))
+        self.lineEdit_localSrc.setObjectName(_fromUtf8("lineEdit_localSrc"))
+        self.horizontalLayout_9.addWidget(self.lineEdit_localSrc)
+        self.pushButton_browseLocalSrc = QtGui.QPushButton(self.tab_2)
+        self.pushButton_browseLocalSrc.setObjectName(_fromUtf8("pushButton_browseLocalSrc"))
+        self.horizontalLayout_9.addWidget(self.pushButton_browseLocalSrc)
+        spacerItem37 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
+        self.horizontalLayout_9.addItem(spacerItem37)
+        self.verticalLayout_4.addLayout(self.horizontalLayout_9)
+        self.horizontalLayout_4 = QtGui.QHBoxLayout()
+        self.horizontalLayout_4.setObjectName(_fromUtf8("horizontalLayout_4"))
+        self.verticalLayout_4.addLayout(self.horizontalLayout_4)
+        self.gridLayout_3.addLayout(self.verticalLayout_4, 0, 0, 1, 1)
+        spacerItem38 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
+        self.gridLayout_3.addItem(spacerItem38, 1, 0, 1, 1)
+        self.tabWidget.addTab(self.tab_2, _fromUtf8(""))
+        self.horizontalLayout_2.addWidget(self.tabWidget)
+        self.verticalLayout.addLayout(self.horizontalLayout_2)
+        self.gridLayout.addLayout(self.verticalLayout, 0, 0, 1, 1)
+        MainWindow.setCentralWidget(self.centralwidget)
+        self.menubar = QtGui.QMenuBar(MainWindow)
+        self.menubar.setGeometry(QtCore.QRect(0, 0, 1412, 25))
+        self.menubar.setObjectName(_fromUtf8("menubar"))
+        self.menuFile = QtGui.QMenu(self.menubar)
+        self.menuFile.setObjectName(_fromUtf8("menuFile"))
+        self.menuHelp = QtGui.QMenu(self.menubar)
+        self.menuHelp.setObjectName(_fromUtf8("menuHelp"))
+        MainWindow.setMenuBar(self.menubar)
+        self.statusbar = QtGui.QStatusBar(MainWindow)
+        self.statusbar.setObjectName(_fromUtf8("statusbar"))
+        MainWindow.setStatusBar(self.statusbar)
+        self.actionQuit = QtGui.QAction(MainWindow)
+        self.actionQuit.setObjectName(_fromUtf8("actionQuit"))
+        self.actionLog = QtGui.QAction(MainWindow)
+        self.actionLog.setObjectName(_fromUtf8("actionLog"))
+        self.actionNew = QtGui.QAction(MainWindow)
+        self.actionNew.setObjectName(_fromUtf8("actionNew"))
+        self.actionOpen = QtGui.QAction(MainWindow)
+        self.actionOpen.setObjectName(_fromUtf8("actionOpen"))
+        self.actionOpen_2 = QtGui.QAction(MainWindow)
+        self.actionOpen_2.setObjectName(_fromUtf8("actionOpen_2"))
+        self.actionLoad_Setup_File = QtGui.QAction(MainWindow)
+        self.actionLoad_Setup_File.setObjectName(_fromUtf8("actionLoad_Setup_File"))
+        self.actionFind_Help = QtGui.QAction(MainWindow)
+        self.actionFind_Help.setObjectName(_fromUtf8("actionFind_Help"))
+        self.menuFile.addAction(self.actionNew)
+        self.menuFile.addAction(self.actionOpen_2)
+        self.menuFile.addSeparator()
+        self.menuFile.addAction(self.actionQuit)
+        self.menuHelp.addAction(self.actionFind_Help)
+        self.menubar.addAction(self.menuFile.menuAction())
+        self.menubar.addAction(self.menuHelp.menuAction())
+
+        self.retranslateUi(MainWindow)
+        self.tabWidget.setCurrentIndex(2)
+        QtCore.QMetaObject.connectSlotsByName(MainWindow)
+
+    def retranslateUi(self, MainWindow):
+        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
+        self.label_expNo.setText(_translate("MainWindow", "Exp No", None))
+        self.label_scanNo.setText(_translate("MainWindow", "Scan No", None))
+        self.pushButton_loadData.setToolTip(_translate("MainWindow", "<html><head/><body><p>For tab \'Raw Detectors\',  \'Individual Detector\', \'Normalized\' and \'Vanadium\', load SPICE data  to MDEventWorkspaces.  </p><p><br/></p><p>If the vanadium correction file and excluded detectors files are found, then these files will be parsed and set up.  </p><p><br/></p><p>Wavelength will be set according to sample log.  If failed, then it will be set to unknown. </p><p><br/></p><p>For tab \'Normalized\' and \'Vanadium\', there will be NO conversion to single spectrum powder diffraction data with this button. </p></body></html>", None))
+        self.pushButton_loadData.setText(_translate("MainWindow", "Load Data", None))
+        self.label_wavelength.setText(_translate("MainWindow", "Wavelength", None))
+        self.comboBox_wavelength.setItemText(0, _translate("MainWindow", "2.41 Ã… (Ge 113 IN)", None))
+        self.comboBox_wavelength.setItemText(1, _translate("MainWindow", "1.54 Ã… (115) ", None))
+        self.comboBox_wavelength.setItemText(2, _translate("MainWindow", "1.12 Ã… (117) ", None))
+        self.comboBox_wavelength.setItemText(3, _translate("MainWindow", "User Specified", None))
+        self.checkBox_useDetEffCorr.setText(_translate("MainWindow", "Detectors Efficiency Correction", None))
+        self.label_detEffFileName.setToolTip(_translate("MainWindow", "<html><head/><body><p>Vanadium correction file</p></body></html>", None))
+        self.label_detEffFileName.setText(_translate("MainWindow", "Detectors Efficiency File", None))
+        self.pushButton_browseVCorrFile.setText(_translate("MainWindow", "Browse", None))
+        self.pushButton_viewVCorrection.setText(_translate("MainWindow", "View Correction", None))
+        self.comboBox_effCorrect.setToolTip(_translate("MainWindow", "<html><head/><body><p>File name for efficiency correction</p></body></html>", None))
+        self.checkBox_useDetExcludeFile.setText(_translate("MainWindow", "Using Exclusion File", None))
+        self.label_excFileName.setText(_translate("MainWindow", "Excluded  Detectors File", None))
+        self.pushButton_browseExcludedDetFile.setText(_translate("MainWindow", "Browse", None))
+        self.label_detExcluded.setText(_translate("MainWindow", "Detectors to Exclude   ", None))
+        self.tabWidget.setToolTip(_translate("MainWindow", "<html><head/><body><p><br/></p></body></html>", None))
+        self.comboBox_rawDetMode.setItemText(0, _translate("MainWindow", "Single Pts.", None))
+        self.label_ptInfo.setText(_translate("MainWindow", "Pt. Number From 1 To Maximum Pt.", None))
+        self.pushButton_plotRaw.setText(_translate("MainWindow", "Plot Raw Detector", None))
+        self.checkBox_overpltRawDet.setText(_translate("MainWindow", "Over Plot Previous", None))
+        self.pushButton_ptUp.setText(_translate("MainWindow", "Previous Pt.", None))
+        self.pushButton_ptDown.setText(_translate("MainWindow", "Next Pt.", None))
+        self.pushButton_clearRawDets.setText(_translate("MainWindow", "Clear", None))
+        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate("MainWindow", "Raw Detectors", None))
+        self.label_11.setText(_translate("MainWindow", "Detector ID", None))
+        self.label_17.setText(_translate("MainWindow", "Detector IDs From 1 to 44", None))
+        self.pushButton_plotIndvDet.setText(_translate("MainWindow", "Plot", None))
+        self.checkBox_overPlotIndvDet.setText(_translate("MainWindow", "Over Plot Previous", None))
+        self.pushButton_plotAllDet.setText(_translate("MainWindow", "Plot All ", None))
+        self.pushButton_plotPrevDet.setText(_translate("MainWindow", "Previous Detector", None))
+        self.pushButton_plotNextDet.setText(_translate("MainWindow", "Next Detector", None))
+        self.pushButton_clearCanvasIndDet.setText(_translate("MainWindow", "Clear", None))
+        self.pushButton_plotLog.setText(_translate("MainWindow", "Plot Sample Log", None))
+        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_5), _translate("MainWindow", "Individual Detector", None))
+        self.label_normalizeMonitor.setText(_translate("MainWindow", "Normalization Monitor", None))
+        self.label_outputFormat.setText(_translate("MainWindow", "Save As", None))
+        self.pushButton_saveData.setText(_translate("MainWindow", "Save", None))
+        self.label_18.setText(_translate("MainWindow", "Binning To Unit", None))
+        self.pushButton_unit2theta.setText(_translate("MainWindow", "2theta", None))
+        self.pushButton_unitD.setText(_translate("MainWindow", "dSpacing", None))
+        self.pushButton_unitQ.setText(_translate("MainWindow", "Q", None))
+        self.label_19.setText(_translate("MainWindow", "Binning Parameters", None))
+        self.label_xmin.setText(_translate("MainWindow", "Min X", None))
+        self.label_xmax_2.setText(_translate("MainWindow", "Max X", None))
+        self.label_binsize.setText(_translate("MainWindow", "Bin Size", None))
+        self.pushButton_nextScan.setText(_translate("MainWindow", "Next Scan", None))
+        self.pushButton_prevScan.setText(_translate("MainWindow", "Prev Scan", None))
+        self.checkBox_clearPrevious.setText(_translate("MainWindow", "Keep Previous Plot", None))
+        self.pushButton_clearTab2Canvas.setToolTip(_translate("MainWindow", "<html><head/><body><p>Clear canvas</p></body></html>", None))
+        self.pushButton_clearTab2Canvas.setText(_translate("MainWindow", "Clear", None))
+        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Normalized", None))
+        self.label_8.setToolTip(_translate("MainWindow", "<html><head/><body><p>Starting scan number</p></body></html>", None))
+        self.label_8.setText(_translate("MainWindow", "From", None))
+        self.label_9.setToolTip(_translate("MainWindow", "<html><head/><body><p>Last scan number included </p></body></html>", None))
+        self.label_9.setText(_translate("MainWindow", "To", None))
+        self.label_12.setText(_translate("MainWindow", "Others", None))
+        self.label_10.setToolTip(_translate("MainWindow", "<html><head/><body><p>Scan numbers that are excluded from merging beween \'from\' and \'to\'</p></body></html>", None))
+        self.label_10.setText(_translate("MainWindow", "Excluded Scans", None))
+        self.pushButton_loadMultData.setText(_translate("MainWindow", "Load All", None))
+        self.label_15.setText(_translate("MainWindow", "Miminum X", None))
+        self.label_14.setText(_translate("MainWindow", "Maximum X", None))
+        self.label_16.setText(_translate("MainWindow", "Bin Size", None))
+        self.comboBox_mscanUnit.setItemText(0, _translate("MainWindow", "2Theta", None))
+        self.pushButton_mscanBin.setText(_translate("MainWindow", "Bin Data", None))
+        self.label_mergeMessage.setText(_translate("MainWindow", "Message", None))
+        self.pushButton_viewMScan1D.setText(_translate("MainWindow", "View 1D", None))
+        self.pushButton_view2D.setText(_translate("MainWindow", "View 2D", None))
+        self.pushButton_saveAllIndScans.setText(_translate("MainWindow", "Save All", None))
+        self.pushButton_mergeScans.setText(_translate("MainWindow", "Merge", None))
+        self.pushButton_viewMerge.setText(_translate("MainWindow", "View Merged", None))
+        self.pushButton_saveMerge.setText(_translate("MainWindow", "Save Merged", None))
+        self.pushButton_clearMultCanvas.setText(_translate("MainWindow", "Clear", None))
+        self.label_13.setText(_translate("MainWindow", "Vertical Label In 2D Plot", None))
+        self.label_7.setText(_translate("MainWindow", "Message", None))
+        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_merge), _translate("MainWindow", "Multiple Scans", None))
+        self.label_2.setText(_translate("MainWindow", "Vanadium Peak List", None))
+        self.pushButton_resetVanPeakList.setText(_translate("MainWindow", "Reset Vanadium Peaks List", None))
+        self.label_3.setText(_translate("MainWindow", "Min 2Theta (Degrees)", None))
+        self.label_4.setText(_translate("MainWindow", "Max 2Theta (Degrees)", None))
+        self.label_5.setText(_translate("MainWindow", "Bin size  (Degrees)", None))
+        self.pushButton_rebin2Theta.setText(_translate("MainWindow", "Bin Vanadium", None))
+        self.pushButton_stripVanPeaks.setText(_translate("MainWindow", "Strip Vanadium Peaks", None))
+        self.pushButton_smoothVanData.setText(_translate("MainWindow", "Smooth Vanadium", None))
+        self.label_20.setText(_translate("MainWindow", "Smooth Parameters", None))
+        self.pushButton_applySmooth.setText(_translate("MainWindow", "Apply Smooth", None))
+        self.pushButton_undoSmooth.setText(_translate("MainWindow", "Undo Smooth", None))
+        self.pushButton_saveVanRun.setToolTip(_translate("MainWindow", "<html><head/><body><p>Save vanadium data for normalization. </p><p>If \'Apply Smooth\' is pushed, then the smoothed data will be saved. </p></body></html>", None))
+        self.pushButton_saveVanRun.setText(_translate("MainWindow", "Save", None))
+        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_4), _translate("MainWindow", "Vanadium", None))
+        self.label_instrument.setText(_translate("MainWindow", "Instrument", None))
+        self.comboBox_instrument.setItemText(0, _translate("MainWindow", "HB2A", None))
+        self.label_cache.setToolTip(_translate("MainWindow", "<html><head/><body><p>Cache data file download from server to local disk. </p><p>The default is current working directory.  </p><p>The cached files will be deleted with normal quit. </p></body></html>", None))
+        self.label_cache.setText(_translate("MainWindow", "Cache Raw Data File", None))
+        self.pushButton_browseCache.setText(_translate("MainWindow", "Browse", None))
+        self.checkBox_delCache.setToolTip(_translate("MainWindow", "<html><head/><body><p>Cached files will be deleted upon quitting normally.</p></body></html>", None))
+        self.checkBox_delCache.setText(_translate("MainWindow", "Delete Cache Before Quit", None))
+        self.label.setText(_translate("MainWindow", "Server    Address", None))
+        self.pushButton_chkServer.setText(_translate("MainWindow", "Check URL", None))
+        self.label_localSrc.setText(_translate("MainWindow", "Local Data Storage", None))
+        self.pushButton_browseLocalSrc.setText(_translate("MainWindow", "Browse", None))
+        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Advanced Setup", None))
+        self.menuFile.setTitle(_translate("MainWindow", "File", None))
+        self.menuHelp.setTitle(_translate("MainWindow", "Help", None))
+        self.actionQuit.setText(_translate("MainWindow", "Quit", None))
+        self.actionQuit.setShortcut(_translate("MainWindow", "Ctrl+Q", None))
+        self.actionLog.setText(_translate("MainWindow", "Log", None))
+        self.actionLog.setShortcut(_translate("MainWindow", "Ctrl+L", None))
+        self.actionNew.setText(_translate("MainWindow", "New", None))
+        self.actionNew.setShortcut(_translate("MainWindow", "Ctrl+N", None))
+        self.actionOpen.setText(_translate("MainWindow", "Open", None))
+        self.actionOpen_2.setText(_translate("MainWindow", "Open", None))
+        self.actionOpen_2.setShortcut(_translate("MainWindow", "Ctrl+O", None))
+        self.actionLoad_Setup_File.setText(_translate("MainWindow", "Load Setup File", None))
+        self.actionFind_Help.setText(_translate("MainWindow", "Find Help", None))
+
diff --git a/Code/Mantid/scripts/HFIRPowderReduction/Ui_MainWindow.ui b/Code/Mantid/scripts/HFIRPowderReduction/Ui_MainWindow.ui
new file mode 100644
index 0000000000000000000000000000000000000000..84346fb974e7155c58d87fe1026086516ddca4ef
--- /dev/null
+++ b/Code/Mantid/scripts/HFIRPowderReduction/Ui_MainWindow.ui
@@ -0,0 +1,2145 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>MainWindow</class>
+ <widget class="QMainWindow" name="MainWindow">
+  <property name="geometry">
+   <rect>
+    <x>0</x>
+    <y>0</y>
+    <width>1412</width>
+    <height>1216</height>
+   </rect>
+  </property>
+  <property name="windowTitle">
+   <string>MainWindow</string>
+  </property>
+  <widget class="QWidget" name="centralwidget">
+   <layout class="QGridLayout" name="gridLayout">
+    <item row="0" column="0">
+     <layout class="QVBoxLayout" name="verticalLayout">
+      <item>
+       <layout class="QHBoxLayout" name="horizontalLayout">
+        <item>
+         <widget class="QLabel" name="label_expNo">
+          <property name="text">
+           <string>Exp No</string>
+          </property>
+         </widget>
+        </item>
+        <item>
+         <widget class="QLineEdit" name="lineEdit_expNo"/>
+        </item>
+        <item>
+         <widget class="QLabel" name="label_scanNo">
+          <property name="text">
+           <string>Scan No</string>
+          </property>
+         </widget>
+        </item>
+        <item>
+         <widget class="QLineEdit" name="lineEdit_scanNo"/>
+        </item>
+        <item>
+         <widget class="QPushButton" name="pushButton_loadData">
+          <property name="toolTip">
+           <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;For tab 'Raw Detectors',  'Individual Detector', 'Normalized' and 'Vanadium', load SPICE data  to MDEventWorkspaces.  &lt;/p&gt;&lt;p&gt;&lt;br/&gt;&lt;/p&gt;&lt;p&gt;If the vanadium correction file and excluded detectors files are found, then these files will be parsed and set up.  &lt;/p&gt;&lt;p&gt;&lt;br/&gt;&lt;/p&gt;&lt;p&gt;Wavelength will be set according to sample log.  If failed, then it will be set to unknown. &lt;/p&gt;&lt;p&gt;&lt;br/&gt;&lt;/p&gt;&lt;p&gt;For tab 'Normalized' and 'Vanadium', there will be NO conversion to single spectrum powder diffraction data with this button. &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+          </property>
+          <property name="text">
+           <string>Load Data</string>
+          </property>
+         </widget>
+        </item>
+        <item>
+         <widget class="QLabel" name="label_calibration">
+          <property name="text">
+           <string/>
+          </property>
+         </widget>
+        </item>
+        <item>
+         <widget class="QLabel" name="label_wavelength">
+          <property name="text">
+           <string>Wavelength</string>
+          </property>
+         </widget>
+        </item>
+        <item>
+         <widget class="QComboBox" name="comboBox_wavelength">
+          <item>
+           <property name="text">
+            <string>2.41 Ã… (Ge 113 IN)</string>
+           </property>
+          </item>
+          <item>
+           <property name="text">
+            <string>1.54 Ã… (115) </string>
+           </property>
+          </item>
+          <item>
+           <property name="text">
+            <string>1.12 Ã… (117) </string>
+           </property>
+          </item>
+          <item>
+           <property name="text">
+            <string>User Specified</string>
+           </property>
+          </item>
+         </widget>
+        </item>
+        <item>
+         <widget class="QLineEdit" name="lineEdit_wavelength"/>
+        </item>
+        <item>
+         <spacer name="horizontalSpacer">
+          <property name="orientation">
+           <enum>Qt::Horizontal</enum>
+          </property>
+          <property name="sizeHint" stdset="0">
+           <size>
+            <width>40</width>
+            <height>20</height>
+           </size>
+          </property>
+         </spacer>
+        </item>
+       </layout>
+      </item>
+      <item>
+       <layout class="QHBoxLayout" name="horizontalLayout_25">
+        <item>
+         <widget class="QCheckBox" name="checkBox_useDetEffCorr">
+          <property name="sizePolicy">
+           <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+            <horstretch>0</horstretch>
+            <verstretch>0</verstretch>
+           </sizepolicy>
+          </property>
+          <property name="minimumSize">
+           <size>
+            <width>250</width>
+            <height>0</height>
+           </size>
+          </property>
+          <property name="text">
+           <string>Detectors Efficiency Correction</string>
+          </property>
+         </widget>
+        </item>
+        <item>
+         <spacer name="horizontalSpacer_15">
+          <property name="orientation">
+           <enum>Qt::Horizontal</enum>
+          </property>
+          <property name="sizeType">
+           <enum>QSizePolicy::Minimum</enum>
+          </property>
+          <property name="sizeHint" stdset="0">
+           <size>
+            <width>40</width>
+            <height>20</height>
+           </size>
+          </property>
+         </spacer>
+        </item>
+        <item>
+         <widget class="QLabel" name="label_detEffFileName">
+          <property name="toolTip">
+           <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Vanadium correction file&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+          </property>
+          <property name="text">
+           <string>Detectors Efficiency File</string>
+          </property>
+         </widget>
+        </item>
+        <item>
+         <widget class="QLineEdit" name="lineEdit_vcorrFileName"/>
+        </item>
+        <item>
+         <widget class="QPushButton" name="pushButton_browseVCorrFile">
+          <property name="text">
+           <string>Browse</string>
+          </property>
+         </widget>
+        </item>
+        <item>
+         <widget class="QPushButton" name="pushButton_viewVCorrection">
+          <property name="text">
+           <string>View Correction</string>
+          </property>
+         </widget>
+        </item>
+        <item>
+         <widget class="QComboBox" name="comboBox_effCorrect">
+          <property name="sizePolicy">
+           <sizepolicy hsizetype="Expanding" vsizetype="Fixed">
+            <horstretch>0</horstretch>
+            <verstretch>0</verstretch>
+           </sizepolicy>
+          </property>
+          <property name="toolTip">
+           <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;File name for efficiency correction&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+          </property>
+         </widget>
+        </item>
+        <item>
+         <spacer name="horizontalSpacer_5">
+          <property name="orientation">
+           <enum>Qt::Horizontal</enum>
+          </property>
+          <property name="sizeType">
+           <enum>QSizePolicy::Expanding</enum>
+          </property>
+          <property name="sizeHint" stdset="0">
+           <size>
+            <width>40</width>
+            <height>20</height>
+           </size>
+          </property>
+         </spacer>
+        </item>
+       </layout>
+      </item>
+      <item>
+       <layout class="QHBoxLayout" name="horizontalLayout_24">
+        <item>
+         <widget class="QCheckBox" name="checkBox_useDetExcludeFile">
+          <property name="sizePolicy">
+           <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+            <horstretch>0</horstretch>
+            <verstretch>0</verstretch>
+           </sizepolicy>
+          </property>
+          <property name="minimumSize">
+           <size>
+            <width>250</width>
+            <height>0</height>
+           </size>
+          </property>
+          <property name="text">
+           <string>Using Exclusion File</string>
+          </property>
+         </widget>
+        </item>
+        <item>
+         <spacer name="horizontalSpacer_16">
+          <property name="orientation">
+           <enum>Qt::Horizontal</enum>
+          </property>
+          <property name="sizeType">
+           <enum>QSizePolicy::Preferred</enum>
+          </property>
+          <property name="sizeHint" stdset="0">
+           <size>
+            <width>40</width>
+            <height>20</height>
+           </size>
+          </property>
+         </spacer>
+        </item>
+        <item>
+         <widget class="QLabel" name="label_excFileName">
+          <property name="text">
+           <string>Excluded  Detectors File</string>
+          </property>
+         </widget>
+        </item>
+        <item>
+         <widget class="QLineEdit" name="lineEdit_excludedDetFileName"/>
+        </item>
+        <item>
+         <widget class="QPushButton" name="pushButton_browseExcludedDetFile">
+          <property name="text">
+           <string>Browse</string>
+          </property>
+         </widget>
+        </item>
+        <item>
+         <spacer name="horizontalSpacer_17">
+          <property name="orientation">
+           <enum>Qt::Horizontal</enum>
+          </property>
+          <property name="sizeType">
+           <enum>QSizePolicy::Preferred</enum>
+          </property>
+          <property name="sizeHint" stdset="0">
+           <size>
+            <width>40</width>
+            <height>20</height>
+           </size>
+          </property>
+         </spacer>
+        </item>
+        <item>
+         <widget class="QLabel" name="label_detExcluded">
+          <property name="sizePolicy">
+           <sizepolicy hsizetype="Fixed" vsizetype="Preferred">
+            <horstretch>0</horstretch>
+            <verstretch>0</verstretch>
+           </sizepolicy>
+          </property>
+          <property name="minimumSize">
+           <size>
+            <width>155</width>
+            <height>0</height>
+           </size>
+          </property>
+          <property name="text">
+           <string>Detectors to Exclude   </string>
+          </property>
+         </widget>
+        </item>
+        <item>
+         <widget class="QLineEdit" name="lineEdit_detExcluded">
+          <property name="sizePolicy">
+           <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+            <horstretch>0</horstretch>
+            <verstretch>0</verstretch>
+           </sizepolicy>
+          </property>
+          <property name="minimumSize">
+           <size>
+            <width>300</width>
+            <height>0</height>
+           </size>
+          </property>
+         </widget>
+        </item>
+        <item>
+         <spacer name="horizontalSpacer_11">
+          <property name="orientation">
+           <enum>Qt::Horizontal</enum>
+          </property>
+          <property name="sizeHint" stdset="0">
+           <size>
+            <width>40</width>
+            <height>20</height>
+           </size>
+          </property>
+         </spacer>
+        </item>
+       </layout>
+      </item>
+      <item>
+       <layout class="QHBoxLayout" name="horizontalLayout_2">
+        <item>
+         <widget class="QTabWidget" name="tabWidget">
+          <property name="sizePolicy">
+           <sizepolicy hsizetype="Expanding" vsizetype="Expanding">
+            <horstretch>0</horstretch>
+            <verstretch>0</verstretch>
+           </sizepolicy>
+          </property>
+          <property name="toolTip">
+           <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;br/&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+          </property>
+          <property name="currentIndex">
+           <number>2</number>
+          </property>
+          <widget class="QWidget" name="tab_3">
+           <attribute name="title">
+            <string>Raw Detectors</string>
+           </attribute>
+           <layout class="QGridLayout" name="gridLayout_4">
+            <item row="0" column="0">
+             <layout class="QVBoxLayout" name="verticalLayout_7">
+              <item>
+               <layout class="QHBoxLayout" name="horizontalLayout_13">
+                <item>
+                 <widget class="QComboBox" name="comboBox_rawDetMode">
+                  <item>
+                   <property name="text">
+                    <string>Single Pts.</string>
+                   </property>
+                  </item>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QLineEdit" name="lineEdit_ptNo">
+                  <property name="sizePolicy">
+                   <sizepolicy hsizetype="Preferred" vsizetype="Fixed">
+                    <horstretch>0</horstretch>
+                    <verstretch>0</verstretch>
+                   </sizepolicy>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QLabel" name="label_ptInfo">
+                  <property name="text">
+                   <string>Pt. Number From 1 To Maximum Pt.</string>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <spacer name="horizontalSpacer_10">
+                  <property name="orientation">
+                   <enum>Qt::Horizontal</enum>
+                  </property>
+                  <property name="sizeType">
+                   <enum>QSizePolicy::Preferred</enum>
+                  </property>
+                  <property name="sizeHint" stdset="0">
+                   <size>
+                    <width>40</width>
+                    <height>20</height>
+                   </size>
+                  </property>
+                 </spacer>
+                </item>
+               </layout>
+              </item>
+              <item>
+               <layout class="QHBoxLayout" name="horizontalLayout_14">
+                <item>
+                 <widget class="QGraphicsView" name="graphicsView_Raw">
+                  <property name="sizePolicy">
+                   <sizepolicy hsizetype="Expanding" vsizetype="Expanding">
+                    <horstretch>0</horstretch>
+                    <verstretch>0</verstretch>
+                   </sizepolicy>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <layout class="QVBoxLayout" name="verticalLayout_9">
+                  <item>
+                   <widget class="QPushButton" name="pushButton_plotRaw">
+                    <property name="text">
+                     <string>Plot Raw Detector</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <widget class="QCheckBox" name="checkBox_overpltRawDet">
+                    <property name="text">
+                     <string>Over Plot Previous</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <spacer name="verticalSpacer_5">
+                    <property name="orientation">
+                     <enum>Qt::Vertical</enum>
+                    </property>
+                    <property name="sizeType">
+                     <enum>QSizePolicy::Preferred</enum>
+                    </property>
+                    <property name="sizeHint" stdset="0">
+                     <size>
+                      <width>20</width>
+                      <height>40</height>
+                     </size>
+                    </property>
+                   </spacer>
+                  </item>
+                  <item>
+                   <widget class="QPushButton" name="pushButton_ptUp">
+                    <property name="text">
+                     <string>Previous Pt.</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <widget class="QPushButton" name="pushButton_ptDown">
+                    <property name="text">
+                     <string>Next Pt.</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <spacer name="verticalSpacer_4">
+                    <property name="orientation">
+                     <enum>Qt::Vertical</enum>
+                    </property>
+                    <property name="sizeType">
+                     <enum>QSizePolicy::Preferred</enum>
+                    </property>
+                    <property name="sizeHint" stdset="0">
+                     <size>
+                      <width>20</width>
+                      <height>40</height>
+                     </size>
+                    </property>
+                   </spacer>
+                  </item>
+                  <item>
+                   <widget class="QPushButton" name="pushButton_clearRawDets">
+                    <property name="text">
+                     <string>Clear</string>
+                    </property>
+                   </widget>
+                  </item>
+                 </layout>
+                </item>
+               </layout>
+              </item>
+              <item>
+               <layout class="QHBoxLayout" name="horizontalLayout_12">
+                <item>
+                 <widget class="QTextBrowser" name="textBrowser_RawDetInfo">
+                  <property name="sizePolicy">
+                   <sizepolicy hsizetype="Expanding" vsizetype="Preferred">
+                    <horstretch>0</horstretch>
+                    <verstretch>0</verstretch>
+                   </sizepolicy>
+                  </property>
+                 </widget>
+                </item>
+               </layout>
+              </item>
+             </layout>
+            </item>
+           </layout>
+          </widget>
+          <widget class="QWidget" name="tab_5">
+           <attribute name="title">
+            <string>Individual Detector</string>
+           </attribute>
+           <layout class="QGridLayout" name="gridLayout_7">
+            <item row="0" column="0">
+             <layout class="QVBoxLayout" name="verticalLayout_8">
+              <item>
+               <layout class="QHBoxLayout" name="horizontalLayout_21">
+                <item>
+                 <widget class="QLabel" name="label_11">
+                  <property name="text">
+                   <string>Detector ID</string>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QLineEdit" name="lineEdit_detID">
+                  <property name="sizePolicy">
+                   <sizepolicy hsizetype="Preferred" vsizetype="Fixed">
+                    <horstretch>0</horstretch>
+                    <verstretch>0</verstretch>
+                   </sizepolicy>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QLabel" name="label_17">
+                  <property name="text">
+                   <string>Detector IDs From 1 to 44</string>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <spacer name="horizontalSpacer_4">
+                  <property name="orientation">
+                   <enum>Qt::Horizontal</enum>
+                  </property>
+                  <property name="sizeHint" stdset="0">
+                   <size>
+                    <width>40</width>
+                    <height>20</height>
+                   </size>
+                  </property>
+                 </spacer>
+                </item>
+               </layout>
+              </item>
+              <item>
+               <layout class="QHBoxLayout" name="horizontalLayout_17">
+                <item>
+                 <layout class="QHBoxLayout" name="horizontalLayout_23">
+                  <item>
+                   <layout class="QVBoxLayout" name="verticalLayout_13">
+                    <item>
+                     <widget class="QGraphicsView" name="graphicsView_indvDet">
+                      <property name="sizePolicy">
+                       <sizepolicy hsizetype="Expanding" vsizetype="Expanding">
+                        <horstretch>0</horstretch>
+                        <verstretch>0</verstretch>
+                       </sizepolicy>
+                      </property>
+                     </widget>
+                    </item>
+                    <item>
+                     <widget class="QComboBox" name="comboBox_indvDetXLabel"/>
+                    </item>
+                   </layout>
+                  </item>
+                  <item>
+                   <layout class="QVBoxLayout" name="verticalLayout_12">
+                    <item>
+                     <widget class="QPushButton" name="pushButton_plotIndvDet">
+                      <property name="text">
+                       <string>Plot</string>
+                      </property>
+                     </widget>
+                    </item>
+                    <item>
+                     <widget class="QCheckBox" name="checkBox_overPlotIndvDet">
+                      <property name="text">
+                       <string>Over Plot Previous</string>
+                      </property>
+                     </widget>
+                    </item>
+                    <item>
+                     <spacer name="verticalSpacer_17">
+                      <property name="orientation">
+                       <enum>Qt::Vertical</enum>
+                      </property>
+                      <property name="sizeType">
+                       <enum>QSizePolicy::Minimum</enum>
+                      </property>
+                      <property name="sizeHint" stdset="0">
+                       <size>
+                        <width>20</width>
+                        <height>40</height>
+                       </size>
+                      </property>
+                     </spacer>
+                    </item>
+                    <item>
+                     <widget class="QPushButton" name="pushButton_plotAllDet">
+                      <property name="enabled">
+                       <bool>false</bool>
+                      </property>
+                      <property name="text">
+                       <string>Plot All </string>
+                      </property>
+                     </widget>
+                    </item>
+                    <item>
+                     <spacer name="verticalSpacer_14">
+                      <property name="orientation">
+                       <enum>Qt::Vertical</enum>
+                      </property>
+                      <property name="sizeType">
+                       <enum>QSizePolicy::Minimum</enum>
+                      </property>
+                      <property name="sizeHint" stdset="0">
+                       <size>
+                        <width>20</width>
+                        <height>40</height>
+                       </size>
+                      </property>
+                     </spacer>
+                    </item>
+                    <item>
+                     <widget class="QPushButton" name="pushButton_plotPrevDet">
+                      <property name="text">
+                       <string>Previous Detector</string>
+                      </property>
+                     </widget>
+                    </item>
+                    <item>
+                     <widget class="QPushButton" name="pushButton_plotNextDet">
+                      <property name="text">
+                       <string>Next Detector</string>
+                      </property>
+                     </widget>
+                    </item>
+                    <item>
+                     <spacer name="verticalSpacer_18">
+                      <property name="orientation">
+                       <enum>Qt::Vertical</enum>
+                      </property>
+                      <property name="sizeHint" stdset="0">
+                       <size>
+                        <width>20</width>
+                        <height>40</height>
+                       </size>
+                      </property>
+                     </spacer>
+                    </item>
+                    <item>
+                     <widget class="QPushButton" name="pushButton_clearCanvasIndDet">
+                      <property name="text">
+                       <string>Clear</string>
+                      </property>
+                     </widget>
+                    </item>
+                    <item>
+                     <spacer name="verticalSpacer_15">
+                      <property name="orientation">
+                       <enum>Qt::Vertical</enum>
+                      </property>
+                      <property name="sizeHint" stdset="0">
+                       <size>
+                        <width>20</width>
+                        <height>40</height>
+                       </size>
+                      </property>
+                     </spacer>
+                    </item>
+                    <item>
+                     <widget class="QComboBox" name="comboBox_indvDetYLabel"/>
+                    </item>
+                    <item>
+                     <widget class="QPushButton" name="pushButton_plotLog">
+                      <property name="text">
+                       <string>Plot Sample Log</string>
+                      </property>
+                     </widget>
+                    </item>
+                    <item>
+                     <spacer name="verticalSpacer_16">
+                      <property name="orientation">
+                       <enum>Qt::Vertical</enum>
+                      </property>
+                      <property name="sizeHint" stdset="0">
+                       <size>
+                        <width>20</width>
+                        <height>40</height>
+                       </size>
+                      </property>
+                     </spacer>
+                    </item>
+                   </layout>
+                  </item>
+                 </layout>
+                </item>
+               </layout>
+              </item>
+             </layout>
+            </item>
+           </layout>
+          </widget>
+          <widget class="QWidget" name="tab">
+           <attribute name="title">
+            <string>Normalized</string>
+           </attribute>
+           <layout class="QGridLayout" name="gridLayout_2">
+            <item row="0" column="0">
+             <layout class="QVBoxLayout" name="verticalLayout_2">
+              <item>
+               <layout class="QHBoxLayout" name="horizontalLayout_3">
+                <item>
+                 <widget class="QLabel" name="label_normalizeMonitor">
+                  <property name="sizePolicy">
+                   <sizepolicy hsizetype="Fixed" vsizetype="Preferred">
+                    <horstretch>0</horstretch>
+                    <verstretch>0</verstretch>
+                   </sizepolicy>
+                  </property>
+                  <property name="minimumSize">
+                   <size>
+                    <width>155</width>
+                    <height>0</height>
+                   </size>
+                  </property>
+                  <property name="text">
+                   <string>Normalization Monitor</string>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QLineEdit" name="lineEdit_normalizeMonitor">
+                  <property name="sizePolicy">
+                   <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+                    <horstretch>0</horstretch>
+                    <verstretch>0</verstretch>
+                   </sizepolicy>
+                  </property>
+                  <property name="minimumSize">
+                   <size>
+                    <width>300</width>
+                    <height>0</height>
+                   </size>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <spacer name="horizontalSpacer_2">
+                  <property name="orientation">
+                   <enum>Qt::Horizontal</enum>
+                  </property>
+                  <property name="sizeType">
+                   <enum>QSizePolicy::Expanding</enum>
+                  </property>
+                  <property name="sizeHint" stdset="0">
+                   <size>
+                    <width>40</width>
+                    <height>20</height>
+                   </size>
+                  </property>
+                 </spacer>
+                </item>
+               </layout>
+              </item>
+              <item>
+               <layout class="QHBoxLayout" name="horizontalLayout_22">
+                <item>
+                 <widget class="QLabel" name="label_outputFormat">
+                  <property name="text">
+                   <string>Save As</string>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QComboBox" name="comboBox_outputFormat">
+                  <property name="sizePolicy">
+                   <sizepolicy hsizetype="Expanding" vsizetype="Fixed">
+                    <horstretch>0</horstretch>
+                    <verstretch>0</verstretch>
+                   </sizepolicy>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QLineEdit" name="lineEdit_outputFileName"/>
+                </item>
+                <item>
+                 <widget class="QPushButton" name="pushButton_saveData">
+                  <property name="text">
+                   <string>Save</string>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <spacer name="horizontalSpacer_14">
+                  <property name="orientation">
+                   <enum>Qt::Horizontal</enum>
+                  </property>
+                  <property name="sizeHint" stdset="0">
+                   <size>
+                    <width>40</width>
+                    <height>20</height>
+                   </size>
+                  </property>
+                 </spacer>
+                </item>
+               </layout>
+              </item>
+              <item>
+               <layout class="QHBoxLayout" name="horizontalLayout_5">
+                <item>
+                 <layout class="QGridLayout" name="gridLayout_reductionView">
+                  <item row="0" column="0">
+                   <widget class="QGraphicsView" name="graphicsView_reducedData">
+                    <property name="sizePolicy">
+                     <sizepolicy hsizetype="Expanding" vsizetype="Expanding">
+                      <horstretch>0</horstretch>
+                      <verstretch>0</verstretch>
+                     </sizepolicy>
+                    </property>
+                   </widget>
+                  </item>
+                 </layout>
+                </item>
+                <item>
+                 <layout class="QVBoxLayout" name="verticalLayout_3">
+                  <item>
+                   <layout class="QHBoxLayout" name="horizontalLayout_6">
+                    <item>
+                     <widget class="QLabel" name="label_18">
+                      <property name="sizePolicy">
+                       <sizepolicy hsizetype="Fixed" vsizetype="Preferred">
+                        <horstretch>0</horstretch>
+                        <verstretch>0</verstretch>
+                       </sizepolicy>
+                      </property>
+                      <property name="text">
+                       <string>Binning To Unit</string>
+                      </property>
+                     </widget>
+                    </item>
+                   </layout>
+                  </item>
+                  <item>
+                   <widget class="QPushButton" name="pushButton_unit2theta">
+                    <property name="text">
+                     <string>2theta</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <widget class="QPushButton" name="pushButton_unitD">
+                    <property name="text">
+                     <string>dSpacing</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <widget class="QPushButton" name="pushButton_unitQ">
+                    <property name="text">
+                     <string>Q</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <spacer name="verticalSpacer_6">
+                    <property name="orientation">
+                     <enum>Qt::Vertical</enum>
+                    </property>
+                    <property name="sizeType">
+                     <enum>QSizePolicy::Preferred</enum>
+                    </property>
+                    <property name="sizeHint" stdset="0">
+                     <size>
+                      <width>20</width>
+                      <height>40</height>
+                     </size>
+                    </property>
+                   </spacer>
+                  </item>
+                  <item>
+                   <layout class="QHBoxLayout" name="horizontalLayout_27">
+                    <item>
+                     <widget class="QLabel" name="label_19">
+                      <property name="sizePolicy">
+                       <sizepolicy hsizetype="Fixed" vsizetype="Preferred">
+                        <horstretch>0</horstretch>
+                        <verstretch>0</verstretch>
+                       </sizepolicy>
+                      </property>
+                      <property name="text">
+                       <string>Binning Parameters</string>
+                      </property>
+                     </widget>
+                    </item>
+                   </layout>
+                  </item>
+                  <item>
+                   <layout class="QHBoxLayout" name="horizontalLayout_26">
+                    <item>
+                     <widget class="QLabel" name="label_xmin">
+                      <property name="sizePolicy">
+                       <sizepolicy hsizetype="Preferred" vsizetype="Fixed">
+                        <horstretch>0</horstretch>
+                        <verstretch>0</verstretch>
+                       </sizepolicy>
+                      </property>
+                      <property name="text">
+                       <string>Min X</string>
+                      </property>
+                     </widget>
+                    </item>
+                    <item>
+                     <widget class="QLineEdit" name="lineEdit_xmin">
+                      <property name="enabled">
+                       <bool>true</bool>
+                      </property>
+                      <property name="sizePolicy">
+                       <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
+                        <horstretch>0</horstretch>
+                        <verstretch>0</verstretch>
+                       </sizepolicy>
+                      </property>
+                      <property name="minimumSize">
+                       <size>
+                        <width>10</width>
+                        <height>0</height>
+                       </size>
+                      </property>
+                     </widget>
+                    </item>
+                   </layout>
+                  </item>
+                  <item>
+                   <layout class="QHBoxLayout" name="horizontalLayout_28">
+                    <item>
+                     <widget class="QLabel" name="label_xmax_2">
+                      <property name="sizePolicy">
+                       <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
+                        <horstretch>0</horstretch>
+                        <verstretch>0</verstretch>
+                       </sizepolicy>
+                      </property>
+                      <property name="text">
+                       <string>Max X</string>
+                      </property>
+                     </widget>
+                    </item>
+                    <item>
+                     <widget class="QLineEdit" name="lineEdit_xmax">
+                      <property name="sizePolicy">
+                       <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
+                        <horstretch>0</horstretch>
+                        <verstretch>0</verstretch>
+                       </sizepolicy>
+                      </property>
+                      <property name="minimumSize">
+                       <size>
+                        <width>10</width>
+                        <height>0</height>
+                       </size>
+                      </property>
+                     </widget>
+                    </item>
+                   </layout>
+                  </item>
+                  <item>
+                   <layout class="QHBoxLayout" name="horizontalLayout_29">
+                    <item>
+                     <widget class="QLabel" name="label_binsize">
+                      <property name="sizePolicy">
+                       <sizepolicy hsizetype="Preferred" vsizetype="Fixed">
+                        <horstretch>0</horstretch>
+                        <verstretch>0</verstretch>
+                       </sizepolicy>
+                      </property>
+                      <property name="text">
+                       <string>Bin Size</string>
+                      </property>
+                     </widget>
+                    </item>
+                    <item>
+                     <widget class="QLineEdit" name="lineEdit_binsize">
+                      <property name="sizePolicy">
+                       <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
+                        <horstretch>0</horstretch>
+                        <verstretch>0</verstretch>
+                       </sizepolicy>
+                      </property>
+                      <property name="minimumSize">
+                       <size>
+                        <width>10</width>
+                        <height>0</height>
+                       </size>
+                      </property>
+                     </widget>
+                    </item>
+                   </layout>
+                  </item>
+                  <item>
+                   <spacer name="verticalSpacer">
+                    <property name="orientation">
+                     <enum>Qt::Vertical</enum>
+                    </property>
+                    <property name="sizeType">
+                     <enum>QSizePolicy::Preferred</enum>
+                    </property>
+                    <property name="sizeHint" stdset="0">
+                     <size>
+                      <width>20</width>
+                      <height>40</height>
+                     </size>
+                    </property>
+                   </spacer>
+                  </item>
+                  <item>
+                   <widget class="QPushButton" name="pushButton_nextScan">
+                    <property name="text">
+                     <string>Next Scan</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <widget class="QPushButton" name="pushButton_prevScan">
+                    <property name="text">
+                     <string>Prev Scan</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <widget class="QCheckBox" name="checkBox_clearPrevious">
+                    <property name="text">
+                     <string>Keep Previous Plot</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <spacer name="verticalSpacer_20">
+                    <property name="orientation">
+                     <enum>Qt::Vertical</enum>
+                    </property>
+                    <property name="sizeType">
+                     <enum>QSizePolicy::Preferred</enum>
+                    </property>
+                    <property name="sizeHint" stdset="0">
+                     <size>
+                      <width>20</width>
+                      <height>40</height>
+                     </size>
+                    </property>
+                   </spacer>
+                  </item>
+                  <item>
+                   <widget class="QPushButton" name="pushButton_clearTab2Canvas">
+                    <property name="toolTip">
+                     <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Clear canvas&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+                    </property>
+                    <property name="text">
+                     <string>Clear</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <spacer name="verticalSpacer_3">
+                    <property name="orientation">
+                     <enum>Qt::Vertical</enum>
+                    </property>
+                    <property name="sizeType">
+                     <enum>QSizePolicy::Expanding</enum>
+                    </property>
+                    <property name="sizeHint" stdset="0">
+                     <size>
+                      <width>20</width>
+                      <height>40</height>
+                     </size>
+                    </property>
+                   </spacer>
+                  </item>
+                 </layout>
+                </item>
+               </layout>
+              </item>
+             </layout>
+            </item>
+           </layout>
+          </widget>
+          <widget class="QWidget" name="tab_merge">
+           <attribute name="title">
+            <string>Multiple Scans</string>
+           </attribute>
+           <layout class="QGridLayout" name="gridLayout_6">
+            <item row="0" column="0">
+             <layout class="QVBoxLayout" name="verticalLayout_merge">
+              <item>
+               <layout class="QHBoxLayout" name="horizontalLayout_19">
+                <item>
+                 <widget class="QLabel" name="label_8">
+                  <property name="toolTip">
+                   <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Starting scan number&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+                  </property>
+                  <property name="text">
+                   <string>From</string>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QLineEdit" name="lineEdit_scanStart">
+                  <property name="sizePolicy">
+                   <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+                    <horstretch>0</horstretch>
+                    <verstretch>0</verstretch>
+                   </sizepolicy>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QLabel" name="label_9">
+                  <property name="toolTip">
+                   <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Last scan number included &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+                  </property>
+                  <property name="text">
+                   <string>To</string>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QLineEdit" name="lineEdit_scanEnd">
+                  <property name="sizePolicy">
+                   <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+                    <horstretch>0</horstretch>
+                    <verstretch>0</verstretch>
+                   </sizepolicy>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QLabel" name="label_12">
+                  <property name="text">
+                   <string>Others</string>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QLineEdit" name="lineEdit_extraScans"/>
+                </item>
+                <item>
+                 <widget class="QLabel" name="label_10">
+                  <property name="toolTip">
+                   <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Scan numbers that are excluded from merging beween 'from' and 'to'&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+                  </property>
+                  <property name="text">
+                   <string>Excluded Scans</string>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QLineEdit" name="lineEdit_exclScans"/>
+                </item>
+                <item>
+                 <widget class="QPushButton" name="pushButton_loadMultData">
+                  <property name="text">
+                   <string>Load All</string>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <spacer name="horizontalSpacer_13">
+                  <property name="orientation">
+                   <enum>Qt::Horizontal</enum>
+                  </property>
+                  <property name="sizeHint" stdset="0">
+                   <size>
+                    <width>40</width>
+                    <height>20</height>
+                   </size>
+                  </property>
+                 </spacer>
+                </item>
+               </layout>
+              </item>
+              <item>
+               <layout class="QHBoxLayout" name="horizontalLayout_18">
+                <item>
+                 <widget class="QLabel" name="label_15">
+                  <property name="text">
+                   <string>Miminum X</string>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QLineEdit" name="lineEdit_mergeMinX">
+                  <property name="sizePolicy">
+                   <sizepolicy hsizetype="Preferred" vsizetype="Fixed">
+                    <horstretch>0</horstretch>
+                    <verstretch>0</verstretch>
+                   </sizepolicy>
+                  </property>
+                  <property name="minimumSize">
+                   <size>
+                    <width>0</width>
+                    <height>0</height>
+                   </size>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QLabel" name="label_14">
+                  <property name="text">
+                   <string>Maximum X</string>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QLineEdit" name="lineEdit_mergeMaxX">
+                  <property name="sizePolicy">
+                   <sizepolicy hsizetype="Preferred" vsizetype="Fixed">
+                    <horstretch>0</horstretch>
+                    <verstretch>0</verstretch>
+                   </sizepolicy>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QLabel" name="label_16">
+                  <property name="text">
+                   <string>Bin Size</string>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QLineEdit" name="lineEdit_mergeBinSize">
+                  <property name="sizePolicy">
+                   <sizepolicy hsizetype="Preferred" vsizetype="Fixed">
+                    <horstretch>0</horstretch>
+                    <verstretch>0</verstretch>
+                   </sizepolicy>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QComboBox" name="comboBox_mscanUnit">
+                  <property name="sizePolicy">
+                   <sizepolicy hsizetype="Preferred" vsizetype="Fixed">
+                    <horstretch>0</horstretch>
+                    <verstretch>0</verstretch>
+                   </sizepolicy>
+                  </property>
+                  <property name="minimumSize">
+                   <size>
+                    <width>140</width>
+                    <height>0</height>
+                   </size>
+                  </property>
+                  <item>
+                   <property name="text">
+                    <string>2Theta</string>
+                   </property>
+                  </item>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QPushButton" name="pushButton_mscanBin">
+                  <property name="text">
+                   <string>Bin Data</string>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <spacer name="horizontalSpacer_3">
+                  <property name="orientation">
+                   <enum>Qt::Horizontal</enum>
+                  </property>
+                  <property name="sizeHint" stdset="0">
+                   <size>
+                    <width>40</width>
+                    <height>20</height>
+                   </size>
+                  </property>
+                 </spacer>
+                </item>
+                <item>
+                 <widget class="QLabel" name="label_mergeMessage">
+                  <property name="sizePolicy">
+                   <sizepolicy hsizetype="Expanding" vsizetype="Preferred">
+                    <horstretch>0</horstretch>
+                    <verstretch>0</verstretch>
+                   </sizepolicy>
+                  </property>
+                  <property name="text">
+                   <string>Message</string>
+                  </property>
+                 </widget>
+                </item>
+               </layout>
+              </item>
+              <item>
+               <layout class="QHBoxLayout" name="horizontalLayout_16">
+                <item>
+                 <layout class="QVBoxLayout" name="verticalLayout_mergeView">
+                  <item>
+                   <widget class="QGraphicsView" name="graphicsView_mergeRun"/>
+                  </item>
+                 </layout>
+                </item>
+                <item>
+                 <layout class="QVBoxLayout" name="verticalLayout_11">
+                  <item>
+                   <spacer name="verticalSpacer_11">
+                    <property name="orientation">
+                     <enum>Qt::Vertical</enum>
+                    </property>
+                    <property name="sizeType">
+                     <enum>QSizePolicy::Preferred</enum>
+                    </property>
+                    <property name="sizeHint" stdset="0">
+                     <size>
+                      <width>20</width>
+                      <height>40</height>
+                     </size>
+                    </property>
+                   </spacer>
+                  </item>
+                  <item>
+                   <widget class="QPushButton" name="pushButton_viewMScan1D">
+                    <property name="text">
+                     <string>View 1D</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <widget class="QPushButton" name="pushButton_view2D">
+                    <property name="text">
+                     <string>View 2D</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <widget class="QPushButton" name="pushButton_saveAllIndScans">
+                    <property name="text">
+                     <string>Save All</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <spacer name="verticalSpacer_12">
+                    <property name="orientation">
+                     <enum>Qt::Vertical</enum>
+                    </property>
+                    <property name="sizeHint" stdset="0">
+                     <size>
+                      <width>20</width>
+                      <height>40</height>
+                     </size>
+                    </property>
+                   </spacer>
+                  </item>
+                  <item>
+                   <widget class="QPushButton" name="pushButton_mergeScans">
+                    <property name="text">
+                     <string>Merge</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <widget class="QPushButton" name="pushButton_viewMerge">
+                    <property name="text">
+                     <string>View Merged</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <widget class="QPushButton" name="pushButton_saveMerge">
+                    <property name="text">
+                     <string>Save Merged</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <spacer name="verticalSpacer_19">
+                    <property name="orientation">
+                     <enum>Qt::Vertical</enum>
+                    </property>
+                    <property name="sizeType">
+                     <enum>QSizePolicy::Preferred</enum>
+                    </property>
+                    <property name="sizeHint" stdset="0">
+                     <size>
+                      <width>20</width>
+                      <height>40</height>
+                     </size>
+                    </property>
+                   </spacer>
+                  </item>
+                  <item>
+                   <widget class="QPushButton" name="pushButton_clearMultCanvas">
+                    <property name="text">
+                     <string>Clear</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <spacer name="verticalSpacer_10">
+                    <property name="orientation">
+                     <enum>Qt::Vertical</enum>
+                    </property>
+                    <property name="sizeHint" stdset="0">
+                     <size>
+                      <width>20</width>
+                      <height>40</height>
+                     </size>
+                    </property>
+                   </spacer>
+                  </item>
+                 </layout>
+                </item>
+               </layout>
+              </item>
+              <item>
+               <layout class="QHBoxLayout" name="horizontalLayout_20">
+                <item>
+                 <widget class="QLabel" name="label_13">
+                  <property name="text">
+                   <string>Vertical Label In 2D Plot</string>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QComboBox" name="comboBox_2"/>
+                </item>
+                <item>
+                 <widget class="QLabel" name="label_7">
+                  <property name="sizePolicy">
+                   <sizepolicy hsizetype="Expanding" vsizetype="Preferred">
+                    <horstretch>0</horstretch>
+                    <verstretch>0</verstretch>
+                   </sizepolicy>
+                  </property>
+                  <property name="text">
+                   <string>Message</string>
+                  </property>
+                 </widget>
+                </item>
+               </layout>
+              </item>
+             </layout>
+            </item>
+           </layout>
+          </widget>
+          <widget class="QWidget" name="tab_4">
+           <attribute name="title">
+            <string>Vanadium</string>
+           </attribute>
+           <layout class="QGridLayout" name="gridLayout_5">
+            <item row="0" column="0">
+             <layout class="QVBoxLayout" name="verticalLayout_5">
+              <item>
+               <layout class="QHBoxLayout" name="horizontalLayout_15">
+                <item>
+                 <widget class="QLabel" name="label_2">
+                  <property name="text">
+                   <string>Vanadium Peak List</string>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QLineEdit" name="lineEdit_stripVPeaks">
+                  <property name="enabled">
+                   <bool>false</bool>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <spacer name="horizontalSpacer_12">
+                  <property name="orientation">
+                   <enum>Qt::Horizontal</enum>
+                  </property>
+                  <property name="sizeType">
+                   <enum>QSizePolicy::Preferred</enum>
+                  </property>
+                  <property name="sizeHint" stdset="0">
+                   <size>
+                    <width>40</width>
+                    <height>20</height>
+                   </size>
+                  </property>
+                 </spacer>
+                </item>
+                <item>
+                 <widget class="QPushButton" name="pushButton_resetVanPeakList">
+                  <property name="text">
+                   <string>Reset Vanadium Peaks List</string>
+                  </property>
+                 </widget>
+                </item>
+               </layout>
+              </item>
+              <item>
+               <layout class="QHBoxLayout" name="horizontalLayout_11">
+                <item>
+                 <widget class="QGraphicsView" name="graphicsView_vanPeaks">
+                  <property name="sizePolicy">
+                   <sizepolicy hsizetype="Expanding" vsizetype="Expanding">
+                    <horstretch>0</horstretch>
+                    <verstretch>0</verstretch>
+                   </sizepolicy>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <layout class="QVBoxLayout" name="verticalLayout_6">
+                  <item>
+                   <spacer name="verticalSpacer_9">
+                    <property name="orientation">
+                     <enum>Qt::Vertical</enum>
+                    </property>
+                    <property name="sizeType">
+                     <enum>QSizePolicy::Preferred</enum>
+                    </property>
+                    <property name="sizeHint" stdset="0">
+                     <size>
+                      <width>20</width>
+                      <height>40</height>
+                     </size>
+                    </property>
+                   </spacer>
+                  </item>
+                  <item>
+                   <widget class="QLabel" name="label_3">
+                    <property name="sizePolicy">
+                     <sizepolicy hsizetype="Minimum" vsizetype="Preferred">
+                      <horstretch>0</horstretch>
+                      <verstretch>0</verstretch>
+                     </sizepolicy>
+                    </property>
+                    <property name="text">
+                     <string>Min 2Theta (Degrees)</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <widget class="Line" name="line">
+                    <property name="orientation">
+                     <enum>Qt::Horizontal</enum>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <widget class="QLineEdit" name="lineEdit_min2Theta">
+                    <property name="sizePolicy">
+                     <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
+                      <horstretch>0</horstretch>
+                      <verstretch>0</verstretch>
+                     </sizepolicy>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <widget class="QLabel" name="label_4">
+                    <property name="text">
+                     <string>Max 2Theta (Degrees)</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <widget class="QLineEdit" name="lineEdit_max2Theta">
+                    <property name="sizePolicy">
+                     <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
+                      <horstretch>0</horstretch>
+                      <verstretch>0</verstretch>
+                     </sizepolicy>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <widget class="QLabel" name="label_5">
+                    <property name="sizePolicy">
+                     <sizepolicy hsizetype="Minimum" vsizetype="Preferred">
+                      <horstretch>0</horstretch>
+                      <verstretch>0</verstretch>
+                     </sizepolicy>
+                    </property>
+                    <property name="text">
+                     <string>Bin size  (Degrees)</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <widget class="QLineEdit" name="lineEdit_binsize2Theta">
+                    <property name="sizePolicy">
+                     <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
+                      <horstretch>0</horstretch>
+                      <verstretch>0</verstretch>
+                     </sizepolicy>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <widget class="QPushButton" name="pushButton_rebin2Theta">
+                    <property name="text">
+                     <string>Bin Vanadium</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <spacer name="verticalSpacer_8">
+                    <property name="orientation">
+                     <enum>Qt::Vertical</enum>
+                    </property>
+                    <property name="sizeType">
+                     <enum>QSizePolicy::Preferred</enum>
+                    </property>
+                    <property name="sizeHint" stdset="0">
+                     <size>
+                      <width>20</width>
+                      <height>40</height>
+                     </size>
+                    </property>
+                   </spacer>
+                  </item>
+                  <item>
+                   <widget class="QPushButton" name="pushButton_stripVanPeaks">
+                    <property name="text">
+                     <string>Strip Vanadium Peaks</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <spacer name="verticalSpacer_21">
+                    <property name="orientation">
+                     <enum>Qt::Vertical</enum>
+                    </property>
+                    <property name="sizeType">
+                     <enum>QSizePolicy::Minimum</enum>
+                    </property>
+                    <property name="sizeHint" stdset="0">
+                     <size>
+                      <width>20</width>
+                      <height>40</height>
+                     </size>
+                    </property>
+                   </spacer>
+                  </item>
+                  <item>
+                   <layout class="QVBoxLayout" name="verticalLayout_14">
+                    <item>
+                     <widget class="QPushButton" name="pushButton_smoothVanData">
+                      <property name="text">
+                       <string>Smooth Vanadium</string>
+                      </property>
+                     </widget>
+                    </item>
+                    <item>
+                     <widget class="QLabel" name="label_20">
+                      <property name="sizePolicy">
+                       <sizepolicy hsizetype="Minimum" vsizetype="Preferred">
+                        <horstretch>0</horstretch>
+                        <verstretch>0</verstretch>
+                       </sizepolicy>
+                      </property>
+                      <property name="text">
+                       <string>Smooth Parameters</string>
+                      </property>
+                     </widget>
+                    </item>
+                    <item>
+                     <widget class="QLineEdit" name="lineEdit_smoothParams">
+                      <property name="sizePolicy">
+                       <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
+                        <horstretch>0</horstretch>
+                        <verstretch>0</verstretch>
+                       </sizepolicy>
+                      </property>
+                     </widget>
+                    </item>
+                    <item>
+                     <widget class="QPushButton" name="pushButton_applySmooth">
+                      <property name="text">
+                       <string>Apply Smooth</string>
+                      </property>
+                     </widget>
+                    </item>
+                    <item>
+                     <widget class="QPushButton" name="pushButton_undoSmooth">
+                      <property name="text">
+                       <string>Undo Smooth</string>
+                      </property>
+                     </widget>
+                    </item>
+                   </layout>
+                  </item>
+                  <item>
+                   <spacer name="verticalSpacer_22">
+                    <property name="orientation">
+                     <enum>Qt::Vertical</enum>
+                    </property>
+                    <property name="sizeType">
+                     <enum>QSizePolicy::Preferred</enum>
+                    </property>
+                    <property name="sizeHint" stdset="0">
+                     <size>
+                      <width>20</width>
+                      <height>40</height>
+                     </size>
+                    </property>
+                   </spacer>
+                  </item>
+                  <item>
+                   <widget class="QPushButton" name="pushButton_saveVanRun">
+                    <property name="toolTip">
+                     <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Save vanadium data for normalization. &lt;/p&gt;&lt;p&gt;If 'Apply Smooth' is pushed, then the smoothed data will be saved. &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+                    </property>
+                    <property name="text">
+                     <string>Save</string>
+                    </property>
+                   </widget>
+                  </item>
+                  <item>
+                   <spacer name="verticalSpacer_7">
+                    <property name="orientation">
+                     <enum>Qt::Vertical</enum>
+                    </property>
+                    <property name="sizeType">
+                     <enum>QSizePolicy::MinimumExpanding</enum>
+                    </property>
+                    <property name="sizeHint" stdset="0">
+                     <size>
+                      <width>20</width>
+                      <height>40</height>
+                     </size>
+                    </property>
+                   </spacer>
+                  </item>
+                 </layout>
+                </item>
+               </layout>
+              </item>
+             </layout>
+            </item>
+           </layout>
+          </widget>
+          <widget class="QWidget" name="tab_2">
+           <attribute name="title">
+            <string>Advanced Setup</string>
+           </attribute>
+           <layout class="QGridLayout" name="gridLayout_3">
+            <item row="0" column="0">
+             <layout class="QVBoxLayout" name="verticalLayout_4">
+              <item>
+               <layout class="QHBoxLayout" name="horizontalLayout_10">
+                <item>
+                 <widget class="QLabel" name="label_instrument">
+                  <property name="sizePolicy">
+                   <sizepolicy hsizetype="Fixed" vsizetype="Preferred">
+                    <horstretch>0</horstretch>
+                    <verstretch>0</verstretch>
+                   </sizepolicy>
+                  </property>
+                  <property name="minimumSize">
+                   <size>
+                    <width>155</width>
+                    <height>0</height>
+                   </size>
+                  </property>
+                  <property name="text">
+                   <string>Instrument</string>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QComboBox" name="comboBox_instrument">
+                  <item>
+                   <property name="text">
+                    <string>HB2A</string>
+                   </property>
+                  </item>
+                 </widget>
+                </item>
+                <item>
+                 <spacer name="horizontalSpacer_9">
+                  <property name="orientation">
+                   <enum>Qt::Horizontal</enum>
+                  </property>
+                  <property name="sizeType">
+                   <enum>QSizePolicy::Preferred</enum>
+                  </property>
+                  <property name="sizeHint" stdset="0">
+                   <size>
+                    <width>40</width>
+                    <height>20</height>
+                   </size>
+                  </property>
+                 </spacer>
+                </item>
+               </layout>
+              </item>
+              <item>
+               <spacer name="verticalSpacer_2">
+                <property name="orientation">
+                 <enum>Qt::Vertical</enum>
+                </property>
+                <property name="sizeType">
+                 <enum>QSizePolicy::Preferred</enum>
+                </property>
+                <property name="sizeHint" stdset="0">
+                 <size>
+                  <width>20</width>
+                  <height>40</height>
+                 </size>
+                </property>
+               </spacer>
+              </item>
+              <item>
+               <layout class="QHBoxLayout" name="horizontalLayout_7">
+                <item>
+                 <widget class="QLabel" name="label_cache">
+                  <property name="sizePolicy">
+                   <sizepolicy hsizetype="Fixed" vsizetype="Preferred">
+                    <horstretch>0</horstretch>
+                    <verstretch>0</verstretch>
+                   </sizepolicy>
+                  </property>
+                  <property name="minimumSize">
+                   <size>
+                    <width>155</width>
+                    <height>0</height>
+                   </size>
+                  </property>
+                  <property name="toolTip">
+                   <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Cache data file download from server to local disk. &lt;/p&gt;&lt;p&gt;The default is current working directory.  &lt;/p&gt;&lt;p&gt;The cached files will be deleted with normal quit. &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+                  </property>
+                  <property name="text">
+                   <string>Cache Raw Data File</string>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QLineEdit" name="lineEdit_cache">
+                  <property name="sizePolicy">
+                   <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+                    <horstretch>0</horstretch>
+                    <verstretch>0</verstretch>
+                   </sizepolicy>
+                  </property>
+                  <property name="minimumSize">
+                   <size>
+                    <width>400</width>
+                    <height>0</height>
+                   </size>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QPushButton" name="pushButton_browseCache">
+                  <property name="text">
+                   <string>Browse</string>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QCheckBox" name="checkBox_delCache">
+                  <property name="toolTip">
+                   <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Cached files will be deleted upon quitting normally.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+                  </property>
+                  <property name="text">
+                   <string>Delete Cache Before Quit</string>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <spacer name="horizontalSpacer_6">
+                  <property name="orientation">
+                   <enum>Qt::Horizontal</enum>
+                  </property>
+                  <property name="sizeHint" stdset="0">
+                   <size>
+                    <width>40</width>
+                    <height>20</height>
+                   </size>
+                  </property>
+                 </spacer>
+                </item>
+               </layout>
+              </item>
+              <item>
+               <layout class="QHBoxLayout" name="horizontalLayout_8">
+                <item>
+                 <widget class="QRadioButton" name="radioButton_useServer">
+                  <property name="sizePolicy">
+                   <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+                    <horstretch>0</horstretch>
+                    <verstretch>0</verstretch>
+                   </sizepolicy>
+                  </property>
+                  <property name="minimumSize">
+                   <size>
+                    <width>20</width>
+                    <height>0</height>
+                   </size>
+                  </property>
+                  <property name="text">
+                   <string/>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QLabel" name="label">
+                  <property name="sizePolicy">
+                   <sizepolicy hsizetype="Fixed" vsizetype="Preferred">
+                    <horstretch>0</horstretch>
+                    <verstretch>0</verstretch>
+                   </sizepolicy>
+                  </property>
+                  <property name="minimumSize">
+                   <size>
+                    <width>135</width>
+                    <height>0</height>
+                   </size>
+                  </property>
+                  <property name="text">
+                   <string>Server    Address</string>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QLineEdit" name="lineEdit_dataIP">
+                  <property name="sizePolicy">
+                   <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+                    <horstretch>0</horstretch>
+                    <verstretch>0</verstretch>
+                   </sizepolicy>
+                  </property>
+                  <property name="minimumSize">
+                   <size>
+                    <width>400</width>
+                    <height>0</height>
+                   </size>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QPushButton" name="pushButton_chkServer">
+                  <property name="text">
+                   <string>Check URL</string>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <spacer name="horizontalSpacer_7">
+                  <property name="orientation">
+                   <enum>Qt::Horizontal</enum>
+                  </property>
+                  <property name="sizeHint" stdset="0">
+                   <size>
+                    <width>40</width>
+                    <height>20</height>
+                   </size>
+                  </property>
+                 </spacer>
+                </item>
+               </layout>
+              </item>
+              <item>
+               <layout class="QHBoxLayout" name="horizontalLayout_9">
+                <item>
+                 <widget class="QRadioButton" name="radioButton_useLocal">
+                  <property name="sizePolicy">
+                   <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+                    <horstretch>0</horstretch>
+                    <verstretch>0</verstretch>
+                   </sizepolicy>
+                  </property>
+                  <property name="minimumSize">
+                   <size>
+                    <width>20</width>
+                    <height>0</height>
+                   </size>
+                  </property>
+                  <property name="text">
+                   <string/>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QLabel" name="label_localSrc">
+                  <property name="sizePolicy">
+                   <sizepolicy hsizetype="Fixed" vsizetype="Preferred">
+                    <horstretch>0</horstretch>
+                    <verstretch>0</verstretch>
+                   </sizepolicy>
+                  </property>
+                  <property name="minimumSize">
+                   <size>
+                    <width>135</width>
+                    <height>0</height>
+                   </size>
+                  </property>
+                  <property name="text">
+                   <string>Local Data Storage</string>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QLineEdit" name="lineEdit_localSrc">
+                  <property name="sizePolicy">
+                   <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+                    <horstretch>0</horstretch>
+                    <verstretch>0</verstretch>
+                   </sizepolicy>
+                  </property>
+                  <property name="minimumSize">
+                   <size>
+                    <width>400</width>
+                    <height>0</height>
+                   </size>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <widget class="QPushButton" name="pushButton_browseLocalSrc">
+                  <property name="text">
+                   <string>Browse</string>
+                  </property>
+                 </widget>
+                </item>
+                <item>
+                 <spacer name="horizontalSpacer_8">
+                  <property name="orientation">
+                   <enum>Qt::Horizontal</enum>
+                  </property>
+                  <property name="sizeHint" stdset="0">
+                   <size>
+                    <width>40</width>
+                    <height>20</height>
+                   </size>
+                  </property>
+                 </spacer>
+                </item>
+               </layout>
+              </item>
+              <item>
+               <layout class="QHBoxLayout" name="horizontalLayout_4"/>
+              </item>
+             </layout>
+            </item>
+            <item row="1" column="0">
+             <spacer name="verticalSpacer_13">
+              <property name="orientation">
+               <enum>Qt::Vertical</enum>
+              </property>
+              <property name="sizeHint" stdset="0">
+               <size>
+                <width>20</width>
+                <height>40</height>
+               </size>
+              </property>
+             </spacer>
+            </item>
+           </layout>
+          </widget>
+         </widget>
+        </item>
+       </layout>
+      </item>
+     </layout>
+    </item>
+   </layout>
+  </widget>
+  <widget class="QMenuBar" name="menubar">
+   <property name="geometry">
+    <rect>
+     <x>0</x>
+     <y>0</y>
+     <width>1412</width>
+     <height>25</height>
+    </rect>
+   </property>
+   <widget class="QMenu" name="menuFile">
+    <property name="title">
+     <string>File</string>
+    </property>
+    <addaction name="actionNew"/>
+    <addaction name="actionOpen_2"/>
+    <addaction name="separator"/>
+    <addaction name="actionQuit"/>
+   </widget>
+   <widget class="QMenu" name="menuHelp">
+    <property name="title">
+     <string>Help</string>
+    </property>
+    <addaction name="actionFind_Help"/>
+   </widget>
+   <addaction name="menuFile"/>
+   <addaction name="menuHelp"/>
+  </widget>
+  <widget class="QStatusBar" name="statusbar"/>
+  <action name="actionQuit">
+   <property name="text">
+    <string>Quit</string>
+   </property>
+   <property name="shortcut">
+    <string>Ctrl+Q</string>
+   </property>
+  </action>
+  <action name="actionLog">
+   <property name="text">
+    <string>Log</string>
+   </property>
+   <property name="shortcut">
+    <string>Ctrl+L</string>
+   </property>
+  </action>
+  <action name="actionNew">
+   <property name="text">
+    <string>New</string>
+   </property>
+   <property name="shortcut">
+    <string>Ctrl+N</string>
+   </property>
+  </action>
+  <action name="actionOpen">
+   <property name="text">
+    <string>Open</string>
+   </property>
+  </action>
+  <action name="actionOpen_2">
+   <property name="text">
+    <string>Open</string>
+   </property>
+   <property name="shortcut">
+    <string>Ctrl+O</string>
+   </property>
+  </action>
+  <action name="actionLoad_Setup_File">
+   <property name="text">
+    <string>Load Setup File</string>
+   </property>
+  </action>
+  <action name="actionFind_Help">
+   <property name="text">
+    <string>Find Help</string>
+   </property>
+  </action>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/Code/Mantid/MantidPlot/pymantidplot/future/__init__.py b/Code/Mantid/scripts/HFIRPowderReduction/__init__.py
similarity index 100%
rename from Code/Mantid/MantidPlot/pymantidplot/future/__init__.py
rename to Code/Mantid/scripts/HFIRPowderReduction/__init__.py
diff --git a/Code/Mantid/scripts/HFIRPowderReduction/customize.py b/Code/Mantid/scripts/HFIRPowderReduction/customize.py
new file mode 100755
index 0000000000000000000000000000000000000000..afbbed0bbaa32b2b07af1771651091190e632121
--- /dev/null
+++ b/Code/Mantid/scripts/HFIRPowderReduction/customize.py
@@ -0,0 +1,54 @@
+#!/usr/bin/python
+################################################################################
+# Customize the widigets in a gui python file generated from pyuic4
+################################################################################
+import sys
+import shutil
+
+def main(argv):
+    """ Main
+    """
+    if len(argv) < 2:
+        print "Input: %s [pyqt python file name]" % (argv[0])
+        return
+
+    # import
+    pfilename = argv[1]
+    if pfilename.endswith('.') is True:
+        pfilename += "py"
+    try:
+        pfile = open(pfilename, 'r')
+        lines = pfile.readlines()
+        pfile.close()
+    except IOError as ioe:
+        raise ioe
+
+    # move the source file
+    shutil.move(pfilename, pfilename+".bak")
+
+    # replace and add import
+    wbuf = ""
+    wbuf += "#pylint: disable=invalid-name,relative-import,too-many-lines,too-many-instance-attributes,"
+    wbuf += "too-many-statements,line-too-long,"
+    wbuf += "too-many-locals,attribute-defined-outside-init\n"
+    importclass = True
+    for line in lines:
+        if line.count('class') == 1 and line.count('):') == 1 and importclass is True:
+            # add import
+            wbuf += 'from MplFigureCanvas import *\n'
+            importclass = False
+        if line.count('QtGui.QGraphicsView(') == 1:
+            # replace QGraphicsView by Qt4MplCanvas
+            line = line.replace('QtGui.QGraphicsView(', 'Qt4MplPlotView(')
+
+        wbuf += line
+
+    # write to file
+    ofile = open(pfilename, 'w')
+    ofile.write(wbuf)
+    ofile.close()
+
+    return
+
+if __name__ == "__main__":
+    main(sys.argv)
diff --git a/Code/Mantid/scripts/HFIR_Powder_Diffraction_Reduction.py b/Code/Mantid/scripts/HFIR_Powder_Diffraction_Reduction.py
new file mode 100644
index 0000000000000000000000000000000000000000..b75b66e559f1012d3bb7650462a08ed00b958238
--- /dev/null
+++ b/Code/Mantid/scripts/HFIR_Powder_Diffraction_Reduction.py
@@ -0,0 +1,22 @@
+#pylint: disable=invalid-name,no-name-in-module
+"""
+    Script used to start the DGS reduction GUI from MantidPlot
+"""
+import sys
+
+from HFIRPowderReduction import HfirPDReductionGUI
+from PyQt4 import QtGui
+
+def qapp():
+    if QtGui.QApplication.instance():
+        _app = QtGui.QApplication.instance()
+    else:
+        _app = QtGui.QApplication(sys.argv)
+    return _app
+
+app = qapp()
+
+reducer = HfirPDReductionGUI.MainWindow() #the main ui class in this file is called MainWindow
+reducer.show()
+
+app.exec_()
diff --git a/Code/Mantid/scripts/Inelastic/Direct/DirectEnergyConversion.py b/Code/Mantid/scripts/Inelastic/Direct/DirectEnergyConversion.py
index 7e932d99679652b0df16fb9843757a9ebe281560..2a4a5ff3aaf42f6c3149dbe07cce291b79b86624 100644
--- a/Code/Mantid/scripts/Inelastic/Direct/DirectEnergyConversion.py
+++ b/Code/Mantid/scripts/Inelastic/Direct/DirectEnergyConversion.py
@@ -424,11 +424,9 @@ class DirectEnergyConversion(object):
                 # find the count rate seen in the regions of the histograms defined
                 # as the background regions, if the user defined such region.
                 # In multirep mode this has to be done here, as workspace
-                # will be cut in chunks and bg regions -- removed
-                ws_base = PropertyManager.sample_run.get_workspace()
+                # will be cut in chunks and bg regions removed
                 bkgd_range = self.bkgd_range
-                bkgr_ws = self._find_or_build_bkgr_ws(ws_base,bkgd_range[0],bkgd_range[1])
-                RenameWorkspace(InputWorkspace=bkgr_ws, OutputWorkspace='bkgr_ws_source')
+                self._find_or_build_bkgr_ws(PropertyManager.sample_run,bkgd_range[0],bkgd_range[1])
             # initialize list to store resulting workspaces to return
             result = []
         else:
@@ -491,7 +489,6 @@ class DirectEnergyConversion(object):
             else: # delete workspace if no output is requested
                 result = None
             self._old_runs_list.append(results_name)
-
         #end_for
 #------------------------------------------------------------------------------------------
 # END Main loop over incident energies
@@ -499,8 +496,14 @@ class DirectEnergyConversion(object):
 
         end_time = time.time()
         prop_man.log("*** Elapsed time = {0} sec".format(end_time - start_time),'notice')
+        # Must! clear backrgound ws (if present in multirep) to calculate background 
+        # source for next workspace 
+        if 'bkgr_ws_source' in mtd:
+            DeleteWorkspace('bkgr_ws_source')
+
 
         # CLEAR existing workspaces only if it is not run within loop
+
         #prop_man.monovan_run = None
         #prop_man.wb_run = None
         # clear combined mask
@@ -635,7 +638,7 @@ class DirectEnergyConversion(object):
         data_ws = data_run.get_workspace()
         monitor_ws = data_run.get_monitors_ws()
         if monitor_ws is None:
-           raise RuntimeError("Can not find monitors workspace for workspace {0}, run N{1}".\
+            raise RuntimeError("Can not find monitors workspace for workspace {0}, run N{1}".\
                  format(data_ws.name(),data_ws.getRunNumber()))
         separate_monitors = data_run.is_monws_separate()
         data_run.set_action_suffix('_shifted')
@@ -653,8 +656,8 @@ class DirectEnergyConversion(object):
            # instrument is shifted in case it is shifted to this monitor (usual
            # case)
            #Find TOF range, correspondent to incident energy monitor peak
-           energy_rage = self.mon2_norm_energy_range
-           self._mon2_norm_time_range = self.get_TOF_for_energies(monitor_ws,energy_rage,\
+            energy_rage = self.mon2_norm_energy_range
+            self._mon2_norm_time_range = self.get_TOF_for_energies(monitor_ws,energy_rage,\
                                                                  [self.mon2_norm_spec],None,self._debug_mode)
         #end
         if separate_monitors:
@@ -715,16 +718,16 @@ class DirectEnergyConversion(object):
         method = method.lower()
         for case in common.switch(method):
             if case('monitor-1'):
-               method,old_ws_name = self._normalize_to_monitor1(run,old_ws_name, range_offset,external_monitors_ws)
-               break
+                method,old_ws_name = self._normalize_to_monitor1(run,old_ws_name, range_offset,external_monitors_ws)
+                break
             if case('monitor-2'):
-               method,old_ws_name = self._normalize_to_monitor2(run,old_ws_name, range_offset,external_monitors_ws)
-               break
+                method,old_ws_name = self._normalize_to_monitor2(run,old_ws_name, range_offset,external_monitors_ws)
+                break
             if case('current'):
                 NormaliseByCurrent(InputWorkspace=old_ws_name,OutputWorkspace=old_ws_name)
                 break
             if case(): # default
-               raise RuntimeError('Normalization method {0} not found. It must be one of monitor-1, monitor-2, current, or None'.format(method))
+                raise RuntimeError('Normalization method {0} not found. It must be one of monitor-1, monitor-2, current, or None'.format(method))
         #endCase
 
 
@@ -741,29 +744,29 @@ class DirectEnergyConversion(object):
         # get monitor's workspace
         separate_monitors = run.is_monws_separate()
         if external_monitor_ws:
-           separate_monitors = True
-           mon_ws = external_monitor_ws
+            separate_monitors = True
+            mon_ws = external_monitor_ws
         else:
-           mon_ws = run.get_monitors_ws()
+            mon_ws = run.get_monitors_ws()
 
         if not mon_ws: # no monitors
-           if self.__in_white_normalization: # we can normalize wb integrals by current separately as they often do not
+            if self.__in_white_normalization: # we can normalize wb integrals by current separately as they often do not
                                              # have monitors
-              self.normalise(run,'current',range_offset)
-              ws = run.get_workspace()
-              new_name = ws.name()
-              return ('current',new_name)
-           else:
-              ws = run.get_workspace()
-              raise RuntimeError('Normalise by monitor-1:: Workspace {0} for run {1} does not have monitors in it'\
+                self.normalise(run,'current',range_offset)
+                ws = run.get_workspace()
+                new_name = ws.name()
+                return ('current',new_name)
+            else:
+                ws = run.get_workspace()
+                raise RuntimeError('Normalise by monitor-1:: Workspace {0} for run {1} does not have monitors in it'\
                    .format(ws.name(),run.run_number()))
 
 
         range = self.norm_mon_integration_range
         if self._debug_mode:
-           kwargs = {'NormFactorWS':'NormMon1_WS' + data_ws.getName()}
+            kwargs = {'NormFactorWS':'NormMon1_WS' + data_ws.getName()}
         else:
-           kwargs = {}
+            kwargs = {}
 
         mon_spect = self.prop_man.mon1_norm_spec
         if separate_monitors:
@@ -787,28 +790,28 @@ class DirectEnergyConversion(object):
       # get monitor's workspace
         separate_monitors = run.is_monws_separate()
         if external_monitor_ws:
-           separate_monitors = True
-           mon_ws = external_monitor_ws
+            separate_monitors = True
+            mon_ws = external_monitor_ws
         else:
-           mon_ws = run.get_monitors_ws()
+            mon_ws = run.get_monitors_ws()
 
 
         if not mon_ws: # no monitors
-           if self.__in_white_normalization: # we can normalize wb integrals by current separately as they often do not
+            if self.__in_white_normalization: # we can normalize wb integrals by current separately as they often do not
                                              # have monitors
-              self.normalise(run,'current',range_offset)
-              ws = run.get_workspace()
-              new_name = ws.name()
-              return ('current',new_name)
-           else:
-              ws = run.get_workspace()
-              raise RuntimeError('Normalize by monitor-2:: Workspace {0} for run {1} does not have monitors in it'\
+                self.normalise(run,'current',range_offset)
+                ws = run.get_workspace()
+                new_name = ws.name()
+                return ('current',new_name)
+            else:
+                ws = run.get_workspace()
+                raise RuntimeError('Normalize by monitor-2:: Workspace {0} for run {1} does not have monitors in it'\
                    .format(ws.name(),run.run_number()))
         #
         if self._debug_mode:
-           kwargs = {'NormFactorWS':'NormMon2_WS' + mon_ws.getName()}
+            kwargs = {'NormFactorWS':'NormMon2_WS' + mon_ws.getName()}
         else:
-           kwargs = {}
+            kwargs = {}
 
         mon_spect = self.prop_man.mon2_norm_spec
         mon_index = int(mon_ws.getIndexFromSpectrumNumber(mon_spect))
@@ -820,23 +823,23 @@ class DirectEnergyConversion(object):
 
         #Find TOF range, correspondent to incident energy monitor peak
         if self._mon2_norm_time_range: # range has been found during ei-calculations
-           range = self._mon2_norm_time_range
-           range_min = range[0] + range_offset
-           range_max = range[1] + range_offset
-           self._mon2_norm_time_range = None
+            range = self._mon2_norm_time_range
+            range_min = range[0] + range_offset
+            range_max = range[1] + range_offset
+            self._mon2_norm_time_range = None
         else:
-           mon_ws_name = mon_ws.name() #monitor's workspace and detector's workspace are e
-           if mon_ws_name.find('_shifted') != -1:
+            mon_ws_name = mon_ws.name() #monitor's workspace and detector's workspace are e
+            if mon_ws_name.find('_shifted') != -1:
               # monitor-2 normalization ranges have to be identified before the
               # instrument is shifted
                 raise RuntimeError("Instrument have been shifted but no time range has been identified. Monitor-2 normalization can not be performed ")
-           else:
+            else:
               # instrument and workspace shifted, so TOF will be calculated wrt
               # shifted instrument
-              energy_rage = self.mon2_norm_energy_range
-              TOF_range = self.get_TOF_for_energies(mon_ws,energy_rage,[mon_spect],None,self._debug_mode)
-              range_min = TOF_range[0]
-              range_max = TOF_range[1]
+                energy_rage = self.mon2_norm_energy_range
+                TOF_range = self.get_TOF_for_energies(mon_ws,energy_rage,[mon_spect],None,self._debug_mode)
+                range_min = TOF_range[0]
+                range_max = TOF_range[1]
        # Normalize to monitor 2
         NormaliseToMonitor(InputWorkspace=old_name,OutputWorkspace=old_name,IntegrationRangeMin=range_min,
                            IntegrationRangeMax=range_max,IncludePartialBins=True,**kwargs)
@@ -848,7 +851,7 @@ class DirectEnergyConversion(object):
             energy range requested
         """
         if not workspace:
-           workspace = PropertyManager.sample_run.get_workspace()
+            workspace = PropertyManager.sample_run.get_workspace()
 
         spectra_id = self.prop_man.multirep_tof_specta_list
         if not spectra_id or len(spectra_id) == 0:
@@ -875,14 +878,14 @@ class DirectEnergyConversion(object):
 
         nBlocks = len(spectra_id)
         if nBlocks > 1:
-           tof_min,t_step,tof_max = process_block(TOF_range[0])
-           for ind in xrange(1,nBlocks):
-               tof_min1,t_step1,tof_max1 = process_block(TOF_range[ind])
-               tof_min = min(tof_min,tof_min1)
-               tof_max = max(tof_max,tof_max1)
-               t_step = min(t_step,t_step1)
+            tof_min,t_step,tof_max = process_block(TOF_range[0])
+            for ind in xrange(1,nBlocks):
+                tof_min1,t_step1,tof_max1 = process_block(TOF_range[ind])
+                tof_min = min(tof_min,tof_min1)
+                tof_max = max(tof_max,tof_max1)
+                t_step = min(t_step,t_step1)
         else:
-               tof_min,t_step,tof_max = process_block(TOF_range)
+            tof_min,t_step,tof_max = process_block(TOF_range)
         #end
         # add 5% for detectors specified in Par file are shifted a bit and not min-max det any more
         return (0.95*tof_min,t_step,1.05*tof_max)
@@ -968,7 +971,7 @@ class DirectEnergyConversion(object):
         """
         if formats:
            # clear up existing save formats as one is defined in parameters
-           self.prop_man.save_format = None
+            self.prop_man.save_format = None
         # set up internal format variable from method parameters
         self.prop_man.set_input_parameters_ignore_nan(save_file_name=save_file,save_format=formats)
         formats = self.prop_man.save_format
@@ -976,7 +979,7 @@ class DirectEnergyConversion(object):
         if save_file:
             save_file,ext = os.path.splitext(save_file)
             if len(ext) > 1:
-               formats.add(ext[1:])
+                formats.add(ext[1:])
         else:
             save_file = self.prop_man.save_file_name
 
@@ -998,27 +1001,27 @@ class DirectEnergyConversion(object):
         for file_format  in formats:
             for case in common.switch(file_format):
                 if case('nxspe'):
-                   filename = save_file + '.nxspe'
+                    filename = save_file + '.nxspe'
                    # nxspe can not write workspace with / in the name
                    # (something to do with folder names inside nxspe)
-                   name_supported = name_orig.replace('/','of')
-                   if name_supported != name_orig:
-                      RenameWorkspace(InputWorkspace=name_orig,OutputWorkspace=name_supported)
-                   SaveNXSPE(InputWorkspace=name_supported,Filename= filename,\
+                    name_supported = name_orig.replace('/','of')
+                    if name_supported != name_orig:
+                        RenameWorkspace(InputWorkspace=name_orig,OutputWorkspace=name_supported)
+                    SaveNXSPE(InputWorkspace=name_supported,Filename= filename,\
                              KiOverKfScaling=prop_man.apply_kikf_correction,psi=prop_man.psi)
-                   if name_supported != name_orig:
-                      RenameWorkspace(InputWorkspace=name_supported,OutputWorkspace=name_orig)
-                   break
+                    if name_supported != name_orig:
+                        RenameWorkspace(InputWorkspace=name_supported,OutputWorkspace=name_orig)
+                    break
                 if case('spe'):
-                   filename = save_file + '.spe'
-                   SaveSPE(InputWorkspace=workspace,Filename= filename)
-                   break
+                    filename = save_file + '.spe'
+                    SaveSPE(InputWorkspace=workspace,Filename= filename)
+                    break
                 if case('nxs'):
-                   filename = save_file + '.nxs'
-                   SaveNexus(InputWorkspace=workspace,Filename= filename)
-                   break
+                    filename = save_file + '.nxs'
+                    SaveNexus(InputWorkspace=workspace,Filename= filename)
+                    break
                 if case(): # default, could also just omit condition or 'if True'
-                   prop_man.log("Unknown file format {0} requested to save results. No saving performed this format".\
+                    prop_man.log("Unknown file format {0} requested to save results. No saving performed this format".\
                                format(file_format))
     #########
     @property
@@ -1159,21 +1162,21 @@ class DirectEnergyConversion(object):
         error = []
         izerc = 0
         for i in range(nhist):
-           try:
-             det = data_ws.getDetector(i)
-           except Exception:
-             continue
-           if det.isMasked():
-             continue
-           sig = data_ws.readY(i)[0]
-           err = data_ws.readE(i)[0]
-           if sig != sig:     #ignore NaN (hopefully it will mean mask some day)
-               continue
-           if (err <= 0) or (sig <= 0):  # count Inf and negative||zero readings.
-              izerc+=1                   # Presence of this indicates that
-              continue                   # something went wrong
-           signal.append(sig)
-           error.append(err)
+            try:
+                det = data_ws.getDetector(i)
+            except Exception:
+                continue
+            if det.isMasked():
+                continue
+            sig = data_ws.readY(i)[0]
+            err = data_ws.readE(i)[0]
+            if sig != sig:     #ignore NaN (hopefully it will mean mask some day)
+                continue
+            if (err <= 0) or (sig <= 0):  # count Inf and negative||zero readings.
+                izerc+=1                     # Presence of this indicates that
+                continue                     # something went wrong
+            signal.append(sig)
+            error.append(err)
         #---------------- Loop finished
 
         norm_factor = {}
@@ -1232,11 +1235,11 @@ class DirectEnergyConversion(object):
 
         # check for NaN
         if (norm_factor['LibISIS'] != norm_factor['LibISIS']) | (izerc != 0):    # It is an error, print diagnostics:
-           if norm_factor['LibISIS'] != norm_factor['LibISIS']:
-               log_value = '\n--------> Absolute normalization factor is NaN <----------------------------------------------\n'
-           else:
-               log_value = '\n--------> Warning, Monovanadium has zero spectra <--------------------------------------------\n'
-               log1_value = \
+            if norm_factor['LibISIS'] != norm_factor['LibISIS']:
+                log_value = '\n--------> Absolute normalization factor is NaN <----------------------------------------------\n'
+            else:
+                log_value = '\n--------> Warning, Monovanadium has zero spectra <--------------------------------------------\n'
+                log1_value = \
                "--------> Processing workspace: {0}\n"\
                "--------> Monovan Integration range : min={1}, max={2} (meV)\n"\
                "--------> Summed:  {3} spectra with total signal: {4} and error: {5}\n"\
@@ -1248,8 +1251,8 @@ class DirectEnergyConversion(object):
                "--------> Abs norm factors: TGP    : {11}\n"\
                .format(ws_name,minmax[0],minmax[1],nhist,sum(signal),sum(error),izerc,scale_factor,
                           norm_factor['LibISIS'],norm_factor['SigSq'],norm_factor['Poisson'],norm_factor['TGP'])
-           log_value = log_value + log1_value
-           propman.log(log_value,'error')
+            log_value = log_value + log1_value
+            propman.log(log_value,'error')
         else:
             if not self._debug_mode:
                 monovan_run.clear_resulting_ws()
@@ -1294,27 +1297,27 @@ class DirectEnergyConversion(object):
         #end
 
     def __getattr__(self,attr_name):
-       """  overloaded to return values of properties non-existing in the class dictionary
+        """  overloaded to return values of properties non-existing in the class dictionary
             from the property manager class except this
             property already have descriptor in self class
        """
-       if attr_name in self._descriptors:
-          return object.__getattr__(self,attr_name)
-       else:
-          return getattr(self._propMan,attr_name)
+        if attr_name in self._descriptors:
+            return object.__getattr__(self,attr_name)
+        else:
+            return getattr(self._propMan,attr_name)
 
     def __setattr__(self,attr_name,attr_value):
-       """ overloaded to prohibit adding non-starting with _properties to the class instance
+        """ overloaded to prohibit adding non-starting with _properties to the class instance
             and add all other properties to property manager except this property already
            have a descriptor
        """
-       if attr_name[0] == '_':
-            object.__setattr__(self,attr_name,attr_value)
-       else:
-         if attr_name in self._descriptors:
+        if attr_name[0] == '_':
             object.__setattr__(self,attr_name,attr_value)
-         else:
-            setattr(self._propMan,attr_name,attr_value)
+        else:
+            if attr_name in self._descriptors:
+                object.__setattr__(self,attr_name,attr_value)
+            else:
+                setattr(self._propMan,attr_name,attr_value)
 
     def initialise(self, instr,reload_instrument=False):
         """
@@ -1358,20 +1361,20 @@ class DirectEnergyConversion(object):
             instrument = workspace.getInstrument()
             name = instrument.getName()
             if name != self.prop_man.instr_name:
-               self.prop_man = PropertyManager(name,workspace)
+                self.prop_man = PropertyManager(name,workspace)
 
 
     def get_run_descriptor(self,run):
-       """ Spawn temporary run descriptor for input data given in format,
+        """ Spawn temporary run descriptor for input data given in format,
            different from run descriptor. Return existing run descriptor,
            if it is what provided.
        """
-       if not isinstance(run,RunDescriptor):
-          tRun = copy.copy(PropertyManager._tmp_run)
-          tRun.__set__(None,run)
-          return tRun
-       else:
-           return run
+        if not isinstance(run,RunDescriptor):
+            tRun = copy.copy(PropertyManager._tmp_run)
+            tRun.__set__(None,run)
+            return tRun
+        else:
+            return run
     #
 # -------------------------------------------------------------------------------------------
 #         This actually does the conversion for the mono-sample and
@@ -1407,7 +1410,7 @@ class DirectEnergyConversion(object):
             bkg_range_min = bkgd_range[0] + bin_offset
             bkg_range_max = bkgd_range[1] + bin_offset
             if isinstance(result_ws,api.IEventWorkspace):
-                bkgr_ws = self._find_or_build_bkgr_ws(result_ws,bkg_range_min,bkg_range_max,bin_offset)
+                bkgr_ws = self._find_or_build_bkgr_ws(data_run,bkg_range_min,bkg_range_max,bin_offset)
             else:
                 bkgr_ws = None
                 CalculateFlatBackground(InputWorkspace=result_ws,OutputWorkspace=result_ws,
@@ -1432,10 +1435,10 @@ class DirectEnergyConversion(object):
 
         energy_bins = PropertyManager.energy_bins.get_abs_range(self.prop_man)
         if energy_bins:
-           Rebin(InputWorkspace=result_name,OutputWorkspace=result_name,Params= energy_bins,PreserveEvents=False)
-           if bkgr_ws: # remove background after converting units and rebinning
-              RemoveBackground(InputWorkspace=result_name,OutputWorkspace=result_name,BkgWorkspace=bkgr_ws,EMode='Direct')
-              DeleteWorkspace(bkgr_ws)
+            Rebin(InputWorkspace=result_name,OutputWorkspace=result_name,Params= energy_bins,PreserveEvents=False)
+            if bkgr_ws: # remove background after converting units and rebinning
+                RemoveBackground(InputWorkspace=result_name,OutputWorkspace=result_name,BkgWorkspace=bkgr_ws,EMode='Direct')
+                DeleteWorkspace(bkgr_ws)
         else:
             pass # TODO: investigate way of removing background from event workspace if we want
                  # result to be an event workspace
@@ -1444,14 +1447,14 @@ class DirectEnergyConversion(object):
 
         if self.apply_detector_eff and energy_bins: #should detector efficiency work on event workspace too?  At the moment it is
                                                     #not (01/02/2015)
-           DetectorEfficiencyCor(InputWorkspace=result_name,OutputWorkspace=result_name)
-           self.prop_man.log("_do_mono: finished DetectorEfficiencyCor for : " + result_name,'information')
+            DetectorEfficiencyCor(InputWorkspace=result_name,OutputWorkspace=result_name)
+            self.prop_man.log("_do_mono: finished DetectorEfficiencyCor for : " + result_name,'information')
         #############
         data_run.synchronize_ws(mtd[result_name])
 
         return
 #-------------------------------------------------------------------------------
-    def _find_or_build_bkgr_ws(self,result_ws,bkg_range_min=None,bkg_range_max=None,time_shift=0):
+    def _find_or_build_bkgr_ws(self,run,bkg_range_min=None,bkg_range_max=None,time_shift=0):
         """ Method calculates  background workspace or restore workspace with
             the same name as the one produced by this method from ADS
         """
@@ -1459,23 +1462,34 @@ class DirectEnergyConversion(object):
             bkg_range_min,bkg_range_max = self.bkgd_range
         bkg_range_min += time_shift
         bkg_range_max += time_shift
+        run = self.get_run_descriptor(run)
+        result_ws = run.get_workspace()
 
-        # has to have specific name for this all working.  This ws is build at
-        # the beginning of
-        # multirep run
+        # has to have specific name for this working. The ws is build at
+        # the beginning of multirep run.
         if 'bkgr_ws_source' in mtd:
+            #TODO: This is questionable operation, which may be unnecessary if remove background
+            # uses time interval only. (and it probably does)
+            # need to check if bkgr_ws =mtd['bkgr_ws_source'] is enough here. 
+            # (and not delete it after bkg removal)
             bkgr_ws = CloneWorkspace(InputWorkspace='bkgr_ws_source',OutputWorkspace='bkgr_ws')
-            if time_shift != 0: # Workspace has probably been shifted, so to have correct units conversion
-                                # one needs to do appropriate shift here as
-                                                               # well
-              CopyInstrumentParameters(result_ws,bkgr_ws)
+            if time_shift != 0: # Workspace has probably been shifted, so to have 
+                                # one needs to do appropriate shift here
+                                #correct units conversion as well
+                CopyInstrumentParameters(result_ws,bkgr_ws)
              # Adjust the TOF such that the first monitor peak is at t=0
-              ScaleX(InputWorkspace=bkgr_ws,OutputWorkspace='bkgr_ws',Operation="Add",Factor=time_shift,\
+                ScaleX(InputWorkspace=bkgr_ws,OutputWorkspace='bkgr_ws',Operation="Add",Factor=time_shift,\
                      InstrumentParameter="DelayTime",Combine=True)
-        else:
-           bkgr_ws = Rebin(result_ws,Params=[bkg_range_min,(bkg_range_max - bkg_range_min) * 1.001,bkg_range_max],PreserveEvents=False)
-           bkgr_ws = self.normalise(bkgr_ws, self.normalise_method, time_shift)
-
+        else: # calculate background workspace for future usage
+            bkgr_ws = Rebin(result_ws,Params=[bkg_range_min,(bkg_range_max - bkg_range_min) * 1.001,bkg_range_max],PreserveEvents=False)
+            if run.is_monws_separate():
+                mon_ws = run.get_monitors_ws()
+                CloneWorkspace(mon_ws,OutputWorkspace="bkgr_ws_monitors")
+            bkgr_ws = self.normalise(bkgr_ws, self.normalise_method, time_shift)
+            if bkgr_ws.name()+"_monitors" in mtd:
+                DeleteWorkspace(bkgr_ws.name()+"_monitors")
+            RenameWorkspace(InputWorkspace=bkgr_ws, OutputWorkspace='bkgr_ws_source')
+            bkgr_ws = mtd['bkgr_ws_source']
 
         return bkgr_ws
 #-------------------------------------------------------------------------------
@@ -1490,10 +1504,10 @@ class DirectEnergyConversion(object):
             self._do_mono_ISIS(run,ei_guess,\
                               white_run, map_file, spectra_masks, Tzero)
         else:
-          result_name = run.set_action_suffix('_spe')
-          self._do_mono_SNS(run,result_name,ei_guess,\
+            result_name = run.set_action_suffix('_spe')
+            self._do_mono_SNS(run,result_name,ei_guess,\
                          white_run, map_file, spectra_masks, Tzero)
-          run.synchronize_ws()
+            run.synchronize_ws()
 
         prop_man = self.prop_man
         ws = run.get_workspace()
@@ -1507,8 +1521,8 @@ class DirectEnergyConversion(object):
 
         # Make sure that our binning is consistent
         if prop_man.energy_bins:
-           bins = PropertyManager.energy_bins.get_abs_range(prop_man)
-           Rebin(InputWorkspace=result_name,OutputWorkspace= result_name,Params=bins)
+            bins = PropertyManager.energy_bins.get_abs_range(prop_man)
+            Rebin(InputWorkspace=result_name,OutputWorkspace= result_name,Params=bins)
 
         # Masking and grouping
         result_ws = mtd[result_name]
@@ -1546,12 +1560,12 @@ class DirectEnergyConversion(object):
                 old_log_val = targ_ws.getRun().getLogData(done_Log).value
                 done_log_VAL = self._build_white_tag()
                 if old_log_val == done_log_VAL:
-                   run.synchronize_ws(targ_ws)
-                   if self._keep_wb_workspace:
+                    run.synchronize_ws(targ_ws)
+                    if self._keep_wb_workspace:
                         result = run.get_ws_clone()
-                   else:
+                    else:
                         result = run.get_workspace()
-                   return result
+                    return result
                 else:
                     DeleteWorkspace(Workspace=new_ws_name)
             else:
@@ -1610,7 +1624,7 @@ def get_failed_spectra_list_from_masks(masked_wksp,prop_man):
     #TODO: get rid of this and use data, obtained form diagnostics
     failed_spectra = []
     if masked_wksp is None:
-       return (failed_spectra,0)
+        return (failed_spectra,0)
     try:
         name = masked_wksp.name()
     except Exeption as ex:
diff --git a/Code/Mantid/scripts/Inelastic/Direct/NonIDF_Properties.py b/Code/Mantid/scripts/Inelastic/Direct/NonIDF_Properties.py
index 08e068dd155ab5a2158ec0bf85f95ce9d97da622..9d07a6261f37ab785d0a5297fb7d9663c09d172e 100644
--- a/Code/Mantid/scripts/Inelastic/Direct/NonIDF_Properties.py
+++ b/Code/Mantid/scripts/Inelastic/Direct/NonIDF_Properties.py
@@ -96,7 +96,7 @@ class NonIDF_Properties(object):
                          If not explicitly set, white beam for sample run is used.""")
     # TODO: do something about it.  Second white is explicitly used in
     # diagnostics but not accessed at all
-    second_white  = RunDescriptor("""Second white beam run resutlts currently unused in the workflow 
+    second_white  = RunDescriptor("""Second white beam run resutlts currently unused in the workflow
                     despite being referred to in Diagnostics.
                     In a future it should be enabled.""")
     #
diff --git a/Code/Mantid/scripts/Inelastic/Direct/ReductionWrapper.py b/Code/Mantid/scripts/Inelastic/Direct/ReductionWrapper.py
index 3b68c9bad1d45dd12734804f2f1334f4f0656e4c..065faeb8835bec6f2be1f770e5b42f85983ef4c3 100644
--- a/Code/Mantid/scripts/Inelastic/Direct/ReductionWrapper.py
+++ b/Code/Mantid/scripts/Inelastic/Direct/ReductionWrapper.py
@@ -68,7 +68,7 @@ class ReductionWrapper(object):
         self._wvs = ReductionWrapper.var_holder(web_var)
       # Initialize reduced for given instrument
         self.reducer = DirectEnergyConversion(instrumentName)
-        # 
+        #
         web_vars = self._wvs.get_all_vars()
         if web_vars :
             self.reducer.prop_man.set_input_parameters(**web_vars)
@@ -159,7 +159,7 @@ class ReductionWrapper(object):
     @property
     def validate_run_number(self):
         """The property defines the run number to validate. If defined, switches reduction wrapper from
-           reduction to validation mode, where reduction tries to load result, previously calculated, 
+           reduction to validation mode, where reduction tries to load result, previously calculated,
            for this run and then compare this result with the result, defined earlier"""
         return self._run_number_to_validate
 
@@ -211,13 +211,13 @@ class ReductionWrapper(object):
 
 #
     def validate_result(self,Error=1.e-6,ToleranceRelErr=True):
-      """Method to validate result against existing validation file
+        """Method to validate result against existing validation file
          or workspace
 
          Change this method to verify different results or validate results differently"""
-      rez,message = ReductionWrapper.build_or_validate_result(self,
+        rez,message = ReductionWrapper.build_or_validate_result(self,
                                      Error,ToleranceRelErr)
-      return rez,message
+        return rez,message
    #
 
     def set_custom_output_filename(self):
@@ -256,7 +256,7 @@ class ReductionWrapper(object):
             else:
                 if len(path)>0:
                     config.appendDataSearchDir(path)
-                # it there bug in getFullPath? It returns the same string if given full path 
+                # it there bug in getFullPath? It returns the same string if given full path
                 # but file has not been found
                 name,fext=os.path.splitext(name)
                 fileName = FileFinder.getFullPath(name+'.nxs')
@@ -269,7 +269,7 @@ class ReductionWrapper(object):
                 else:
                     build_validation = True
         elif isinstance(validation_file,api.Workspace):
-        # its workspace: 
+        # its workspace:
             reference_ws = validation_file
             build_validation = False
             fileName = "workspace:"+reference_ws.name()
diff --git a/Code/Mantid/scripts/Inelastic/Direct/RunDescriptor.py b/Code/Mantid/scripts/Inelastic/Direct/RunDescriptor.py
index 48677e349e84048fb8cdbbe66d740c5b1587dcc9..c0c8a33fcce5b6beda210900dd702d0617ff5c3a 100644
--- a/Code/Mantid/scripts/Inelastic/Direct/RunDescriptor.py
+++ b/Code/Mantid/scripts/Inelastic/Direct/RunDescriptor.py
@@ -844,7 +844,7 @@ class RunDescriptor(PropDescriptor):
             except:
                 try:
                     monws_name = mon_ws.name()
-                except: 
+                except:
                     monws_name = 'None'
                 RunDescriptor._logger('*** Monitor workspace {0} does not have monitor with ID {1}. Monitor workspace set to None'.\
                                           format(monws_name,monID),'warning')
@@ -974,13 +974,26 @@ class RunDescriptor(PropDescriptor):
         else:
             mon_load_option = 'Separate'
         #
+        nxs_file=False
+        file,ext = os.path.splitext(data_file)
+        if ext == '.nxs':
+            nxs_file = True
         try: # Hack: LoadEventNexus does not understand Separate at the moment and throws.
             # And event loader always loads monitors separately
             Load(Filename=data_file, OutputWorkspace=ws_name,LoadMonitors = mon_load_option)
         except ValueError:
             #mon_load_option =str(int(load_mon_with_workspace))
             Load(Filename=data_file, OutputWorkspace=ws_name,LoadMonitors = '1',MonitorsAsEvents='0')
-
+        #HACK >>> , necessary until #11565 is fixed
+        if nxs_file :
+           instr_name = RunDescriptor._holder.instr_name
+           if instr_name == 'LET' and self._run_number>14151 and self._run_number<14382:
+                FrameworkManager.clearInstruments()
+                idf_file = api.ExperimentInfo.getInstrumentFilename(instr_name)
+                idf_path,tile = os.path.split(idf_file)
+                idf_file = os.path.join(idf_path,'LET_Definition.xml')
+                LoadInstrument(ws_name,idf_file,RewriteSpectraMap='0')
+        #HACK<<<
         RunDescriptor._logger("Loaded {0}".format(data_file),'information')
 
         loaded_ws = mtd[ws_name]
@@ -1077,7 +1090,7 @@ class RunDescriptor(PropDescriptor):
         except:
             try:
                 ws_index = data_ws.getIndexFromSpectrumNumber(spectraID)
-            except: 
+            except:
                 raise RuntimeError('*** Error: Can not retrieve spectra with ID {0} from source workspace: {1}'.\
                                     format(spectraID,data_ws.name()))
 
diff --git a/Code/Mantid/scripts/Inelastic/Direct/dgreduce.py b/Code/Mantid/scripts/Inelastic/Direct/dgreduce.py
index 53fa5df5ef9769f75c3f943ccd9a1d6665f5f1eb..eac4022db4dd6ce5794d85e88d09c5019d6b9096 100644
--- a/Code/Mantid/scripts/Inelastic/Direct/dgreduce.py
+++ b/Code/Mantid/scripts/Inelastic/Direct/dgreduce.py
@@ -151,7 +151,7 @@ def arb_units(wb_run,sample_run,ei_guess,rebin,map_file='default',monovan_run=No
     return res
 
 def runs_are_equal(ws1,ws2):
-    """Compare two run numbers, provided either as run numbers, 
+    """Compare two run numbers, provided either as run numbers,
        or as workspaces or as ws names"""
     if ws1 == ws2:
         return True
diff --git a/Code/Mantid/scripts/Inelastic/Direct/diagnostics.py b/Code/Mantid/scripts/Inelastic/Direct/diagnostics.py
index 80751e0d2816eeb1783940b536014a04d82c21ac..363ca3c9bbc5c2d9de8e5e782461145d120e151b 100644
--- a/Code/Mantid/scripts/Inelastic/Direct/diagnostics.py
+++ b/Code/Mantid/scripts/Inelastic/Direct/diagnostics.py
@@ -374,10 +374,10 @@ def do_bleed_test(sample_run, max_framerate, ignored_pixels):
     try:
         nFrames= data_ws.run().getLogData('goodfrm').value
     except RuntimeError:
-        try: 
+        try:
             nFrames = len(data_ws.run().getLogData('good_frame_log').value)
-            AddSampleLog(Workspace=data_ws, LogName='goodfrm', LogText=str(nFrames), LogType='Number') 
-        except RuntimeError: 
+            AddSampleLog(Workspace=data_ws, LogName='goodfrm', LogText=str(nFrames), LogType='Number')
+        except RuntimeError:
             raise RuntimeError("""Can not run bleed test as no appropriate good frame log is found in the workspace: {0}\n
                                   Disable bleed test by setting diag_bleed_test=False or add 'goodfrm' log value to the workspace\n"""\
                                   .format(data_ws.name()))
diff --git a/Code/Mantid/scripts/Inelastic/IndirectCommon.py b/Code/Mantid/scripts/Inelastic/IndirectCommon.py
index df391079902c51ebe4eb3f6770d5802fb3c19328..2f44373b804fb5707c1b4f93f908c8341e786c6d 100644
--- a/Code/Mantid/scripts/Inelastic/IndirectCommon.py
+++ b/Code/Mantid/scripts/Inelastic/IndirectCommon.py
@@ -88,7 +88,18 @@ def getWSprefix(wsname):
 
 def getEfixed(workspace, detIndex=0):
     inst = mtd[workspace].getInstrument()
-    return inst.getNumberParameter("efixed-val")[0]
+
+    if inst.hasParameter('Efixed'):
+        return inst.getNumberParameter('EFixed')[0]
+
+    if inst.hasParameter('analyser'):
+        analyser_name = inst.getStringParameter('analyser')[0]
+        analyser_comp = inst.getComponentByName(analyser_name)
+
+        if analyser_comp.hasParameter('Efixed'):
+            return analyser_comp.getNumberParameter('EFixed')[0]
+
+    raise ValueError('No Efixed parameter found')
 
 
 def checkUnitIs(ws, unit_id, axis_index=0):
diff --git a/Code/Mantid/scripts/Inelastic/IndirectNeutron.py b/Code/Mantid/scripts/Inelastic/IndirectNeutron.py
index 3ff569b788e9af85f6cc5ce4d464c323f7d6d73e..9633c691fe1375207654d3691f9466f9b4012569 100644
--- a/Code/Mantid/scripts/Inelastic/IndirectNeutron.py
+++ b/Code/Mantid/scripts/Inelastic/IndirectNeutron.py
@@ -5,7 +5,7 @@ from IndirectImport import *
 from mantid.simpleapi import *
 from mantid import config, logger, mtd, FileFinder
 import sys, math, os.path, numpy as np
-from IndirectCommon import StartTime, EndTime, ExtractFloat, ExtractInt
+from IndirectCommon import StartTime, EndTime, ExtractFloat, ExtractInt, getEfixed
 MTD_PLOT = import_mantidplot()
 
 #  Routines for Ascii file of raw data
@@ -447,7 +447,7 @@ def RunParas(ascWS,instr,run,title):
     AddSampleLog(Workspace=ascWS, LogName="facility", LogType="String", LogText="ILL")
     ws.getRun()['run_number'] = run
     ws.getRun()['run_title'] = title
-    efixed = inst.getNumberParameter('efixed-val')[0]
+    efixed = getEfixed(ascWS)
 
     facility = ws.getRun().getLogData('facility').value
     logger.information('Facility is ' +facility)
diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_reduction_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_reduction_script.py
index 7be77dcb093e64600ce6339b38067c740563beb2..d555dc0f53d88e4bdaba66ba999ef7582ac4fc13 100644
--- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_reduction_script.py
+++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_reduction_script.py
@@ -28,7 +28,7 @@ class DiffractionReductionScripter(BaseReductionScripter):
     def __init__(self, name="VULCAN", facility="SNS"):
         """ Initialization
         """
-        # Call base class 
+        # Call base class
         super(DiffractionReductionScripter, self).__init__(name=name, facility=facility)
 
         # Find whether there is stored setup XMLs
@@ -36,7 +36,7 @@ class DiffractionReductionScripter(BaseReductionScripter):
         mantidconfigdir = os.path.join(homedir, ".mantid")
         self.configDir = mantidconfigdir
 
-        # create configuratin dir if it has not been 
+        # create configuratin dir if it has not been
         if os.path.exists(self.configDir) is False:
             os.makedirs(self.configDir)
 
@@ -48,10 +48,10 @@ class DiffractionReductionScripter(BaseReductionScripter):
         return
 
     def to_script(self, file_name=None):
-        """ Generate reduction script via observers and 
-        (1) save the script to disk and (2) save the reduction setup to disk. 
+        """ Generate reduction script via observers and
+        (1) save the script to disk and (2) save the reduction setup to disk.
 
-        Arguments: 
+        Arguments:
          - file_name: name of the file to write the script to
         """
         # Collect partial scripters from observers
@@ -63,7 +63,7 @@ class DiffractionReductionScripter(BaseReductionScripter):
 
         # Construct python commands
         script = self.constructPythonScript(paramdict)
-        
+
         # Save script to disk
         if file_name is None:
             file_name = os.path.join(self.configDir, DiffractionReductionScripter.AUTOSCRIPTNAME)
@@ -75,7 +75,7 @@ class DiffractionReductionScripter(BaseReductionScripter):
         except IOError as e:
             print "Unable to save script to file. Reason: %s." % (str(e))
 
-        # Export XML file 
+        # Export XML file
         autosavexmlfname = os.path.join(self.configDir, "snspowderreduction.xml")
         self.to_xml(autosavexmlfname)
 
diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/scripter.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/scripter.py
index daab5c3f42790509976c304fddf94112577d3e00..243cf77a12a0cda16030e2cee6adae29e9783b88 100644
--- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/scripter.py
+++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/scripter.py
@@ -528,12 +528,18 @@ class BaseReductionScripter(object):
                 if len(scripts)>1:
                     _job_name += "_%s" % i
                 # Submit the job
-                submit_cmd =  "Authenticate(ComputeResource='%s', " % resource
+                # Note: keeping version 1 for now. See comment about
+                # versions in cluster_status.py
+                submit_cmd =  "Authenticate(Version=1, ComputeResource='%s', " % resource
                 submit_cmd += "UserName='%s', Password='%s')\n" % (user, pwd)
 
-                submit_cmd += "id=StartRemoteTransaction(ComputeResource='%s')\n" % resource
+                # Note: keeping version 1 for now. See comment about
+                # versions in cluster_status.py
+                submit_cmd += "id=StartRemoteTransaction(Version=1, ComputeResource='%s')\n" % resource
 
-                submit_cmd += "SubmitRemoteJob(ComputeResource='%s', " % resource
+                # Note: keeping version 1 for now. See comment about
+                # versions in cluster_status.py
+                submit_cmd += "SubmitRemoteJob(Version=1, ComputeResource='%s', " % resource
                 submit_cmd += "TaskName='%s'," % _job_name
                 submit_cmd += "NumNodes=%s, CoresPerNode=%s, " % (nodes, cores_per_node)
                 submit_cmd += "TransactionID=id, "
diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/cluster_status.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/cluster_status.py
index 261aba78e9b81999ebb7001bde90b51978e0584d..9f1f96873f763e872447a289c9e74e07241e4d65 100644
--- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/cluster_status.py
+++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/cluster_status.py
@@ -147,14 +147,20 @@ class RemoteJobsWidget(BaseWidget):
             self._settings.cluster_pass = pwd
             util.set_valid(self._content.username_edit, True)
             util.set_valid(self._content.password_edit, True)
-        alg = AlgorithmManager.create("Authenticate")
+        # Note: here and in the following create() calls. Version 1 of
+        # the remote algorithms is guaranteed to work at SNS. Version
+        # 2 generalizes the remote algorithms (see tickets #9277 and
+        # #11126). While the v2 implementation for the remote job
+        # submission API has been refactored without changes, it would
+        # need to be tested before upgrading v1->v2 in this script.
+        alg = AlgorithmManager.create("Authenticate", 1)
         alg.initialize()
         alg.setProperty("ComputeResource", str(self._settings.compute_resource))
         alg.setProperty("UserName", str(self._settings.cluster_user))
         alg.setProperty("Password", str(self._settings.cluster_pass))
         alg.execute()
 
-        alg = AlgorithmManager.create("QueryAllRemoteJobs")
+        alg = AlgorithmManager.create("QueryAllRemoteJobs", 1)
         alg.initialize()
         alg.setProperty("ComputeResource", str(self._settings.compute_resource))
         alg.execute()
@@ -247,7 +253,7 @@ class RemoteJobsWidget(BaseWidget):
         if is_running:
             try:
                 # At this point we are authenticated so just purge
-                alg = AlgorithmManager.create("AbortRemoteJob")
+                alg = AlgorithmManager.create("AbortRemoteJob", 1)
                 alg.initialize()
                 alg.setProperty("ComputeResource", str(self._settings.compute_resource))
                 alg.setProperty("JobID", job_id)
@@ -255,7 +261,7 @@ class RemoteJobsWidget(BaseWidget):
             except:
                 Logger("cluster_status").error("Problem aborting job: %s" % sys.exc_value)
         try:
-            alg = AlgorithmManager.create("StopRemoteTransaction")
+            alg = AlgorithmManager.create("StopRemoteTransaction", 1)
             alg.initialize()
             alg.setProperty("ComputeResource", str(self._settings.compute_resource))
             alg.setProperty("TransactionID", trans_id)
diff --git a/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_adv_setup.py b/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_adv_setup.py
index 034e3994dcb1b97e5a44defda9d9f55af35e4b07..158727ebbddfda698fec141d26217b20204c5e39 100644
--- a/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_adv_setup.py
+++ b/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_adv_setup.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,line-too-long,too-many-instance-attributes,too-many-statements
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'diffraction_adv_setup.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_filter_setup.py b/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_filter_setup.py
index d88b116c7de140b9079bd5d5d365a73aa1e78cbc..1abb6824bda7724b9b5e000d720e98194168e035 100644
--- a/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_filter_setup.py
+++ b/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_filter_setup.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,line-too-long,too-many-instance-attributes,too-many-statements
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'diffraction_filter_setup.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_info.py b/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_info.py
index 8db4195d820dfd955010b3e121c2ec0a5ac9424a..d7fd8a137e51d1b7a946b2ac3430562cc6104714 100644
--- a/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_info.py
+++ b/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_info.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,line-too-long,attribute-defined-outside-init
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'diffraction_info.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_run_setup.py b/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_run_setup.py
index cc7c42d4b27ebe39b9eaa35eac946e351ec1feee..4f035b95c6830136693217c20963619c29c9e7c0 100644
--- a/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_run_setup.py
+++ b/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_run_setup.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,line-too-long,too-many-instance-attributes,too-many-statements
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'diffraction_run_setup.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/diffraction/ui_filter_info.py b/Code/Mantid/scripts/Interface/ui/diffraction/ui_filter_info.py
index 9a448ee278d415ff0b1f8d44273978f04b8fbf56..bbdf54f0bc3240a993dd9a58f0aa5538facc3bb0 100644
--- a/Code/Mantid/scripts/Interface/ui/diffraction/ui_filter_info.py
+++ b/Code/Mantid/scripts/Interface/ui/diffraction/ui_filter_info.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,line-too-long
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'filter_info.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_absolute_units.py b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_absolute_units.py
index 4a326237468b2c699342979b2db163d42bb25221..9d7c1ac7bb99472fc77d5480ea506c3ba9a74051 100644
--- a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_absolute_units.py
+++ b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_absolute_units.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,line-too-long,too-many-instance-attributes,too-many-statements
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'ui/inelastic/dgs_absolute_units.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_data_corrections.py b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_data_corrections.py
index 6ad6b96db96e91045564271d230a10c088533d25..1ef11a3e1256afe66ba3b3cbcb6edd8f738f9e11 100644
--- a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_data_corrections.py
+++ b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_data_corrections.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,line-too-long,too-many-instance-attributes,too-many-statements
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'ui/inelastic/dgs_data_corrections.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_diagnose_detectors.py b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_diagnose_detectors.py
index dfbb26eecbe121ca16e89d2f5cd62bcffd91ee04..3eddfed7c5549aeef735a8df59694a12334cb5b6 100644
--- a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_diagnose_detectors.py
+++ b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_diagnose_detectors.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,line-too-long,too-many-instance-attributes,too-many-statements
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'ui/inelastic/dgs_diagnose_detectors.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_pd_sc_conversion.py b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_pd_sc_conversion.py
index 9cd9be7636061b165c7debd56be03de879fc98e9..23344adf8f2b754d4119269e96be114f76d8c4cd 100644
--- a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_pd_sc_conversion.py
+++ b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_pd_sc_conversion.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,line-too-long,too-many-instance-attributes
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'ui/inelastic/dgs_pd_sc_conversion.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_sample_setup.py b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_sample_setup.py
index 88f73ac39881aa9757dd9bea5b766555b8036f52..d54978a883618228eab5b41f31c16c9f6a2ae0dd 100644
--- a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_sample_setup.py
+++ b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_sample_setup.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,line-too-long,too-many-instance-attributes,too-many-statements
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file './dgs_sample_setup.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_columns.py b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_columns.py
index d1fd9c668295bf73b7d585da25f0d45352e319ca..91624a93da3f3f507e202fd7cf15eb734cb9e66b 100644
--- a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_columns.py
+++ b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_columns.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,line-too-long
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'D:\mantid\windows\Code\Mantid\scripts\Interface\ui\reflectometer/refl_columns.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_window.py b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_window.py
index c4ab205822037c08374ef866e50f7a22c577e9d9..eb9305c56b168d3a463b6f3322c6fcc1ab58f964 100644
--- a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_window.py
+++ b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_window.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,too-many-statements,too-many-instance-attributes,line-too-long
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'refl_window.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/ui_data_refl_simple.py b/Code/Mantid/scripts/Interface/ui/reflectometer/ui_data_refl_simple.py
index 4af2bc635311bd4ac3dd96d4dd238b9655d63950..a0952c1fadd6a895d0822e45c65bb47dd3175736 100644
--- a/Code/Mantid/scripts/Interface/ui/reflectometer/ui_data_refl_simple.py
+++ b/Code/Mantid/scripts/Interface/ui/reflectometer/ui_data_refl_simple.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,line-too-long,too-many-lines,too-many-instance-attributes,too-many-locals,too-many-statements,attribute-defined-outside-init
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'data_refl_simple.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refl_sf_calculator.py b/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refl_sf_calculator.py
index 622ad2badb7275e270e75bc9dc2ef232b230ffd8..f7fae718236a5b4e7eeaaf594aeaeff54545849b 100644
--- a/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refl_sf_calculator.py
+++ b/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refl_sf_calculator.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,too-many-statements,too-many-instance-attributes,line-too-long
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'refl_sf_calculator.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refl_stitching.py b/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refl_stitching.py
index fdc12c8d191b68e562bf47711a6fe0d9a16a295b..3905b80fba27445e6bf6aaa3cac6b8be0227e4f7 100644
--- a/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refl_stitching.py
+++ b/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refl_stitching.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,too-many-statements,too-many-instance-attributes,line-too-long
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'ui/reflectometer/refl_stitching.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refm_reduction.py b/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refm_reduction.py
index 267934bda984dd536dc8e886e82d79731dad94e3..431559f14a99f17949a6a1d33d3bf9dfcb84e833 100644
--- a/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refm_reduction.py
+++ b/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refm_reduction.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,line-too-long,too-many-lines,too-many-instance-attributes,too-many-locals,too-many-statements,attribute-defined-outside-init
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'refm_reduction.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_info.py b/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_info.py
index 49e5bff30d84a787d4f8195a08d144d983ef2aa6..7c8de5795d754915fcbc7b600c284e0564341c34 100644
--- a/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_info.py
+++ b/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_info.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,line-too-long
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'ui/sans/eqsans_info.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_instrument.py b/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_instrument.py
index 870b7a7d93c55866b2f2154475b202d8376c8c07..88ef626d86b250755eb3d1492e65a7512c753c7a 100644
--- a/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_instrument.py
+++ b/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_instrument.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,line-too-long,too-many-instance-attributes,too-many-statements,attribute-defined-outside-init
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'ui/sans/eqsans_instrument.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_sample_data.py b/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_sample_data.py
index c2e42a69e670b40d5e9ff1e62d806d92cd2885e3..2d9dd6a1e1e74dfd77935b73caddcc5a6b4b126e 100644
--- a/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_sample_data.py
+++ b/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_sample_data.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,too-many-statements,too-many-instance-attributes,line-too-long
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'ui/sans/eqsans_sample_data.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_background.py b/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_background.py
index 4ab3d4e4e9d5e886b348880adb52cde5c99ceaf3..8f9938e6a64a75c5818b37e4431a1a0433decedb 100644
--- a/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_background.py
+++ b/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_background.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,too-many-statements,too-many-instance-attributes,line-too-long
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'ui/sans/hfir_background.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_detector.py b/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_detector.py
index cf5fc9336376cb727c69ded1751fb718e0de7e31..21e280e709c9faffd1792c1f17d8b0176fc037db 100644
--- a/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_detector.py
+++ b/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_detector.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,too-many-statements,too-many-instance-attributes,line-too-long
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'ui/sans/hfir_detector.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_instrument.py b/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_instrument.py
index 2224f3ec82bd5e747bbffd1e1f9c290d03ac7828..a9b2337330e236bccaa954dd9df4f3545c0e46af 100644
--- a/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_instrument.py
+++ b/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_instrument.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,line-too-long,too-many-instance-attributes,too-many-statements,attribute-defined-outside-init
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'ui/sans/hfir_instrument.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_sample_data.py b/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_sample_data.py
index 834aa6ef746cde35bb8b2648519a8e4dd40dcfdd..41e4292e27e96ea06bfd4391462c3b9d441358f2 100644
--- a/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_sample_data.py
+++ b/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_sample_data.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,too-many-statements,too-many-instance-attributes,line-too-long
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'ui/sans/hfir_sample_data.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/sans/ui_trans_direct_beam.py b/Code/Mantid/scripts/Interface/ui/sans/ui_trans_direct_beam.py
index 423ff87ff5f5ecdd21bb2f2e69f4727bd2e672fd..8a7308b7ce294d4a53724ab1a55925f7ee488a74 100644
--- a/Code/Mantid/scripts/Interface/ui/sans/ui_trans_direct_beam.py
+++ b/Code/Mantid/scripts/Interface/ui/sans/ui_trans_direct_beam.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,line-too-long,too-many-instance-attributes,too-many-statements
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'ui/sans/trans_direct_beam.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/sans/ui_trans_spreader.py b/Code/Mantid/scripts/Interface/ui/sans/ui_trans_spreader.py
index 566620ef1ad02e1f4118efb1d1e92ab0dd5497cd..077d6af3fad7a4088744a796f3f9dc869046de32 100644
--- a/Code/Mantid/scripts/Interface/ui/sans/ui_trans_spreader.py
+++ b/Code/Mantid/scripts/Interface/ui/sans/ui_trans_spreader.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,too-many-locals, too-many-instance-attributes,line-too-long
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'ui/sans/trans_spreader.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/ui_cluster_details_dialog.py b/Code/Mantid/scripts/Interface/ui/ui_cluster_details_dialog.py
index d29d1c852590ad8701732aa776dbf6d246b6efd4..3d1e66eb28a657f54d4e82b8aac6ebf514c97899 100644
--- a/Code/Mantid/scripts/Interface/ui/ui_cluster_details_dialog.py
+++ b/Code/Mantid/scripts/Interface/ui/ui_cluster_details_dialog.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,too-many-instance-attributes
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'ui/cluster_details_dialog.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/ui_cluster_status.py b/Code/Mantid/scripts/Interface/ui/ui_cluster_status.py
index edb55cc71116b265ea11a0ff928023d94b74ef41..2c4e73b0181d38a67d14f61cfec1055fb550ae24 100644
--- a/Code/Mantid/scripts/Interface/ui/ui_cluster_status.py
+++ b/Code/Mantid/scripts/Interface/ui/ui_cluster_status.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,line-too-long,too-many-instance-attributes
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'ui/cluster_status.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/ui_data_catalog.py b/Code/Mantid/scripts/Interface/ui/ui_data_catalog.py
index 9893c53b9a45e56d5266a593356242509e7118c6..e45838f492f7aec8e34eb8b5347bdadfe6888239 100644
--- a/Code/Mantid/scripts/Interface/ui/ui_data_catalog.py
+++ b/Code/Mantid/scripts/Interface/ui/ui_data_catalog.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'ui/data_catalog.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/ui_hfir_output.py b/Code/Mantid/scripts/Interface/ui/ui_hfir_output.py
index b779a4dc13d76eb3b5f99036f22cc769f88025d9..fee6fe518da045e4a93e80abfac6fca454770f7c 100644
--- a/Code/Mantid/scripts/Interface/ui/ui_hfir_output.py
+++ b/Code/Mantid/scripts/Interface/ui/ui_hfir_output.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,line-too-long,too-many-instance-attributes
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'ui/hfir_output.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/ui_instrument_dialog.py b/Code/Mantid/scripts/Interface/ui/ui_instrument_dialog.py
index 67b3ab66b280215c1f916f11f726e0e2602c71ba..f0355cfaa03bf1d50529fa11b9dcc96aae6b20a6 100644
--- a/Code/Mantid/scripts/Interface/ui/ui_instrument_dialog.py
+++ b/Code/Mantid/scripts/Interface/ui/ui_instrument_dialog.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,too-many-instance-attributes
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'ui/instrument_dialog.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/ui_reduction_main.py b/Code/Mantid/scripts/Interface/ui/ui_reduction_main.py
index f3fecebf0c6e4069d1eb8f7bd235f913df51e11b..b7f965acb10e8eede9ff3ed4bc083380f854ffa9 100644
--- a/Code/Mantid/scripts/Interface/ui/ui_reduction_main.py
+++ b/Code/Mantid/scripts/Interface/ui/ui_reduction_main.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,line-too-long,too-many-instance-attributes
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'reduction_main.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/ui_stitcher.py b/Code/Mantid/scripts/Interface/ui/ui_stitcher.py
index 9ca6c11a4af19ef5b92f9e2bd6b49618a5d24520..a607f4aa62a8acf9c0457b3d0768ee5196061514 100644
--- a/Code/Mantid/scripts/Interface/ui/ui_stitcher.py
+++ b/Code/Mantid/scripts/Interface/ui/ui_stitcher.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,line-too-long,too-many-instance-attributes,too-many-statements
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'ui/stitcher.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/ui_trans_direct_beam.py b/Code/Mantid/scripts/Interface/ui/ui_trans_direct_beam.py
index d7a996b26006a42e991c9a030cdd96ebd0a52e6b..a9f0c2a6260d18b3ea3e09eda1598391e7896ed4 100644
--- a/Code/Mantid/scripts/Interface/ui/ui_trans_direct_beam.py
+++ b/Code/Mantid/scripts/Interface/ui/ui_trans_direct_beam.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,line-too-long,too-many-instance-attributes
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'ui/trans_direct_beam.ui'
diff --git a/Code/Mantid/scripts/Interface/ui/ui_trans_spreader.py b/Code/Mantid/scripts/Interface/ui/ui_trans_spreader.py
index d5d5119dbcc1bd3df83f421b0fdd80c4ddc44768..80a16af8b37275de17de59614113e0b945c3840e 100644
--- a/Code/Mantid/scripts/Interface/ui/ui_trans_spreader.py
+++ b/Code/Mantid/scripts/Interface/ui/ui_trans_spreader.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: disable=invalid-name,attribute-defined-outside-init,line-too-long,too-many-instance-attributes
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'ui/trans_spreader.ui'
diff --git a/Code/Mantid/scripts/Powder_Diffraction_Reduction.py b/Code/Mantid/scripts/Powder_Diffraction_Reduction.py
index 18a5cd66b305a3fa25d61c2567437c33f14ddc0d..73ccc25e770f468180ed1c528dfeb8b5600fc91c 100644
--- a/Code/Mantid/scripts/Powder_Diffraction_Reduction.py
+++ b/Code/Mantid/scripts/Powder_Diffraction_Reduction.py
@@ -8,15 +8,15 @@ from reduction_application import ReductionGUI
 from PyQt4 import QtCore, uic
 
 reducer = ReductionGUI(instrument_list=["PG3", "NOM", "VULCAN"])
-if reducer.setup_layout(load_last=True): 
-  
+if reducer.setup_layout(load_last=True):
+
     # Set up reduction configuration from previous usage
     try:
         # Find home dir
-        homedir = os.path.expanduser("~") 
+        homedir = os.path.expanduser("~")
         mantidconfigdir = os.path.join(homedir, ".mantid")
         autopath = os.path.join(mantidconfigdir, 'snspowderreduction.xml')
-        # Load configuration 
+        # Load configuration
         reducer.open_file(autopath)
     except IOError as e:
         print "[Error] Unable to load previously reduction setup from file %s.\nReason: %s." % (
diff --git a/Code/Mantid/scripts/PyChop.py b/Code/Mantid/scripts/PyChop.py
index 650936bba2eaad9a32ea9dedb5d03593c98b0dda..c09010802ef0ba551d6d570540806155166429c9 100644
--- a/Code/Mantid/scripts/PyChop.py
+++ b/Code/Mantid/scripts/PyChop.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: skip-file
 from mantid import config
 from PyChop import fluxGUI
 from PyChop import PyChopGUI
diff --git a/Code/Mantid/scripts/PyChop/PyChop.py b/Code/Mantid/scripts/PyChop/PyChop.py
index a869bbdaefb04912ab412ebb0031b5c6a9bbaab5..c0a7a62f24fdf86e2f7443c624fe9bec3c7bb672 100644
--- a/Code/Mantid/scripts/PyChop/PyChop.py
+++ b/Code/Mantid/scripts/PyChop/PyChop.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: skip-file
 import time as time
 import math
 import numpy
diff --git a/Code/Mantid/scripts/PyChop/PyChopGUI.py b/Code/Mantid/scripts/PyChop/PyChopGUI.py
index 73140bc454100270bb063dda66863056256d3238..e19e007495673a0c73a79f053bcfaf63f00e4b73 100644
--- a/Code/Mantid/scripts/PyChop/PyChopGUI.py
+++ b/Code/Mantid/scripts/PyChop/PyChopGUI.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: skip-file
 
 from PyChopUI import Ui_MainWindow
 from PyQt4 import QtCore, QtGui
diff --git a/Code/Mantid/scripts/PyChop/PyChopUI.py b/Code/Mantid/scripts/PyChop/PyChopUI.py
index a36624b4cf51da8ab700a53404fe02acc531b807..865ab01da5f079a4eccfb19201510d7b4c10a37c 100644
--- a/Code/Mantid/scripts/PyChop/PyChopUI.py
+++ b/Code/Mantid/scripts/PyChop/PyChopUI.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: skip-file
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file '/Users/jon/QtSDK/pychopui.ui'
diff --git a/Code/Mantid/scripts/PyChop/PyChop_LET_UI.py b/Code/Mantid/scripts/PyChop/PyChop_LET_UI.py
index b25f6b02556797362c1e5b4ed4cac6105953e9a3..a3c5a97b8a3d3be5384277bb62186c93b9899823 100644
--- a/Code/Mantid/scripts/PyChop/PyChop_LET_UI.py
+++ b/Code/Mantid/scripts/PyChop/PyChop_LET_UI.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: skip-file
 # -*- coding: utf-8 -*-
 
 # Form implementation generated from reading ui file 'C:\Mantid\Code\Mantid\scripts\PyChop\PyChop_LET_UI.ui'
diff --git a/Code/Mantid/scripts/PyChop/fluxGUI.py b/Code/Mantid/scripts/PyChop/fluxGUI.py
index 7f6444bff60c809c80fc444813d70ab22d97b948..7bd747c99327d9f518b7d8bbd542685488772936 100644
--- a/Code/Mantid/scripts/PyChop/fluxGUI.py
+++ b/Code/Mantid/scripts/PyChop/fluxGUI.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+#pylint: skip-file
 from PyChop_LET_UI import Ui_MainWindow #import line for the UI python class
 from PyQt4 import QtCore, QtGui #import others if needed
 
diff --git a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/quick.py b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/quick.py
index fa0c74c731dfdd4cefcc1c3495e8ecfc5ca6a0b0..41101523f41074363ccd5fc60587737929b3b9f0 100644
--- a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/quick.py
+++ b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/quick.py
@@ -9,13 +9,13 @@
 '''
 #these need to be moved into one NR folder or so
 #from ReflectometerCors import *
-from l2q import *
-from combineMulti import *
+from isis_reflectometry.l2q import *
+from isis_reflectometry.combineMulti import *
 from mantid.simpleapi import *  # New API
 
 from mantid.api import WorkspaceGroup, MatrixWorkspace
 from mantid.kernel import logger
-from convert_to_wavelength import ConvertToWavelength
+from isis_reflectometry.convert_to_wavelength import ConvertToWavelength
 import math
 import re
 import abc
@@ -122,7 +122,8 @@ def quick_explicit(run, i0_monitor_index, lambda_min, lambda_max,  background_mi
         detector_index_ranges = (multi_detector_start, nHist-1)
 
 
-    _monitor_ws, _detector_ws = to_lam.convert(wavelength_min=lambda_min, wavelength_max=lambda_max, detector_workspace_indexes=detector_index_ranges, monitor_workspace_index=i0_monitor_index, correct_monitor=True, bg_min=background_min, bg_max=background_max )
+    _monitor_ws, _detector_ws = to_lam.convert(wavelength_min=lambda_min, wavelength_max=lambda_max, 
+    detector_workspace_indexes=detector_index_ranges, monitor_workspace_index=i0_monitor_index, correct_monitor=True, bg_min=background_min, bg_max=background_max )
 
     inst = _sample_ws.getInstrument()
     # Some beamline constants from IDF
@@ -187,7 +188,6 @@ def quick_explicit(run, i0_monitor_index, lambda_min, lambda_max,  background_mi
             detLocation=inst.getComponentByName(detector_component_name).getPos()
             sampleLocation=inst.getComponentByName(sample_component_name).getPos()
             detLocation=inst.getComponentByName(detector_component_name).getPos()
-            sample2detector=detLocation-sampleLocation    # metres
             source=inst.getSource()
             beamPos = sampleLocation - source.getPos()
             theta = groupGet(str(_sample_ws),'samp','theta')
@@ -238,9 +238,8 @@ def make_trans_corr(transrun, stitch_start_overlap, stitch_end_overlap, stitch_p
     Make the transmission correction workspace.
     '''
 
-    '''
-    Check to see whether all optional inputs have been provide. If not we have to get them from the IDF.
-    '''
+
+    # Check to see whether all optional inputs have been provide. If not we have to get them from the IDF.
     if not all((lambda_min, lambda_max, background_min, background_max, int_min, int_max, detector_index_ranges, i0_monitor_index)):
         logger.notice("make_trans_corr: Fetching missing arguments from the IDF")
         instrument_source = transrun
diff --git a/Code/Mantid/scripts/SANS/ISISCommandInterface.py b/Code/Mantid/scripts/SANS/ISISCommandInterface.py
index 127cc5410f9793efc32eb66af44bf6a30f0c2379..d0e229a05a9c6b6b06c915baad1a87a728648aac 100644
--- a/Code/Mantid/scripts/SANS/ISISCommandInterface.py
+++ b/Code/Mantid/scripts/SANS/ISISCommandInterface.py
@@ -864,7 +864,7 @@ def SetDetectorOffsets(bank, x, y, z, rot, radius, side, xtilt=0.0, ytilt=0.0 ):
     detector.y_tilt = ytilt
 
 def SetCorrectionFile(bank, filename):
-    # 10/03/15 RKH, create a new routine that allows change of "direct beam file" = correction file, for a given 
+    # 10/03/15 RKH, create a new routine that allows change of "direct beam file" = correction file, for a given
     # detector, this simplify the iterative process used to adjust it. Will still have to keep changing the name of the file
     # for each iteratiom to avoid Mantid using a cached version, but can then use only a single user (=mask) file for each set of iterations.
     # Modelled this on SetDetectorOffsets above ...
@@ -876,7 +876,7 @@ def SetCorrectionFile(bank, filename):
 
     detector = ReductionSingleton().instrument.getDetector(bank)
     detector.correction_file = filename
-    
+
 def LimitsR(rmin, rmax, quiet=False, reducer=None):
     if reducer == None:
         reducer = ReductionSingleton().reference()
diff --git a/Code/Mantid/scripts/SANS/SANSUtility.py b/Code/Mantid/scripts/SANS/SANSUtility.py
index 59904b160692ccdf40799e8fcfa05dfb9296b761..141b8e924cb827d49ed0c0036abfbca602213eb9 100644
--- a/Code/Mantid/scripts/SANS/SANSUtility.py
+++ b/Code/Mantid/scripts/SANS/SANSUtility.py
@@ -4,7 +4,7 @@
 # SANS data reduction scripts
 ########################################################
 from mantid.simpleapi import *
-from mantid.api import IEventWorkspace
+from mantid.api import IEventWorkspace, MatrixWorkspace, WorkspaceGroup
 import inspect
 import math
 import os
@@ -13,6 +13,11 @@ import types
 
 sanslog = Logger("SANS")
 
+ADDED_EVENT_DATA_TAG = '_added_event_data'
+
+REG_DATA_NAME = '-add' + ADDED_EVENT_DATA_TAG + '[_1-9]*$'
+REG_DATA_MONITORS_NAME = '-add_monitors' + ADDED_EVENT_DATA_TAG + '[_1-9]*$'
+
 def deprecated(obj):
     """
     Decorator to apply to functions or classes that we think are not being (or
@@ -471,6 +476,128 @@ def mask_detectors_with_masking_ws(ws_name, masking_ws_name):
 
     MaskDetectors(Workspace=ws, DetectorList=masked_det_ids)
 
+
+def check_child_ws_for_name_and_type_for_added_eventdata(wsGroup):
+    '''
+    Ensure that the while loading added event data, we are dealing with
+    1. The correct naming convention. For event data this is the run number,
+       an add tag and possibly underscores and numbers when the same workspace
+       is reloaded. For monitor data it is the run number, an add tag, a monitor
+       tag and the possibly underscores and numbers when the same workspace is
+       reloaded
+    2. The correct workspace types.
+    @param wsGroup ::  workspace group.
+    '''
+    hasData = False
+    hasMonitors = False
+
+    # Check if there are only two children in the group workspace
+    if len(wsGroup) != 2:
+        return False
+
+    assert isinstance(wsGroup, WorkspaceGroup)
+
+    for index in range(len(wsGroup)):
+        childWorkspace = wsGroup.getItem(index)
+        if re.search(REG_DATA_NAME, childWorkspace.getName()):
+            if isinstance(childWorkspace, IEventWorkspace):
+                hasData = True
+        elif re.search(REG_DATA_MONITORS_NAME, childWorkspace.getName()):
+            if isinstance(childWorkspace, MatrixWorkspace):
+                hasMonitors = True
+
+    return hasData and hasMonitors
+
+def extract_child_ws_for_added_eventdata(ws_group, appendix):
+    '''
+    Extract the the child workspaces from a workspace group which was
+    created by adding event data. The workspace group must contains a data
+    workspace which is an EventWorkspace and a monitor workspace which is a
+    matrix workspace.
+    @param ws_group :: workspace group.
+    @param appendix :: what to append to the names of the child workspaces
+    '''
+    # Store the name of the group workspace in a string
+    ws_group_name = ws_group.getName()
+
+    # Get a handle on each child workspace
+    ws_handles = []
+    for index in range(len(ws_group)):
+        ws_handles.append(ws_group.getItem(index))
+
+    if len(ws_handles) != 2:
+        raise RuntimeError('Expected two child workspaces when loading added event data.'/
+                           'Please make sure that you have loaded added event data which was generated by the Add tab of the SANS Gui.')
+
+    # Now ungroup the group
+    UnGroupWorkspace(ws_group)
+
+    # Rename the child workspaces to be of the expected format. (see _get_workspace_name in sans_reduction_steps)
+    for ws_handle in ws_handles:
+        # Check if the child is an event data workspace or a monitor workspace
+        if appendix in ws_handle.getName():
+            new_name = ws_group_name + appendix
+            RenameWorkspace(InputWorkspace = ws_handle.getName(), OutputWorkspace = new_name)
+        else:
+            new_name = ws_group_name
+            RenameWorkspace(InputWorkspace = ws_handle.getName(), OutputWorkspace = new_name)
+
+def bundle_added_event_data_as_group(out_file_name, out_file_monitors_name):
+    """
+    We load an added event data file and its associated monitor file. Combine
+    the data in a group workspace and delete the original files.
+    @param out_file_name :: the file name of the event data file
+    @param out_file_monitors_name :: the file name of the monitors file
+    @return the name fo the new group workspace file
+    """
+    # Extract the file name and the extension
+    file_name, file_extension = os.path.splitext(out_file_name)
+
+    event_data_temp = file_name + ADDED_EVENT_DATA_TAG
+    Load(Filename = out_file_name, OutputWorkspace = event_data_temp)
+    event_data_ws = mtd[event_data_temp]
+
+    monitor_temp = file_name + '_monitors' + ADDED_EVENT_DATA_TAG
+    Load(Filename = out_file_monitors_name, OutputWorkspace = monitor_temp)
+
+    monitor_ws = mtd[monitor_temp]
+
+    out_group_file_name = file_name + file_extension
+    out_group_ws_name = file_name
+
+    # Delete the intermediate files
+    full_data_path_name = get_full_path_for_added_event_data(out_file_name)
+    full_monitor_path_name = get_full_path_for_added_event_data(out_file_monitors_name)
+
+    if os.path.exists(full_data_path_name):
+        os.remove(full_data_path_name)
+    if os.path.exists(full_monitor_path_name):
+        os.remove(full_monitor_path_name)
+
+    # Create a grouped workspace with the data and the monitor child workspaces
+    GroupWorkspaces(InputWorkspaces = [event_data_ws, monitor_ws], OutputWorkspace = out_group_ws_name)
+    group_ws = mtd[out_group_ws_name]
+
+    # Save the group
+    SaveNexusProcessed(InputWorkspace = group_ws, Filename = out_group_file_name, Append=False)
+    # Delete the files and the temporary workspaces
+    DeleteWorkspace(event_data_ws)
+    DeleteWorkspace(monitor_ws)
+
+    return out_group_file_name
+
+def get_full_path_for_added_event_data(file_name):
+    path,base = os.path.split(file_name)
+    if path == '' or base not in os.listdir(path):
+        path = config['defaultsave.directory'] + path
+        # If the path is still an empty string check in the current working directory
+        if path == '':
+            path = os.getcwd()
+        assert base in os.listdir(path)
+    full_path_name = os.path.join(path, base)
+
+    return full_path_name
+
 ###############################################################################
 ######################### Start of Deprecated Code ############################
 ###############################################################################
diff --git a/Code/Mantid/scripts/SANS/SANSadd2.py b/Code/Mantid/scripts/SANS/SANSadd2.py
index a8a6436f50ad6148177616e20abaf0b120c59dff..d47d6661852dd2b28b240bfb9c2e73c512f41c76 100644
--- a/Code/Mantid/scripts/SANS/SANSadd2.py
+++ b/Code/Mantid/scripts/SANS/SANSadd2.py
@@ -2,12 +2,13 @@
 import os
 from mantid.simpleapi import *
 from mantid.kernel import Logger
+from SANSUtility import (bundle_added_event_data_as_group)
 sanslog = Logger("SANS")
 from shutil import copyfile
 
 _NO_INDIVIDUAL_PERIODS = -1
 
-def add_runs(runs, inst='sans2d', defType='.nxs', rawTypes=('.raw', '.s*', 'add','.RAW'), lowMem=False, binning='Monitors'):
+def add_runs(runs, inst='sans2d', defType='.nxs', rawTypes=('.raw', '.s*', 'add','.RAW'), lowMem=False, binning='Monitors', saveAsEvent=False):
     if inst.upper() == "SANS2DTUBES":
         inst = "SANS2D"
   #check if there is at least one file in the list
@@ -86,7 +87,7 @@ def add_runs(runs, inst='sans2d', defType='.nxs', rawTypes=('.raw', '.s*', 'add'
             return ""
 
     # in case of event file force it into a histogram workspace
-        if isFirstDataSetEvent:
+        if isFirstDataSetEvent and saveAsEvent == False:
             wsInMonitor = mtd['AddFilesSumTempory_monitors']
             if binning == 'Monitors':
                 monX = wsInMonitor.dataX(0)
@@ -125,17 +126,27 @@ def add_runs(runs, inst='sans2d', defType='.nxs', rawTypes=('.raw', '.s*', 'add'
 
             if 'AddFilesSumTempory_Rebin' in mtd : DeleteWorkspace('AddFilesSumTempory_Rebin')
 
+
         lastFile = os.path.splitext(lastFile)[0]
     # now save the added file
         outFile = lastFile+'-add.'+'nxs'
+        outFile_monitors = lastFile+'-add_monitors.'+'nxs'
         logger.notice('writing file:   '+outFile)
+
         if period == 1 or period == _NO_INDIVIDUAL_PERIODS:
-      #replace the file the first time around
+        #replace the file the first time around
             SaveNexusProcessed(InputWorkspace="AddFilesSumTempory",
                                Filename=outFile, Append=False)
+            # If we are saving event data, then we need to save also the monitor file
+            if isFirstDataSetEvent and saveAsEvent:
+                SaveNexusProcessed(InputWorkspace="AddFilesSumTempory_monitors",
+                                   Filename=outFile_monitors , Append=False)
+
         else:
       #then append
             SaveNexusProcessed("AddFilesSumTempory", outFile, Append=True)
+            if isFirstDataSetEvent and saveAsEvent:
+                SaveNexusProcessed("AddFilesSumTempory_monitors", outFile_monitors , Append=True)
 
         DeleteWorkspace("AddFilesSumTempory")
         if isFirstDataSetEvent:
@@ -149,11 +160,17 @@ def add_runs(runs, inst='sans2d', defType='.nxs', rawTypes=('.raw', '.s*', 'add'
         else:
             period += 1
 
-  #this adds the path to the filename
+    if isFirstDataSetEvent and saveAsEvent:
+        outFile = bundle_added_event_data_as_group(outFile, outFile_monitors)
 
+  #this adds the path to the filename
     path,base = os.path.split(outFile)
     if path == '' or base not in os.listdir(path):
+        # Try the default save directory
         path = config['defaultsave.directory'] + path
+        # If the path is still an empty string check in the current working directory
+        if path == '':
+            path = os.getcwd()
         assert base in os.listdir(path)
     pathout = path
     if logFile:
@@ -279,6 +296,5 @@ def _copyLog(lastPath, logFile, pathout):
         print error
         logger.notice(error)
 
-
 if __name__ == '__main__':
     add_runs(('16183','16197'),'SANS2D','.nxs')
diff --git a/Code/Mantid/scripts/SANS/isis_instrument.py b/Code/Mantid/scripts/SANS/isis_instrument.py
index 088d87dd5f3481a27bb9cc82a476b8dc892dd9c0..4560564c06b26a4d5de15f216fefc4650824ff19 100644
--- a/Code/Mantid/scripts/SANS/isis_instrument.py
+++ b/Code/Mantid/scripts/SANS/isis_instrument.py
@@ -1,11 +1,8 @@
 #pylint: disable=invalid-name
-import datetime
 import math
 import os
 import re
 import sys
-import time
-import xml.dom.minidom
 
 from mantid.simpleapi import *
 from mantid.api import WorkspaceGroup, Workspace, ExperimentInfo
@@ -435,24 +432,24 @@ class ISISInstrument(BaseInstrument):
         # see if a second step size is defined. If not set the second value to the first for compatibility
         #logger.warning("Trying to find centre-finder-step-size2")
         try:
-           self.cen_find_step2 = float(self.definition.getNumberParameter('centre-finder-step-size2')[0])
+            self.cen_find_step2 = float(self.definition.getNumberParameter('centre-finder-step-size2')[0])
         except:
            #logger.warning("Failed to find centre-finder-step-size2")
-           self.cen_find_step2 = self.cen_find_step
+            self.cen_find_step2 = self.cen_find_step
 
         logger.warning("Trying to find beam-centre-scale-factor1")
         try:
-           self.beam_centre_scale_factor1 = float(self.definition.getNumberParameter('beam-centre-scale-factor1')[0])
+            self.beam_centre_scale_factor1 = float(self.definition.getNumberParameter('beam-centre-scale-factor1')[0])
         except:
-           logger.warning("Failed to find beam-centre-scale-factor1")
-           self.beam_centre_scale_factor1 = 1000.0
+            logger.warning("Failed to find beam-centre-scale-factor1")
+            self.beam_centre_scale_factor1 = 1000.0
 
         logger.warning("Trying to find beam-centre-scale-factor2")
         try:
-           self.beam_centre_scale_factor2 = float(self.definition.getNumberParameter('beam-centre-scale-factor2')[0])
+            self.beam_centre_scale_factor2 = float(self.definition.getNumberParameter('beam-centre-scale-factor2')[0])
         except:
-           logger.warning("Failed to find beam-centre-scale-factor2")
-           self.beam_centre_scale_factor2 = 1000.0
+            logger.warning("Failed to find beam-centre-scale-factor2")
+            self.beam_centre_scale_factor2 = 1000.0
 
         firstDetect = DetectorBank(self.definition, 'low-angle')
         #firstDetect.disable_y_and_rot_corrs()
@@ -924,14 +921,14 @@ class SANS2D(ISISInstrument):
         FRONT_DET_Z, FRONT_DET_X, FRONT_DET_ROT, REAR_DET_Z, REAR_DET_X = self.getDetValues(ws)
 
         # Deal with front detector
-        # 10/03/15 RKH need to add tilt of detector, in degrees, with respect to the horizontal or vertical of the detector plane 
+        # 10/03/15 RKH need to add tilt of detector, in degrees, with respect to the horizontal or vertical of the detector plane
         # this time we can rotate about the detector's own axis so can use RotateInstrumentComponent, ytilt rotates about x axis, xtilt rotates about z axis
         #
         if frontDet.y_tilt != 0.0:
             RotateInstrumentComponent(Workspace=ws,ComponentName= self.getDetector('front').name(), X = "1.", Y = "0.", Z = "0.", Angle = frontDet.y_tilt)
         if frontDet.x_tilt != 0.0:
             RotateInstrumentComponent(Workspace=ws,ComponentName= self.getDetector('front').name(), X = "0.", Y = "0.", Z = "1.", Angle = frontDet.x_tilt)
-        #		
+        #
         # 9/1/12  this all dates to Richard Heenan & Russell Taylor's original python development for SANS2d
     	# the rotation axis on the SANS2d front detector is actually set front_det_radius = 306mm behind the detector.
     	# Since RotateInstrumentComponent will only rotate about the centre of the detector, we have to to the rest here.
@@ -961,7 +958,7 @@ class SANS2D(ISISInstrument):
 
         # deal with rear detector
 
-        # 10/03/15 RKH need to add tilt of detector, in degrees, with respect to the horizontal or vertical of the detector plane 
+        # 10/03/15 RKH need to add tilt of detector, in degrees, with respect to the horizontal or vertical of the detector plane
         # Best to do the tilts first, while the detector is still centred on the z axis, ytilt rotates about x axis, xtilt rotates about z axis
         # NOTE the beam centre coordinates may change
         if rearDet.y_tilt != 0.0:
@@ -1382,7 +1379,7 @@ class LARMOR(ISISInstrument):
 
         # The angle value
         # Note that the x position gets converted from mm to m when read from the user file so we need to reverse this if X is now an angle
-        if(int(run_num) < 2217):
+        if int(run_num) < 2217:
             # Initial commisioning before run 2217 did not pay much attention to making sure the bench_rot value was meaningful
             xshift = -xbeam
             sanslog.notice("Setup move " + str(xshift*XSF) + " " + str(0.0) + " " + str(0.0))
@@ -1446,7 +1443,7 @@ class LARMOR(ISISInstrument):
             run_num = ws_ref.getRun().getLogData('run_number').value
         except:
             run_num = int(re.findall(r'\d+',str(ws_name))[-1])
-        if(int(run_num) >= 2217):
+        if int(run_num) >= 2217:
             try:
                 #logger.warning("Trying get_detector_log")
                 log = self.get_detector_log(ws_ref)
diff --git a/Code/Mantid/scripts/SANS/isis_reduction_steps.py b/Code/Mantid/scripts/SANS/isis_reduction_steps.py
index 65bf57953fed2fbf5700accf26ae28a7c81927c0..486272054841ec896f388cad23a67c33296f4aa8 100644
--- a/Code/Mantid/scripts/SANS/isis_reduction_steps.py
+++ b/Code/Mantid/scripts/SANS/isis_reduction_steps.py
@@ -21,7 +21,8 @@ from mantid.api import WorkspaceGroup, Workspace, IEventWorkspace
 from SANSUtility import (GetInstrumentDetails, MaskByBinRange,
                          isEventWorkspace, getFilePathFromWorkspace,
                          getWorkspaceReference, slice2histogram, getFileAndName,
-                         mask_detectors_with_masking_ws)
+                         mask_detectors_with_masking_ws, check_child_ws_for_name_and_type_for_added_eventdata,
+                         extract_child_ws_for_added_eventdata)
 import isis_instrument
 import isis_reducer
 from reducer_singleton import ReductionStep
@@ -53,7 +54,7 @@ class LoadRun(object):
             @param trans: set to true if the file is from a transmission run (default: False)
             @param reload: if to reload the workspace if it is already present
             @param entry: the entry number of the run, useful for multi-period files (default: load the entire file)
-    """
+        """
         super(LoadRun, self).__init__()
         self._data_file = run_spec
         self._is_trans = trans
@@ -146,15 +147,40 @@ class LoadRun(object):
 
         outWs = Load(self._data_file, **extra_options)
 
-        monitor_ws_name = workspace + "_monitors"
+        appendix = "_monitors"
 
-        if isinstance(outWs, IEventWorkspace):
-            LoadNexusMonitors(self._data_file, OutputWorkspace=monitor_ws_name)
-        else:
-            if monitor_ws_name in mtd:
-                DeleteWorkspace(monitor_ws_name)
+        # We need to check if we are dealing with a group workspace which is made up of added event data. Note that
+        # we can also have a group workspace which is associated with period data, which don't want to deal with here.
+
+        added_event_data_flag = False
+        if isinstance(outWs, WorkspaceGroup) and check_child_ws_for_name_and_type_for_added_eventdata(outWs):
+            if self._period != self.UNSET_PERIOD:
+                raise RuntimeError("Trying to use multiperiod and added eventdata. This is currently not supported.")
+            extract_child_ws_for_added_eventdata(outWs, appendix)
+            added_event_data_flag = True
+            # Reload the outWs, it has changed from a group workspace to an event workspace
+            outWs = mtd[workspace]
 
-        loader_name = outWs.getHistory().lastAlgorithm().getProperty('LoaderName').value
+        monitor_ws_name = workspace + appendix
+
+        if not added_event_data_flag:
+            if isinstance(outWs, IEventWorkspace):
+                try:
+                    LoadNexusMonitors(self._data_file, OutputWorkspace=monitor_ws_name)
+                except ValueError, details:
+                    sanslog.warning('The file does not contain monitors. \n' +
+                                    'The normalization might behave differently than you expect.\n'
+                                   ' Further details: ' + str(details) + '\n')
+            else:
+                if monitor_ws_name in mtd:
+                    DeleteWorkspace(monitor_ws_name)
+
+        loader_name = ''
+        try:
+            last_algorithm = outWs.getHistory().lastAlgorithm()
+            loader_name = last_algorithm.getProperty('LoaderName').value
+        except RuntimeError, details:
+            sanslog.warning('Tried to get a loader name. But it seems that there is no loader name. Further info: ' + str(details))
 
         if loader_name == 'LoadRaw':
             self._loadSampleDetails(workspace)
@@ -163,8 +189,10 @@ class LoadRun(object):
             outWs = mtd[self._leaveSinglePeriod(outWs.name(), self._period)]
 
         self.periods_in_file = self._find_workspace_num_periods(workspace)
+
         self._wksp_name = workspace
 
+
     def _get_workspace_name(self, entry_num=None):
         """
             Creates a name for the workspace that will contain the raw
@@ -1076,7 +1104,7 @@ class LoadSample(LoadRun):
 
     def execute(self, reducer, isSample):
         self._assignHelper(reducer)
-
+        
         if self.wksp_name == '':
             raise RuntimeError('Unable to load SANS sample run, cannot continue.')
 
diff --git a/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_OneRun.py b/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_OneRun.py
index 8ae81127207be15b6d7bff3d4f079f5d9f55bd07..d6d2ce7088f30d202d415c8f463a15509c8265eb 100644
--- a/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_OneRun.py
+++ b/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_OneRun.py
@@ -37,7 +37,6 @@
 
 import os
 import sys
-import shutil
 import time
 import ReduceDictionary
 sys.path.append("/opt/mantidnightly/bin")
@@ -210,7 +209,8 @@ if read_UB:
         uc_alpha = peaks_ws.sample().getOrientedLattice().alpha()
         uc_beta = peaks_ws.sample().getOrientedLattice().beta()
         uc_gamma = peaks_ws.sample().getOrientedLattice().gamma()
-        FindUBUsingLatticeParameters(PeaksWorkspace= peaks_ws,a=uc_a,b=uc_b,c=uc_c,alpha=uc_alpha,beta=uc_beta, gamma=uc_gamma,NumInitial=num_peaks_to_find,Tolerance=tolerance)
+        FindUBUsingLatticeParameters(PeaksWorkspace= peaks_ws,a=uc_a,b=uc_b,c=uc_c,alpha=uc_alpha,beta=uc_beta,
+                                     gamma=uc_gamma,NumInitial=num_peaks_to_find,Tolerance=tolerance)
 else:
   # Find a Niggli UB matrix that indexes the peaks in this run
     FindUBUsingFFT( PeaksWorkspace=peaks_ws, MinD=min_d, MaxD=max_d, Tolerance=tolerance )
@@ -224,10 +224,10 @@ IndexPeaks( PeaksWorkspace=peaks_ws, Tolerance=tolerance)
 #
 SaveIsawUB( InputWorkspace=peaks_ws,Filename=run_niggli_matrix_file )
 if output_nexus:
-	SaveNexus( InputWorkspace=peaks_ws, Filename=run_niggli_integrate_file )
+    SaveNexus( InputWorkspace=peaks_ws, Filename=run_niggli_integrate_file )
 else:
-	SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=False,
-               Filename=run_niggli_integrate_file )
+    SaveIsawPeaks(InputWorkspace=peaks_ws, AppendFile=False,
+                  Filename=run_niggli_integrate_file )
 
 #
 # Get complete list of peaks to be integrated and load the UB matrix into
@@ -335,10 +335,10 @@ elif use_cylindrical_integration:
 # result.
 #
 if output_nexus:
-	SaveNexus( InputWorkspace=peaks_ws, Filename=run_niggli_integrate_file )
+    SaveNexus( InputWorkspace=peaks_ws, Filename=run_niggli_integrate_file )
 else:
-	SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=False,
-               Filename=run_niggli_integrate_file )
+    SaveIsawPeaks(InputWorkspace=peaks_ws, AppendFile=False,
+                  Filename=run_niggli_integrate_file )
 
 # Print warning if user is trying to integrate using the cylindrical method and transorm the cell
 if use_cylindrical_integration:
@@ -362,12 +362,12 @@ else:
                       CellType=cell_type, Centering=centering,\
                       AllowPermutations=allow_perm,\
                       Apply=True, Tolerance=tolerance )
-	if output_nexus:
-        	SaveNexus( InputWorkspace=peaks_ws, Filename=run_conventional_integrate_file )
-        else:
-        	SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=False,\
-                   Filename=run_conventional_integrate_file )
-        SaveIsawUB( InputWorkspace=peaks_ws, Filename=run_conventional_matrix_file )
+    if output_nexus:
+        SaveNexus(InputWorkspace=peaks_ws, Filename=run_conventional_integrate_file )
+    else:
+        SaveIsawPeaks(InputWorkspace=peaks_ws, AppendFile=False,\
+                      Filename=run_conventional_integrate_file )
+        SaveIsawUB(InputWorkspace=peaks_ws, Filename=run_conventional_matrix_file )
 
 end_time = time.time()
 print '\nReduced run ' + str(run) + ' in ' + str(end_time - start_time) + ' sec'
diff --git a/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_Parallel.py b/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_Parallel.py
index 804358531b1d668af187c5aedeea8ff4958e5339..07130bdeca502b40ab328a9657db9ae12ace369e 100644
--- a/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_Parallel.py
+++ b/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_Parallel.py
@@ -174,7 +174,7 @@ if output_nexus:
         for item in candidates:
             if os.path.exists(item):
                 full_name = str(item)
-    
+
         if not full_name.endswith('nxs'):
             print "Exiting since the data_directory was not specified and"
             print "findnexus failed for event NeXus file: " + instrument_name + " " + str(run)
@@ -195,7 +195,7 @@ if not use_cylindrical_integration:
             peaks_ws = LoadIsawPeaks( Filename=one_run_file )
         if first_time:
             if UseFirstLattice and not read_UB:
-    # Find a UB (using FFT) for the first run to use in the FindUBUsingLatticeParameters
+                # Find a UB (using FFT) for the first run to use in the FindUBUsingLatticeParameters
                 FindUBUsingFFT( PeaksWorkspace=peaks_ws, MinD=min_d, MaxD=max_d, Tolerance=tolerance )
                 uc_a = peaks_ws.sample().getOrientedLattice().a()
                 uc_b = peaks_ws.sample().getOrientedLattice().b()
@@ -203,17 +203,17 @@ if not use_cylindrical_integration:
                 uc_alpha = peaks_ws.sample().getOrientedLattice().alpha()
                 uc_beta = peaks_ws.sample().getOrientedLattice().beta()
                 uc_gamma = peaks_ws.sample().getOrientedLattice().gamma()
-		if output_nexus:
-                    peaks_total = CombinePeaksWorkspaces(LHSWorkspace=peaks_total, RHSWorkspace=peaks_ws)
-                    SaveNexus( InputWorkspace=peaks_ws, Filename=niggli_integrate_file )
-		else:
-                    SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=False, Filename=niggli_integrate_file )
+            if output_nexus:
+                peaks_total = CombinePeaksWorkspaces(LHSWorkspace=peaks_total, RHSWorkspace=peaks_ws)
+                SaveNexus( InputWorkspace=peaks_ws, Filename=niggli_integrate_file )
+            else:
+                SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=False, Filename=niggli_integrate_file )
             first_time = False
         else:
-	    if output_nexus:
+            if output_nexus:
                 peaks_total = CombinePeaksWorkspaces(LHSWorkspace=peaks_total, RHSWorkspace=peaks_ws)
                 SaveNexus( InputWorkspace=peaks_total, Filename=niggli_integrate_file )
-	    else:
+            else:
                 SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=True, Filename=niggli_integrate_file )
 
 #
@@ -232,18 +232,21 @@ if not use_cylindrical_integration:
     if read_UB:
         LoadIsawUB(InputWorkspace=peaks_ws, Filename=UB_filename)
         if UseFirstLattice:
-      # Find UB using lattice parameters from the specified file
+            # Find UB using lattice parameters from the specified file
             uc_a = peaks_ws.sample().getOrientedLattice().a()
             uc_b = peaks_ws.sample().getOrientedLattice().b()
             uc_c = peaks_ws.sample().getOrientedLattice().c()
             uc_alpha = peaks_ws.sample().getOrientedLattice().alpha()
             uc_beta = peaks_ws.sample().getOrientedLattice().beta()
             uc_gamma = peaks_ws.sample().getOrientedLattice().gamma()
-            FindUBUsingLatticeParameters(PeaksWorkspace= peaks_ws,a=uc_a,b=uc_b,c=uc_c,alpha=uc_alpha,beta=uc_beta, gamma=uc_gamma,NumInitial=num_peaks_to_find,Tolerance=tolerance)
-  #OptimizeCrystalPlacement(PeaksWorkspace=peaks_ws,ModifiedPeaksWorkspace=peaks_ws,FitInfoTable='CrystalPlacement_info',MaxIndexingError=tolerance)
+            FindUBUsingLatticeParameters(PeaksWorkspace= peaks_ws,a=uc_a,b=uc_b,c=uc_c,alpha=uc_alpha,beta=uc_beta,
+                                         gamma=uc_gamma,NumInitial=num_peaks_to_find,Tolerance=tolerance)
+        #OptimizeCrystalPlacement(PeaksWorkspace=peaks_ws,ModifiedPeaksWorkspace=peaks_ws,
+        #                         FitInfoTable='CrystalPlacement_info',MaxIndexingError=tolerance)
     elif UseFirstLattice and not read_UB:
-    # Find UB using lattice parameters using the FFT results from first run if no UB file is specified
-        FindUBUsingLatticeParameters(PeaksWorkspace= peaks_ws,a=uc_a,b=uc_b,c=uc_c,alpha=uc_alpha,beta=uc_beta, gamma=uc_gamma,NumInitial=num_peaks_to_find,Tolerance=tolerance)
+        # Find UB using lattice parameters using the FFT results from first run if no UB file is specified
+        FindUBUsingLatticeParameters(PeaksWorkspace= peaks_ws,a=uc_a,b=uc_b,c=uc_c,alpha=uc_alpha,beta=uc_beta,
+                                     gamma=uc_gamma,NumInitial=num_peaks_to_find,Tolerance=tolerance)
     else:
         FindUBUsingFFT( PeaksWorkspace=peaks_ws, MinD=min_d, MaxD=max_d, Tolerance=tolerance )
 
@@ -296,7 +299,8 @@ if use_cylindrical_integration:
         filename = output_directory + '/' + instrument_name + '_' + r_num + '.profiles'
         input = open(filename, 'r')
         for line in input:
-            if line[0] == '0': break
+            if line[0] == '0':
+                break
         output.write(line)
         for line in input:
             output.write(line)
diff --git a/Code/Mantid/scripts/Vates/SXD_NaCl.py b/Code/Mantid/scripts/Vates/SXD_NaCl.py
index 409c422541ef57077e97118bd38bb25044530db3..90448f33ae5279bdce1e4fe3346b21b1dcc41991 100644
--- a/Code/Mantid/scripts/Vates/SXD_NaCl.py
+++ b/Code/Mantid/scripts/Vates/SXD_NaCl.py
@@ -17,7 +17,9 @@ Load(Filename='SXD23767.raw',OutputWorkspace='SXD23767',LoadMonitors='Exclude')
 #
 # A lower SplitThreshold, with a reasonable bound on the recursion depth, helps find weaker peaks at higher Q.
 #
-QLab = ConvertToDiffractionMDWorkspace(InputWorkspace='SXD23767', OutputDimensions='Q (lab frame)', SplitThreshold=50, LorentzCorrection='1',MaxRecursionDepth='13',Extents='-15,15,-15,15,-15,15')
+QLab = ConvertToDiffractionMDWorkspace(InputWorkspace='SXD23767', OutputDimensions='Q (lab frame)',
+                                       SplitThreshold=50, LorentzCorrection='1',
+                                       MaxRecursionDepth='13',Extents='-15,15,-15,15,-15,15')
 
 #
 #  NaCl has a relatively small unit cell, so the distance between peaks is relatively large.  Setting the PeakDistanceThreshold
@@ -44,11 +46,13 @@ if  use_fft:
     print '\nNiggli cell found from FindUBUsingFFT:'
 
 if use_cubic_lat_par:
-    FindUBUsingLatticeParameters(PeaksWorkspace=peaks_qLab, a=5.6402,b=5.6402,c=5.6402,alpha=90,beta=90,gamma=90,NumInitial=25,Tolerance=0.12)
+    FindUBUsingLatticeParameters(PeaksWorkspace=peaks_qLab, a=5.6402,b=5.6402,c=5.6402,
+                                 alpha=90,beta=90,gamma=90,NumInitial=25,Tolerance=0.12)
     print  '\nCubic cell found directly from FindUBUsingLatticeParameters'
 
 if use_Niggli_lat_par:
-    FindUBUsingLatticeParameters(PeaksWorkspace=peaks_qLab, a=3.9882,b=3.9882,c=3.9882,alpha=60,beta=60,gamma=60,NumInitial=25,Tolerance=0.12)
+    FindUBUsingLatticeParameters(PeaksWorkspace=peaks_qLab, a=3.9882,b=3.9882,c=3.9882,
+                                 alpha=60,beta=60,gamma=60,NumInitial=25,Tolerance=0.12)
     print '\nNiggli cell found from FindUBUsingLatticeParameters:'
 
 reportUnitCell(peaks_qLab)
@@ -59,7 +63,8 @@ if use_fft or use_Niggli_lat_par:
     ShowPossibleCells(PeaksWorkspace=peaks_qLab,MaxScalarError='0.5')
     SelectCellOfType(PeaksWorkspace=peaks_qLab, CellType='Cubic', Centering='F', Apply=True)
 
-peaks_qLab_Integrated = IntegratePeaksMD(InputWorkspace=QLab, PeaksWorkspace=peaks_qLab, PeakRadius=0.2, BackgroundInnerRadius=0.3, BackgroundOuterRadius=0.4)
+peaks_qLab_Integrated = IntegratePeaksMD(InputWorkspace=QLab, PeaksWorkspace=peaks_qLab, PeakRadius=0.2,
+                                         BackgroundInnerRadius=0.3, BackgroundOuterRadius=0.4)
 
 binned=BinMD(InputWorkspace=QLab,AlignedDim0='Q_lab_x,-15,15,200',AlignedDim1='Q_lab_y,-15,15,200',AlignedDim2='Q_lab_z,-15,15,200')
 
diff --git a/Code/Mantid/scripts/reduction/instruments/reflectometer/wks_utility.py b/Code/Mantid/scripts/reduction/instruments/reflectometer/wks_utility.py
index 707396dfa9f5ecb92dd68ae2531a09c04ae7cea4..b9dec721553ac63bdbeb835d613fe0b306a45bb4 100644
--- a/Code/Mantid/scripts/reduction/instruments/reflectometer/wks_utility.py
+++ b/Code/Mantid/scripts/reduction/instruments/reflectometer/wks_utility.py
@@ -1420,7 +1420,7 @@ def applyScalingFactor(tof_axis,
     file created by the sfCalculator procedure
     """
     isSFfound = False
-    
+
     #sf_file = 'NaN'
     if os.path.isfile(sf_file):
 
diff --git a/Code/Mantid/scripts/test/IndirectCommonTests.py b/Code/Mantid/scripts/test/IndirectCommonTests.py
index a0bbe462f14254221715448ab0b8b70d7269affa..b2dd6298d82e119d6b32171a1856a1cc0331dcb0 100644
--- a/Code/Mantid/scripts/test/IndirectCommonTests.py
+++ b/Code/Mantid/scripts/test/IndirectCommonTests.py
@@ -69,7 +69,7 @@ class IndirectCommonTests(unittest.TestCase):
 
     def test_getEFixed_failure(self):
         ws = CreateSampleWorkspace()
-        self.assertRaises(IndexError, indirect_common.getEfixed, ws.name())
+        self.assertRaises(ValueError, indirect_common.getEfixed, ws.name())
 
     def test_getDefaultWorkingDirectory(self):
         config['defaultsave.directory'] = os.path.expanduser('~')
diff --git a/Code/Mantid/scripts/test/SANSUtilitytests.py b/Code/Mantid/scripts/test/SANSUtilitytests.py
index 81ff7648cb097eb96adb4c448633106ab0a0ac38..132d16da42611101409b2a02ac1873bea3947f2f 100644
--- a/Code/Mantid/scripts/test/SANSUtilitytests.py
+++ b/Code/Mantid/scripts/test/SANSUtilitytests.py
@@ -1,52 +1,227 @@
+
 import unittest
+import re
+# Need to import mantid before we import SANSUtility
+import mantid
+from mantid.simpleapi import *
+from mantid.api import mtd, WorkspaceGroup
 import SANSUtility as su
+import re
+
+TEST_STRING_DATA = 'SANS2D0003434-add' + su.ADDED_EVENT_DATA_TAG
+TEST_STRING_MON = 'SANS2D0003434-add_monitors' + su.ADDED_EVENT_DATA_TAG
+
+TEST_STRING_DATA1 = TEST_STRING_DATA + '_1'
+TEST_STRING_MON1 = TEST_STRING_MON + '_1'
+
+TEST_STRING_DATA2 = TEST_STRING_DATA + '_2'
+TEST_STRING_MON2 = TEST_STRING_MON + '_2'
+
+TEST_STRING_DATA3 = TEST_STRING_DATA + '_3'
+TEST_STRING_MON3 = TEST_STRING_MON + '_3'
+
+def provide_group_workspace_for_added_event_data(event_ws_name, monitor_ws_name, out_ws_name):
+    CreateWorkspace(DataX = [1,2,3], DataY = [2,3,4], OutputWorkspace = monitor_ws_name)
+    CreateSampleWorkspace(WorkspaceType= 'Event', OutputWorkspace = event_ws_name)
+    GroupWorkspaces(InputWorkspaces = [event_ws_name, monitor_ws_name ], OutputWorkspace = out_ws_name)
+
+# This test does not pass and was not used before 1/4/2015. SansUtilitytests was disabled.
+
+#class TestSliceStringParser(unittest.TestCase):
+
+#    def checkValues(self, list1, list2):
+
+#        def _check_single_values( v1, v2):
+#            self.assertAlmostEqual(v1, v2)
+
+#        self.assertEqual(len(list1), len(list2))
+#        for v1,v2 in zip(list1, list2):
+#            start_1,stop_1 = v1
+#            start_2, stop_2 = v2
+#            _check_single_values(start_1, start_2)
+#            _check_single_values(stop_1, stop_2)
+
+#    def test_checkValues(self):
+#        """sanity check to ensure that the others will work correctly"""
+#        values = [  [[1,2],],
+#                  [[None, 3],[4, None]],
+#                 ]
+#        for singlevalues in values:
+#            self.checkValues(singlevalues, singlevalues)
+
+
+#    def test_parse_strings(self):
+#        inputs = { '1-2':[[1,2]],         # single period syntax  min < x < max
+#                   '1.3-5.6':[[1.3,5.6]], # float
+#                   '1-2,3-4':[[1,2],[3,4]],# more than one slice
+#                   '>1':[[1, -1]],       # just lower bound
+#                   '<5':[[-1, 5]],      # just upper bound
+#                   '<5,8-9': [[-1, 5], [8,9]],
+#                   '1:2:5': [[1,3], [3,5]] # sintax: start, step, stop
+#            }
+
+#        for (k, v) in inputs.items():
+#            self.checkValues(su.sliceParser(k),v)
+
+#    def test_accept_spaces(self):
+#        self.checkValues(su.sliceParser("1 - 2, 3 - 4"), [[1,2],[3,4]])
+
+#    def test_invalid_values_raise(self):
+#        invalid_strs = ["5>6", ":3:", "MAX<min"]
+#        for val in invalid_strs:
+#            self.assertRaises(SyntaxError, su.sliceParser, val)
+
+#    def test_empty_string_is_valid(self):
+#        self.checkValues(su.sliceParser(""), [[-1,-1]])
+
+class TestBundleAddedEventDataFilesToGroupWorkspaceFile(unittest.TestCase):
+    def _prepare_workspaces(self, names):
+        CreateSampleWorkspace(WorkspaceType = 'Event', OutputWorkspace = names[0])
+        CreateWorkspace(DataX = [1,1,1], DataY = [1,1,1], OutputWorkspace = names[1])
+
+        temp_save_dir = config['defaultsave.directory']
+        if (temp_save_dir == ''):
+            temp_save_dir = os.getcwd()
+
+        data_file_name = os.path.join(temp_save_dir, names[0] + '.nxs')
+        monitor_file_name = os.path.join(temp_save_dir, names[1] + '.nxs')
+
+        SaveNexusProcessed(InputWorkspace = names[0], Filename = data_file_name)
+        SaveNexusProcessed(InputWorkspace = names[1], Filename = monitor_file_name)
+
+        file_names = [data_file_name, monitor_file_name]
+
+        return file_names
+
+
+    def _cleanup_workspaces(self, names):
+        for name in names:
+            DeleteWorkspace(name)
+
+
+    def test_load_valid_added_event_data_and_monitor_file_produces_group_ws(self):
+        # Arrange
+        names = ['event_data', 'monitor']
+        file_names = self._prepare_workspaces(names = names)
+        self._cleanup_workspaces(names = names)
+
+        # Act
+        group_ws_name = 'g_ws'
+        output_group_file_name = su.bundle_added_event_data_as_group(file_names[0], file_names[1])
+
+        Load(Filename = output_group_file_name, OutputWorkspace = group_ws_name)
+        group_ws = mtd[group_ws_name]
+
+        # Assert
+        self.assertTrue(isinstance(group_ws, WorkspaceGroup))
+        self.assertEqual(group_ws.size(), 2)
+        self.assertTrue(os.path.exists(file_names[0])) # File for group workspace exists
+        self.assertFalse(os.path.exists(file_names[1]))  # File for monitors is deleted
+
+        # Clean up
+        ws_names_to_delete = []
+        for ws_name in mtd.getObjectNames():
+            if ws_name != group_ws_name:
+                ws_names_to_delete.append(str(ws_name))
+        self._cleanup_workspaces(names = ws_names_to_delete)
+
+        if os.path.exists(file_names[0]):
+            os.remove(file_names[0])
+
+
+class TestLoadingAddedEventWorkspaceNameParsing(unittest.TestCase):
+
+    def do_test_load_check(self, event_name, monitor_name):
+        out_name = 'out_ws'
+        provide_group_workspace_for_added_event_data(event_ws_name = event_name, monitor_ws_name = monitor_name, out_ws_name = out_name)
+        out_ws = mtd[out_name]
+        self.assertTrue(su.check_child_ws_for_name_and_type_for_added_eventdata(out_ws))
+        DeleteWorkspace(out_ws)
+
+    def test_check_regex_for_data(self):
+        # Check when there is no special ending
+        self.assertNotEqual(None, re.search(su.REG_DATA_NAME, TEST_STRING_DATA))
+        # Check when there is a _1 ending
+        self.assertNotEqual(None, re.search(su.REG_DATA_NAME, TEST_STRING_DATA1))
+        # Check when there is a _2 ending
+        self.assertNotEqual(None, re.search(su.REG_DATA_NAME, TEST_STRING_DATA2))
+        # Check when there is a multiple ending
+        self.assertNotEqual(None, re.search(su.REG_DATA_NAME, TEST_STRING_DATA3))
+
+
+    def test_check_regex_for_data_monitors(self):
+        # Check when there is no special ending
+        self.assertNotEqual(None, re.search(su.REG_DATA_MONITORS_NAME, TEST_STRING_MON))
+        # Check when there is a _1 ending
+        self.assertNotEqual(None, re.search(su.REG_DATA_MONITORS_NAME, TEST_STRING_MON1))
+        # Check when there is a _2 ending
+        self.assertNotEqual(None, re.search(su.REG_DATA_MONITORS_NAME, TEST_STRING_MON2))
+        # Check when there is a multiple ending
+        self.assertNotEqual(None, re.search(su.REG_DATA_MONITORS_NAME, TEST_STRING_MON3))
+
+    def test_regexes_do_not_clash(self):
+        # Check when there is no special ending
+        self.assertEqual(None, re.search(su.REG_DATA_NAME, TEST_STRING_MON)) 
+        self.assertEqual(None, re.search(su.REG_DATA_MONITORS_NAME, TEST_STRING_DATA))
+        # Check when there is a _1 ending
+        self.assertEqual(None, re.search(su.REG_DATA_NAME, TEST_STRING_MON1)) 
+        self.assertEqual(None, re.search(su.REG_DATA_MONITORS_NAME, TEST_STRING_DATA1))
+        # Check when there is a _2 ending
+        self.assertEqual(None, re.search(su.REG_DATA_NAME, TEST_STRING_MON2)) 
+        self.assertEqual(None, re.search(su.REG_DATA_MONITORS_NAME, TEST_STRING_DATA2))
+        # Check when there is a multiple ending
+        self.assertEqual(None, re.search(su.REG_DATA_NAME, TEST_STRING_MON3)) 
+        self.assertEqual(None, re.search(su.REG_DATA_MONITORS_NAME, TEST_STRING_DATA3))
+    
+    def test_check_child_file_names_for_valid_names(self):
+        # Check when there is no special ending
+        event_name = TEST_STRING_DATA
+        monitor_name = TEST_STRING_MON
+        self.do_test_load_check(event_name = event_name, monitor_name = monitor_name)
+
+        # Check when there is a _1 ending
+        event_name1 = TEST_STRING_DATA1
+        monitor_name1 = TEST_STRING_MON1
+        self.do_test_load_check(event_name = event_name1, monitor_name = monitor_name1)
+
+        # Check when there is a _2 ending
+        event_name2 = TEST_STRING_DATA2
+        monitor_name2 = TEST_STRING_MON2
+        self.do_test_load_check(event_name = event_name2, monitor_name = monitor_name2)
 
-class TestSliceStringParser(unittest.TestCase):
+        # Check when there is a multiple ending
+        event_name3 = TEST_STRING_DATA3
+        monitor_name3 = TEST_STRING_MON3
+        self.do_test_load_check(event_name = event_name3, monitor_name = monitor_name3)
 
-    def checkValues(self, list1, list2):
 
-        def _check_single_values( v1, v2):
-            self.assertAlmostEqual(v1, v2)
+class TestLoadingAddedEventWorkspaceExtraction(unittest.TestCase):
+    _appendix = '_monitors'
 
-        self.assertEqual(len(list1), len(list2))
-        for v1,v2 in zip(list1, list2):
-            start_1,stop_1 = v1
-            start_2, stop_2 = v2
-            _check_single_values(start_1, start_2)
-            _check_single_values(stop_1, stop_2)
+    def do_test_extraction(self, event_name, monitor_name):
+        out_ws_name = 'out_group'
+        event_name_expect = out_ws_name
+        monitor_name_expect = out_ws_name + self._appendix
 
-    def test_checkValues(self):
-        """sanity check to ensure that the others will work correctly"""
-        values = [  [[1,2],],
-                  [[None, 3],[4, None]],
-                 ]
-        for singlevalues in values:
-            self.checkValues(singlevalues, singlevalues)
+        provide_group_workspace_for_added_event_data(event_ws_name = event_name, monitor_ws_name = monitor_name, out_ws_name = out_ws_name)
+        out_ws_group = mtd[out_ws_name]
+        
+        # Act
+        su.extract_child_ws_for_added_eventdata(out_ws_group, self._appendix)
 
+        # Assert
 
-    def test_parse_strings(self):
-        inputs = { '1-2':[[1,2]],         # single period syntax  min < x < max
-                   '1.3-5.6':[[1.3,5.6]], # float
-                   '1-2,3-4':[[1,2],[3,4]],# more than one slice
-                   '>1':[[1, -1]],       # just lower bound
-                   '<5':[[-1, 5]],      # just upper bound
-                   '<5,8-9': [[-1, 5], [8,9]],
-                   '1:2:5': [[1,3], [3,5]] # sintax: start, step, stop
-            }
+        self.assertTrue(event_name_expect in mtd)
+        self.assertTrue(monitor_name_expect in mtd)
 
-        for (k, v) in inputs.items():
-            self.checkValues(su.sliceParser(k),v)
+        DeleteWorkspace(event_name_expect)
+        DeleteWorkspace(monitor_name_expect)
 
-    def test_accept_spaces(self):
-        self.checkValues(su.sliceParser("1 - 2, 3 - 4"), [[1,2],[3,4]])
 
-    def test_invalid_values_raise(self):
-        invalid_strs = ["5>6", ":3:", "MAX<min"]
-        for val in invalid_strs:
-            self.assertRaises(SyntaxError, su.sliceParser, val)
+    def test_extract_data_and_monitor_child_ws(self):
+        # Check when there is no special ending
+        self.do_test_extraction(TEST_STRING_DATA, TEST_STRING_MON)
 
-    def test_empty_string_is_valid(self):
-        self.checkValues(su.sliceParser(""), [[-1,-1]])
 
 if __name__ == "__main__":
     unittest.main()
diff --git a/Code/Tools/Pylint/pylint.cfg b/Code/Tools/Pylint/pylint.cfg
index 45bc53816b56ed31ae0c707a46246217cedc1172..eec53d4f7b22bdfd67bc5e8f1c30b956fa6be060 100644
--- a/Code/Tools/Pylint/pylint.cfg
+++ b/Code/Tools/Pylint/pylint.cfg
@@ -45,8 +45,9 @@ load-plugins=
 #    C0326 - Spaces around equality and commas
 #    W0401 - Wildcard imports
 #    R0201 - Method could be used as a function. All algorithms do this in the category method
+#    R0801 - Similar lines in different files
 #
-disable=W0142,I0011,F0401,W0614,E0602,C0111,C0326,W0401,R0201
+disable=W0142,I0011,F0401,W0614,E0602,C0111,C0326,W0401,R0201,R0801
 
 
 [REPORTS]
diff --git a/Code/Tools/Valgrind/DataObjectsTest.supp b/Code/Tools/Valgrind/DataObjectsTest.supp
index 847b04c36f429a4253f6fa52eb1c460deec29ad5..7bd99af4a73ba326bbc5c4d7ed2714450d11aa7b 100644
--- a/Code/Tools/Valgrind/DataObjectsTest.supp
+++ b/Code/Tools/Valgrind/DataObjectsTest.supp
@@ -7,4 +7,47 @@
    fun:_ZN6Mantid11DataObjects14parallel_sort2INS0_8TofEventEEEvRSt6vectorIT_SaIS4_EE
    ...
 }
-
+{
+   <Leak_within_nexus_library>
+   Memcheck:Leak
+   ...
+   ...
+   fun:_ZN5NeXus4File11getNextAttrEv
+   fun:_ZN5NeXus4File7hasAttrERKSs
+   fun:_ZN6Mantid11DataObjects13MDBoxFlatTree21createOrOpenMDWSgroupERKSsRiS3_bRb
+   ...
+}
+{
+   <HDF5_write>
+   Memcheck:Param
+   write(buf)
+   ...
+   fun:H5FD_write
+   ...
+   fun:nxiflush_
+   fun:_ZN5NeXus4File5flushEv
+   fun:_ZNK6Mantid11DataObjects20BoxControllerNeXusIO9flushDataEv
+   fun:_ZNK6Mantid11DataObjects13MDBoxSaveable9flushDataEv
+   fun:_ZN6Mantid6Kernel10DiskBuffer15writeOldObjectsEv
+   fun:_ZN6Mantid6Kernel10DiskBuffer10flushCacheEv
+   fun:_ZN17MDBoxSaveableTest46test_fileBackEnd_nonConst_EventListChangesSizeEv
+}
+{
+   <gomp_false_positive_leak_workspace2d>
+   Memcheck:Leak
+   fun:calloc
+   fun:_dl_allocate_tls
+   ...
+   fun:_ZNK6Mantid3API15MatrixWorkspace20getIntegratedSpectraERSt6vectorIdSaIdEEddb
+   fun:_ZN15Workspace2DTest33testIntegrateSpectra_entire_rangeEv
+   fun:_ZN71TestDescription_suite_Workspace2DTest_testIntegrateSpectra_entire_range7runTestEv
+}
+{
+   <gomp_false_positive_leak_mdgridboxtest>
+   Memcheck:Leak
+   fun:calloc
+   fun:_dl_allocate_tls
+   ...
+   fun:_ZN13MDGridBoxTest28do_test_addEvents_inParallelEPN6Mantid6Kernel15ThreadSchedulerE
+   fun:_ZN13MDGridBoxTest25test_addEvents_inParallelEv
+}
diff --git a/Code/Tools/scripts/extractAlgorithmNames.py b/Code/Tools/scripts/extractAlgorithmNames.py
new file mode 100644
index 0000000000000000000000000000000000000000..05120ece167861601920362aa08ca0105a6bda7e
--- /dev/null
+++ b/Code/Tools/scripts/extractAlgorithmNames.py
@@ -0,0 +1,22 @@
+# simply just print out all algorithm names in a directory which can be piped
+# to a file
+
+import string, os, re
+
+import glob
+import mmap
+
+
+os.chdir("PythonInterface/plugins/algorithms/WorkflowAlgorithms")
+for file in glob.glob("*.py"):
+    #print file
+    if 'PythonAlgorithm' in open(file).read():
+        print file
+
+
+#os.chdir("LiveData/src")
+#for file in glob.glob("*.cpp"):
+#    #print file
+#    if 'DECLARE_ALGORITHM' in open(file).read():
+#        print file
+
diff --git a/Code/Tools/scripts/extractAuthorNamesFromGit.py b/Code/Tools/scripts/extractAuthorNamesFromGit.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee6bf1e2eceb5ff853dc9c5baa93a86814ee91d0
--- /dev/null
+++ b/Code/Tools/scripts/extractAuthorNamesFromGit.py
@@ -0,0 +1,58 @@
+# This python script is run after running extractAlgorithmNames.py, where
+# the output of that script is saved to a *.txt
+#
+# This script then query github for author of each algorithm. This script
+# was original used in connection with creating usage examples for algorithms
+# and creating an algorithm list for each developer to have a go at
+
+import string, os, re
+
+import subprocess
+
+
+project = 'PyWorkflowAlg'
+algorithmList = 'allAlgorithmsIn'+project+'.txt'
+
+allAlgs = [line.strip() for line in open(algorithmList)]
+#os.chdir(project+"/src")
+os.chdir('PythonInterface/plugins/algorithms/WorkflowAlgorithms')
+for line in allAlgs:
+    #print line
+    fullline = line    
+    args = [
+        'git', 'log',
+        '--pretty=short',
+        '--format="%aN"',
+        '--follow',
+        line
+    ]
+
+    authors = subprocess.check_output(args).replace('"', '').split('\n')
+    authors = set(authors)
+    authors = authors - set([''])
+    
+    for author in authors:
+        #print author
+        fullline = fullline + ", " + author
+	
+    print fullline
+
+#line = 'GroupWorkspaces.cpp'
+#fullline = line
+#args = [
+#        'git', 'log',
+#        '--pretty=short',
+#        '--format="%aN"',
+#        '--follow',
+#        line
+#]
+
+#authors = subprocess.check_output(args).replace('"', '').split('\n')
+#authors = set(authors)
+#authors = authors - set([''])
+
+#for author in authors:
+    #print author
+#    fullline = fullline + ", " + author
+	
+#print fullline