diff --git a/Code/Mantid/Build/CMake/Coveralls.cmake b/Code/Mantid/Build/CMake/Coveralls.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..b6a93eb5f5923f10d23ca235748731bfb076fc32
--- /dev/null
+++ b/Code/Mantid/Build/CMake/Coveralls.cmake
@@ -0,0 +1,125 @@
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in all
+# copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+# SOFTWARE.
+#
+# Copyright (C) 2014 Joakim Söderberg <joakim.soderberg@gmail.com>
+#
+
+
+#
+# Param _COVERAGE_SRCS	A list of source files that coverage should be collected for.
+# Param _COVERALLS_UPLOAD Upload the result to coveralls?
+#
+function(coveralls_setup _COVERAGE_SRCS _COVERALLS_UPLOAD)
+
+	if (ARGC GREATER 2)
+		set(_CMAKE_SCRIPT_PATH ${ARGN})
+		message("Coveralls: Using alternate CMake script dir: ${_CMAKE_SCRIPT_PATH}")
+	else()
+		set(_CMAKE_SCRIPT_PATH ${PROJECT_SOURCE_DIR}/cmake)
+	endif()
+
+	if (NOT EXISTS "${_CMAKE_SCRIPT_PATH}/CoverallsClear.cmake")
+		message(FATAL_ERROR "Coveralls: Missing ${_CMAKE_SCRIPT_PATH}/CoverallsClear.cmake")
+	endif()
+
+	if (NOT EXISTS "${_CMAKE_SCRIPT_PATH}/CoverallsGenerateGcov.py")
+		message(FATAL_ERROR "Coveralls: Missing ${_CMAKE_SCRIPT_PATH}/CoverallsGenerateGcov.py")
+	endif()
+
+        #pass name to a file instead of a list of every source.
+	set(COVERAGE_SRCS ${_COVERAGE_SRCS})
+
+	set(COVERALLS_FILE ${PROJECT_BINARY_DIR}/coveralls.json)
+
+        find_package(Git)
+        execute_process(
+            COMMAND ${GIT_EXECUTABLE} rev-parse --show-toplevel
+            WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
+            OUTPUT_VARIABLE PROJECT_ROOT
+            OUTPUT_STRIP_TRAILING_WHITESPACE
+        )
+
+        INCLUDE(FindPythonInterp)
+	add_custom_target(coveralls_generate
+
+		# Zero the coverage counters.
+		COMMAND ${CMAKE_COMMAND}
+				-P "${_CMAKE_SCRIPT_PATH}/CoverallsClear.cmake"
+
+		# Run regression tests. Continue even if tests fail.
+		COMMAND ${CMAKE_CTEST_COMMAND} --output-on-failure || true
+
+		# Generate Gcov and translate it into coveralls JSON.
+		# We do this by executing an external CMake script.
+		# (We don't want this to run at CMake generation time, but after compilation and everything has run).
+		COMMAND ${PYTHON_EXECUTABLE} 
+                                ${_CMAKE_SCRIPT_PATH}/CoverallsGenerateGcov.py
+				--COVERAGE_SRCS_FILE="${COVERAGE_SRCS}"
+				--COVERALLS_OUTPUT_FILE="${COVERALLS_FILE}"
+				--COV_PATH="${PROJECT_BINARY_DIR}"
+				--PROJECT_ROOT="${PROJECT_ROOT}"
+
+		WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
+		COMMENT "Generating coveralls output..."
+		)
+
+	if (_COVERALLS_UPLOAD)
+		message("COVERALLS UPLOAD: ON")
+
+		find_program(CURL_EXECUTABLE curl)
+
+		if (NOT CURL_EXECUTABLE)
+			message(FATAL_ERROR "Coveralls: curl not found! Aborting")
+		endif()
+
+		add_custom_target(coveralls_upload
+			# Upload the JSON to coveralls.
+			COMMAND ${CURL_EXECUTABLE}
+					-S -F json_file=@${COVERALLS_FILE}
+					https://coveralls.io/api/v1/jobs
+
+			DEPENDS coveralls_generate
+
+			WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
+			COMMENT "Uploading coveralls output...")
+
+		add_custom_target(coveralls DEPENDS coveralls_upload)
+	else()
+		message("COVERALLS UPLOAD: OFF")
+		add_custom_target(coveralls DEPENDS coveralls_generate)
+	endif()
+
+endfunction()
+
+macro(coveralls_turn_on_coverage)
+	if(NOT (CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX)
+		AND (NOT "${CMAKE_C_COMPILER_ID}" STREQUAL "Clang"))
+		message(FATAL_ERROR "Coveralls: Compiler ${CMAKE_C_COMPILER_ID} is not GNU gcc! Aborting... You can set this on the command line using CC=/usr/bin/gcc CXX=/usr/bin/g++ cmake <options> ..")
+	endif()
+
+	if(NOT CMAKE_BUILD_TYPE STREQUAL "Debug")
+		message(FATAL_ERROR "Coveralls: Code coverage results with an optimised (non-Debug) build may be misleading! Add -DCMAKE_BUILD_TYPE=Debug")
+	endif()
+
+	set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -O0 -fprofile-arcs -ftest-coverage")
+	set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -O0 -fprofile-arcs -ftest-coverage")
+endmacro()
+
+
+
diff --git a/Code/Mantid/Build/CMake/CoverallsClear.cmake b/Code/Mantid/Build/CMake/CoverallsClear.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..eb68695a2b1fce4ea197f5be588379d13e3c2fb7
--- /dev/null
+++ b/Code/Mantid/Build/CMake/CoverallsClear.cmake
@@ -0,0 +1,24 @@
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in all
+# copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+# SOFTWARE.
+#
+# Copyright (C) 2014 Joakim Söderberg <joakim.soderberg@gmail.com>
+#
+
+file(REMOVE_RECURSE ${PROJECT_BINARY_DIR}/*.gcda)
+
diff --git a/Code/Mantid/Build/CMake/CoverallsGenerateGcov.py b/Code/Mantid/Build/CMake/CoverallsGenerateGcov.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f45783a0f546f2883e0011ff4355e8c1359a23c
--- /dev/null
+++ b/Code/Mantid/Build/CMake/CoverallsGenerateGcov.py
@@ -0,0 +1,145 @@
+import json
+import os
+import sys
+import getopt
+import subprocess
+import re
+import copy
+import hashlib
+
+def getBranchName(directory):
+    """Returns the name of the current git branch"""
+    return subprocess.check_output(["git","rev-parse","--abbrev-ref","HEAD"],cwd=directory).strip()
+
+def getRemotes(directory):
+    """Returns list of remote git repositories"""
+    gitRemoteOutput = subprocess.check_output(['git','remote','-v'],cwd=directory)
+    remotes = []
+    for line in gitRemoteOutput.splitlines(): 
+        if '(fetch)' in line:
+            splitLine = line.split();
+            remotes.append({'name': splitLine[0].strip(), 'url': splitLine[1].strip()})
+    return remotes
+
+def gitLogValue(format,directory):
+    """Returns git log value specified by format"""
+    return subprocess.check_output(["git","log","-1","--pretty=format:%"+format],cwd=directory).strip()
+
+def getAllFilesWithExtension(directory,extension):
+    """Recursively return a list of all files in directory with specified extension"""
+    filesWithExtension = []
+    for root, dirs, files in os.walk(directory):
+        for file in files:
+            if file.endswith(extension):
+                 filesWithExtension.append(os.path.realpath(os.path.join(root, file)))
+    return filesWithExtension
+
+def getSourcePathFromGcovFile(gcovFilename):
+    """Return the source path corresponding to a .gcov file"""
+    gcovPath,gcovFilenameWithExtension = os.path.split(gcovFilename)
+    srcFilename = re.sub(".gcov$","",gcovFilenameWithExtension)  
+    return re.sub("#","/",srcFilename)
+
+def main(argv):
+    arguments = ['COVERAGE_SRCS_FILE=','COVERALLS_OUTPUT_FILE=','COV_PATH=','PROJECT_ROOT='] 
+    COVERAGE_SRCS_FILE=None
+    COVERALLS_OUTPUT_FILE=None
+    COV_PATH=None
+    PROJECT_ROOT=None
+    optlist, args = getopt.getopt(argv,'',arguments)
+
+    for o, a in optlist:
+        if o == "--COVERAGE_SRCS_FILE":
+            COVERAGE_SRCS_FILE=a
+        elif o == "--COVERALLS_OUTPUT_FILE":
+            COVERALLS_OUTPUT_FILE=a
+        elif o == "--COV_PATH":
+            COV_PATH=a
+        elif o == "--PROJECT_ROOT":
+            PROJECT_ROOT=a
+        else:
+            assert False, "unhandled option"
+
+    if COVERAGE_SRCS_FILE == None:
+        assert False, "COVERAGE_SRCS_FILE is not defined"
+    if COVERALLS_OUTPUT_FILE==None:
+        assert False, "COVERALLS_OUTPUT_FILE is not defined"
+    if COV_PATH==None:
+        assert False, "COV_PATH is not defined"
+    if PROJECT_ROOT==None:
+        assert False, "PROJECT_ROOT is not defined"
+
+    gcdaAllFiles = getAllFilesWithExtension(COV_PATH,".gcda")
+    for gcdaFile in gcdaAllFiles:
+        gcdaDirectory = os.path.dirname(gcdaFile)
+        subprocess.check_call(["gcov","-p","-o",gcdaDirectory,gcdaFile],cwd=COV_PATH)
+
+    gcovAllFiles = getAllFilesWithExtension(COV_PATH,".gcov")
+
+    sourcesToCheck = [line.strip() for line in open(COVERAGE_SRCS_FILE, 'r')]
+
+    gcovCheckedFiles = []
+    uncheckedSources = sourcesToCheck
+    for gcovFile in gcovAllFiles:
+        sourceWithPath = getSourcePathFromGcovFile(gcovFile)
+        if sourceWithPath in sourcesToCheck:
+            print "YES: ",sourceWithPath.strip()," WAS FOUND"
+            gcovCheckedFiles.append(gcovFile)
+            uncheckedSources.remove(sourceWithPath)
+        else:
+            print "NO: ",sourceWithPath.strip()," WAS NOT FOUND"
+
+    coverageList = []
+    for gcovFilename in gcovCheckedFiles:
+        fileCoverage = {}
+        #get name for json file
+        sourceWithPath = getSourcePathFromGcovFile(gcovFilename)
+        fileCoverage['name'] = os.path.relpath(sourceWithPath,PROJECT_ROOT)
+        print "Generating JSON file for "+fileCoverage['name']    
+        fileCoverage['source_digest'] = hashlib.md5(open(sourceWithPath, 'rb').read()).hexdigest()
+        lineCoverage = []
+        gcovFile = open(gcovFilename,'r')
+        for line in gcovFile:
+            line = [i.strip() for i in line.split(':')]
+            lineNumber = int(line[1])
+            if lineNumber != 0:
+                if line[0] == '#####':
+                    lineCoverage.append(0)
+                elif line[0] == '-':
+                    lineCoverage.append(None)
+                else: 
+                    lineCoverage.append(int(line[0]))
+                if lineNumber != len(lineCoverage):
+                    raise RuntimeError['line_number does not match len(array)']
+        gcovFile.close()
+        fileCoverage['coverage'] = lineCoverage
+        coverageList.append(copy.deepcopy(fileCoverage))
+
+    for uncheckedFilename in uncheckedSources:
+        fileCoverage = {}
+        fileCoverage['name'] = os.path.relpath(uncheckedFilename,PROJECT_ROOT)
+        fileCoverage['source_digest'] = hashlib.md5(open(uncheckedFilename, 'rb').read()).hexdigest()
+        lineCoverage =  []
+        uncheckedFile = open(uncheckedFilename,'r')
+        for line in uncheckedFile:
+            lineCoverage.append(0)
+        uncheckedFile.close()
+        fileCoverage['coverage'] = lineCoverage
+        coverageList.append(copy.deepcopy(fileCoverage))
+
+    coverallsOutput = {}
+    coverallsOutput['repo_token'] = os.environ.get('COVERALLS_REPO_TOKEN')
+    coverallsOutput['source_files'] = coverageList
+
+    head = {'id':gitLogValue('H',PROJECT_ROOT),'author_name':gitLogValue('an',PROJECT_ROOT), \
+            'author_email':gitLogValue('ae',PROJECT_ROOT),'committer_name':gitLogValue('cn',PROJECT_ROOT), \
+            'committer_email':gitLogValue('ce',PROJECT_ROOT), 'message':gitLogValue('B',PROJECT_ROOT)} 
+
+    gitDict = {'head':head,'branch':getBranchName(PROJECT_ROOT),'remotes':getRemotes(COV_PATH)}
+    coverallsOutput['git'] = gitDict
+
+    with open(COVERALLS_OUTPUT_FILE, 'w') as outfile:
+        json.dump(coverallsOutput,outfile,indent=4)
+
+if __name__ == "__main__":
+    main(sys.argv[1:])
diff --git a/Code/Mantid/CMakeLists.txt b/Code/Mantid/CMakeLists.txt
index 567d60082df155c7f69ff4a82b10497d8bb989bd..a1e87c99bb9148f03e2db88253e8fcd265dd2e65 100644
--- a/Code/Mantid/CMakeLists.txt
+++ b/Code/Mantid/CMakeLists.txt
@@ -95,6 +95,14 @@ IF (${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
 
 ENDIF()
 
+# We probably don't want this to run on every build.
+option(COVERALLS "Generate coveralls data" OFF)
+
+if (COVERALLS)
+    include(Coveralls)
+    coveralls_turn_on_coverage()
+endif()
+
 ###########################################################################
 # Call our setup script
 ###########################################################################
@@ -195,6 +203,23 @@ add_subdirectory ( docs )
 # System test data target
 add_subdirectory ( Testing/SystemTests/scripts )
 
+if (COVERALLS)
+  get_property(ALL_SRCS GLOBAL PROPERTY COVERAGE_SRCS)
+        set(SRCS_FILE "")
+        foreach (SRC ${ALL_SRCS})
+                set(SRCS_FILE "${SRCS_FILE}\n${SRC}")
+        endforeach()
+        #remove initial \n
+        string(SUBSTRING ${SRCS_FILE} 1 -1 SRCS_FILE)
+  set( SRCS_FILENAME "${CMAKE_CURRENT_BINARY_DIR}/sources.txt") 
+  file(WRITE ${SRCS_FILENAME} ${SRCS_FILE})
+  coveralls_setup(
+    ${SRCS_FILENAME}
+    OFF
+    "${CMAKE_SOURCE_DIR}/Build/CMake"
+  )
+endif ()
+
 ###########################################################################
 # Installation settings
 ###########################################################################
diff --git a/Code/Mantid/Framework/API/CMakeLists.txt b/Code/Mantid/Framework/API/CMakeLists.txt
index 363257c25e21761c1d8dfe92655f4c54f2676bd1..9db3514d3b5a3463b95295ac47a245458694074d 100644
--- a/Code/Mantid/Framework/API/CMakeLists.txt
+++ b/Code/Mantid/Framework/API/CMakeLists.txt
@@ -403,6 +403,11 @@ set ( GMOCK_TEST_FILES
 	MatrixWorkspaceTest.h
 )
 
+if (COVERALLS)
+    foreach( loop_var ${SRC_FILES} ${INC_FILES} )
+      set_property(GLOBAL APPEND PROPERTY COVERAGE_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/${loop_var}")
+    endforeach(loop_var)
+endif()
 
 if(UNITY_BUILD)
   include(UnityBuild)
diff --git a/Code/Mantid/Framework/API/inc/MantidAPI/IMDHistoWorkspace.h b/Code/Mantid/Framework/API/inc/MantidAPI/IMDHistoWorkspace.h
index cc7c014a382a07ff9bf27bc15cebb1f03703d5b2..91ef362ddae909c27264ff45e168d09574bf613b 100644
--- a/Code/Mantid/Framework/API/inc/MantidAPI/IMDHistoWorkspace.h
+++ b/Code/Mantid/Framework/API/inc/MantidAPI/IMDHistoWorkspace.h
@@ -93,6 +93,7 @@ public:
 
   virtual boost::shared_ptr<IMDHistoWorkspace> clone() const = 0;
 
+
 protected:
   virtual const std::string toString() const;
 };
diff --git a/Code/Mantid/Framework/API/inc/MantidAPI/IMDNode.h b/Code/Mantid/Framework/API/inc/MantidAPI/IMDNode.h
index 1d8579b35fae7800f8e6a3aa2e34f44e64e1d290..b04cf2042fbc0134e08f4181b2cd8b26dfd5ad0c 100644
--- a/Code/Mantid/Framework/API/inc/MantidAPI/IMDNode.h
+++ b/Code/Mantid/Framework/API/inc/MantidAPI/IMDNode.h
@@ -279,6 +279,11 @@ public:
   // to avoid casting (which need also the number of dimensions) method say if
   // Node is a box. if not, it is gridbox
   virtual bool isBox() const = 0;
+
+  virtual signal_t getSignalByNEvents() const {
+    return this->getSignal()/static_cast<signal_t>(this->getNPoints());
+  }
+
   // ----------------------------- Helper Methods
   // --------------------------------------------------------
   //-----------------------------------------------------------------------------------------------
diff --git a/Code/Mantid/Framework/API/inc/MantidAPI/IMDWorkspace.h b/Code/Mantid/Framework/API/inc/MantidAPI/IMDWorkspace.h
index 35203727852cbdc1dbf5deed99311f12fe2abd61..664b55423a3c632adf1c1d4a2814d48095d01557 100644
--- a/Code/Mantid/Framework/API/inc/MantidAPI/IMDWorkspace.h
+++ b/Code/Mantid/Framework/API/inc/MantidAPI/IMDWorkspace.h
@@ -130,6 +130,9 @@ public:
         "This method is not generally implemented ");
   }
 
+  // Preferred normalization to use for display
+  virtual MDNormalization displayNormalization() const;
+
 protected:
   virtual const std::string toString() const;
 };
diff --git a/Code/Mantid/Framework/API/src/Algorithm.cpp b/Code/Mantid/Framework/API/src/Algorithm.cpp
index 878f4b3abe717291ca545ce5da93526e912e0b94..f66d32bd923940545f6f4d40872adb40254a90ad 100644
--- a/Code/Mantid/Framework/API/src/Algorithm.cpp
+++ b/Code/Mantid/Framework/API/src/Algorithm.cpp
@@ -1305,27 +1305,34 @@ bool Algorithm::processGroups() {
         outputBaseName += ws->name();
 
         // Set the property using the name of that workspace
-        Property *prop = dynamic_cast<Property *>(m_inputWorkspaceProps[iwp]);
-        alg->setPropertyValue(prop->name(), ws->name());
+        if (Property *prop = dynamic_cast<Property *>(m_inputWorkspaceProps[iwp])) {
+          alg->setPropertyValue(prop->name(), ws->name());
+        } else {
+          throw std::logic_error(
+              "Found a Workspace property which doesn't inherit from Property.");
+        }
       } // not an empty (i.e. optional) input
     }   // for each InputWorkspace property
 
     std::vector<std::string> outputWSNames(m_pureOutputWorkspaceProps.size());
     // ---------- Set all the output workspaces ----------------------------
     for (size_t owp = 0; owp < m_pureOutputWorkspaceProps.size(); owp++) {
-      Property *prop =
-          dynamic_cast<Property *>(m_pureOutputWorkspaceProps[owp]);
-
-      // Default name = "in1_in2_out"
-      std::string outName = outputBaseName + "_" + prop->value();
-      // Except if all inputs had similar names, then the name is "out_1"
-      if (m_groupsHaveSimilarNames)
-        outName = prop->value() + "_" + Strings::toString(entry + 1);
-
-      // Set in the output
-      alg->setPropertyValue(prop->name(), outName);
-
-      outputWSNames[owp] = outName;
+      if (Property *prop =
+              dynamic_cast<Property *>(m_pureOutputWorkspaceProps[owp])) {
+        // Default name = "in1_in2_out"
+        std::string outName = outputBaseName + "_" + prop->value();
+        // Except if all inputs had similar names, then the name is "out_1"
+        if (m_groupsHaveSimilarNames)
+          outName = prop->value() + "_" + Strings::toString(entry + 1);
+
+        // Set in the output
+        alg->setPropertyValue(prop->name(), outName);
+
+        outputWSNames[owp] = outName;
+      } else {
+        throw std::logic_error(
+            "Found a Workspace property which doesn't inherit from Property.");
+      }
     } // for each OutputWorkspace property
 
     // ------------ Execute the algo --------------
diff --git a/Code/Mantid/Framework/API/src/IMDWorkspace.cpp b/Code/Mantid/Framework/API/src/IMDWorkspace.cpp
index 82ed14e15c3290bbe7c051a4e4f02296eba6d382..e5484916df383d96b3904bcaacbf82dd17167c0b 100644
--- a/Code/Mantid/Framework/API/src/IMDWorkspace.cpp
+++ b/Code/Mantid/Framework/API/src/IMDWorkspace.cpp
@@ -122,6 +122,13 @@ void IMDWorkspace::getLinePlot(const Mantid::Kernel::VMD &start,
   // And the last point
   x.push_back((end - start).norm());
 }
+
+/**
+@return normalization preferred for visualization. Set to none for the generic case, but overriden elsewhere.
+*/
+MDNormalization IMDWorkspace::displayNormalization() const {
+  return NoNormalization;
+}
 }
 }
 
diff --git a/Code/Mantid/Framework/API/src/MDGeometry.cpp b/Code/Mantid/Framework/API/src/MDGeometry.cpp
index 1cc0f96fd307d2cc5b20a13cbfa2797b7c39b0ce..71a5c8d06beba25fefd3fbc0dab72c323b0c0e0f 100644
--- a/Code/Mantid/Framework/API/src/MDGeometry.cpp
+++ b/Code/Mantid/Framework/API/src/MDGeometry.cpp
@@ -237,7 +237,7 @@ MDGeometry::getYDimension() const {
 boost::shared_ptr<const Mantid::Geometry::IMDDimension>
 MDGeometry::getZDimension() const {
   if (this->getNumDims() < 3)
-    throw std::runtime_error("Workspace does not have a X dimension.");
+    throw std::runtime_error("Workspace does not have a Z dimension.");
   return this->getDimension(2);
 }
 
diff --git a/Code/Mantid/Framework/Algorithms/CMakeLists.txt b/Code/Mantid/Framework/Algorithms/CMakeLists.txt
index 012f793358d5cab13f7ccde04a26b036314b0d79..62a4a90e9878b46bce718624c8ea43f0710ad97d 100644
--- a/Code/Mantid/Framework/Algorithms/CMakeLists.txt
+++ b/Code/Mantid/Framework/Algorithms/CMakeLists.txt
@@ -767,6 +767,12 @@ set ( TEST_FILES
 
 set ( TEST_PY_FILES NormaliseToUnityTest.py )
 
+if (COVERALLS)
+    foreach( loop_var ${SRC_FILES} ${INC_FILES})
+      set_property(GLOBAL APPEND PROPERTY COVERAGE_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/${loop_var}")
+    endforeach(loop_var)
+endif()
+
 # Add a precompiled header where they are supported
 enable_precompiled_headers ( inc/MantidAlgorithms/PrecompiledHeader.h SRC_FILES )
 # Add the target for this directory
diff --git a/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/FindPeakBackground.h b/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/FindPeakBackground.h
index 04427a1bd1ea7662296befb0be7d6df0b95c3bca..dafdd2a808cb2638517e753c0e71393948c4fc8c 100644
--- a/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/FindPeakBackground.h
+++ b/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/FindPeakBackground.h
@@ -58,7 +58,7 @@ private:
   double moment4(MantidVec &X, size_t n, double mean);
   void estimateBackground(const MantidVec &X, const MantidVec &Y,
                           const size_t i_min, const size_t i_max,
-                          const size_t p_min, const size_t p_max,
+                          const size_t p_min, const size_t p_max, const bool hasPeak,
                           double &out_bg0, double &out_bg1, double &out_bg2);
   struct cont_peak {
     size_t start;
diff --git a/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/FindPeaks.h b/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/FindPeaks.h
index 4504a70253489a55be017c8de1156bcf9bf9b32c..ab6d05910530ddc9dce8d6b3e4d45d031c6ef2ab 100644
--- a/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/FindPeaks.h
+++ b/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/FindPeaks.h
@@ -142,13 +142,13 @@ private:
                   const bool isoutputraw, const double mincost);
 
   /// Add the fit record (failure) to output workspace
-  void addNonFitRecord(const size_t spectrum);
+  void addNonFitRecord(const size_t spectrum, const double centre);
 
   /// Create peak and background functions
   void createFunctions();
 
   /// Find peak background
-  bool findPeakBackground(const API::MatrixWorkspace_sptr &input, int spectrum,
+  int findPeakBackground(const API::MatrixWorkspace_sptr &input, int spectrum,
                           size_t i_min, size_t i_max,
                           std::vector<double> &vecBkgdParamValues,
                           std::vector<double> &vecpeakrange);
@@ -182,7 +182,8 @@ private:
                      const API::IBackgroundFunction_sptr backgroundfunction,
                      const std::vector<double> &vec_fitwindow,
                      const std::vector<double> &vec_peakrange,
-                     int minGuessedFWHM, int maxGuessFWHM, int guessedFWHMStep);
+                     int minGuessedFWHM, int maxGuessFWHM, int guessedFWHMStep,
+                     int estBackResult=0);
 
   std::vector<std::string> m_peakParameterNames;
   std::vector<std::string> m_bkgdParameterNames;
@@ -208,6 +209,7 @@ private:
   /// parameters or effective (centre, width, height)
   std::size_t
       m_numTableParams; //<Number of parameters in the output table workspace
+  std::size_t m_centre_index; //< Column in output table of peak centre
   std::string m_peakFuncType;   //< The name of the peak function to fit
   std::string m_backgroundType; //< The type of background to fit
 
diff --git a/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/PhaseQuadMuon.h b/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/PhaseQuadMuon.h
index ddd716bd9206f1e78e178f1fdd798b7f38b848cc..588f7f1a5d77d91f905dda48283acd3bce414489 100644
--- a/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/PhaseQuadMuon.h
+++ b/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/PhaseQuadMuon.h
@@ -39,7 +39,9 @@ public:
   /// Default constructor
   PhaseQuadMuon()
       : API::Algorithm(), m_muLife(2.19703), m_bigNumber(1e10), m_tPulseOver(0),
-        m_pulseTail(182), m_poissonLim(30), m_pulseTwo(0.325){};
+        m_pulseTail(182), m_poissonLim(30), m_pulseTwo(0.325), m_nHist(0),
+        m_nData(0), m_res(0.0), m_meanLag(0.0), m_tValid(0), m_isDouble(false),
+        m_tMin(0.0){};
   /// Destructor
   virtual ~PhaseQuadMuon(){};
   /// Algorithm's name for identification overriding a virtual method
diff --git a/Code/Mantid/Framework/Algorithms/src/ApplyDetailedBalance.cpp b/Code/Mantid/Framework/Algorithms/src/ApplyDetailedBalance.cpp
index 539b42354be153d3e897fd11dec1882a589d9618..cae398437d8384fce9bf052bc4ed3486f76c6f13 100644
--- a/Code/Mantid/Framework/Algorithms/src/ApplyDetailedBalance.cpp
+++ b/Code/Mantid/Framework/Algorithms/src/ApplyDetailedBalance.cpp
@@ -62,13 +62,16 @@ void ApplyDetailedBalance::exec() {
   std::string Tstring = getProperty("Temperature");
   double Temp;
   try {
-    if (inputWS->run().hasProperty(Tstring))
-      Temp = (dynamic_cast<Kernel::TimeSeriesProperty<double> *>(
-                  inputWS->run().getProperty(Tstring)))
-                 ->getStatistics()
-                 .mean;
-    else
+    if (inputWS->run().hasProperty(Tstring)) {
+      if (auto log = dynamic_cast<Kernel::TimeSeriesProperty<double> *>(
+                  inputWS->run().getProperty(Tstring)) ) {
+        Temp = log->getStatistics().mean;
+      } else {
+        throw std::invalid_argument(Tstring + " is not a double-valued log.");
+      }
+    } else {
       Temp = boost::lexical_cast<double>(Tstring);
+    }
   } catch (...) {
     Tstring += " is not a valid log, nor is it a number";
     throw std::invalid_argument(Tstring);
diff --git a/Code/Mantid/Framework/Algorithms/src/ConvertSpectrumAxis.cpp b/Code/Mantid/Framework/Algorithms/src/ConvertSpectrumAxis.cpp
index 077c52cbb24b5edc38b6c4c6c3639534ef323d09..cfa92ffabf5d20b7c7c6db8102cb6973d002203e 100644
--- a/Code/Mantid/Framework/Algorithms/src/ConvertSpectrumAxis.cpp
+++ b/Code/Mantid/Framework/Algorithms/src/ConvertSpectrumAxis.cpp
@@ -185,7 +185,13 @@ double ConvertSpectrumAxis::getEfixed(IDetector_const_sptr detector,
         Kernel::Property *p = inputWS->run().getProperty("Ei");
         Kernel::PropertyWithValue<double> *doublep =
             dynamic_cast<Kernel::PropertyWithValue<double> *>(p);
-        efixed = (*doublep)();
+        if (doublep) {
+          efixed = (*doublep)();
+        } else {
+          efixed = 0.0;
+          g_log.warning() << "Efixed could not be found for detector "
+                          << detector->getID() << ", set to 0.0\n";
+        }
       } else {
         efixed = 0.0;
         g_log.warning() << "Efixed could not be found for detector "
diff --git a/Code/Mantid/Framework/Algorithms/src/EQSANSTofStructure.cpp b/Code/Mantid/Framework/Algorithms/src/EQSANSTofStructure.cpp
index ede4630245ae5a8fe4e2cf1f1a5e4d9c0820979a..32fa06766592a85d465c40dbd57b84ca0696e398 100644
--- a/Code/Mantid/Framework/Algorithms/src/EQSANSTofStructure.cpp
+++ b/Code/Mantid/Framework/Algorithms/src/EQSANSTofStructure.cpp
@@ -73,19 +73,23 @@ void EQSANSTofStructure::exec() {
   high_tof_cut = getProperty("HighTOFCut");
 
   // Calculate the frame width
-  double frequency = dynamic_cast<TimeSeriesProperty<double> *>(
-                         inputWS->run().getLogData("frequency"))
-                         ->getStatistics()
-                         .mean;
+  auto frequencyLog = dynamic_cast<TimeSeriesProperty<double> *>(
+      inputWS->run().getLogData("frequency"));
+  if (!frequencyLog) {
+    throw std::runtime_error("Frequency log not found.");
+  }
+  double frequency = frequencyLog->getStatistics().mean;
   double tof_frame_width = 1.0e6 / frequency;
 
   // Determine whether we need frame skipping or not by checking the chopper
   // speed
   bool frame_skipping = false;
-  const double chopper_speed = dynamic_cast<TimeSeriesProperty<double> *>(
-                                   inputWS->run().getLogData("Speed1"))
-                                   ->getStatistics()
-                                   .mean;
+  auto chopper_speedLog = dynamic_cast<TimeSeriesProperty<double> *>(
+      inputWS->run().getLogData("Speed1"));
+  if (!chopper_speedLog) {
+    throw std::runtime_error("Chopper speed log not found.");
+  }
+  const double chopper_speed = chopper_speedLog->getStatistics().mean;
   if (std::fabs(chopper_speed - frequency / 2.0) < 1.0)
     frame_skipping = true;
 
@@ -114,8 +118,10 @@ EQSANSTofStructure::execEvent(Mantid::DataObjects::EventWorkspace_sptr inputWS,
   // Get the nominal sample-to-detector distance (in mm)
   Mantid::Kernel::Property *prop =
       inputWS->run().getProperty("sample_detector_distance");
-  Mantid::Kernel::PropertyWithValue<double> *dp =
-      dynamic_cast<Mantid::Kernel::PropertyWithValue<double> *>(prop);
+  auto dp = dynamic_cast<Mantid::Kernel::PropertyWithValue<double> *>(prop);
+  if (!dp) {
+    throw std::runtime_error("sample_detector_distance log not found.");
+  }
   const double SDD = *dp / 1000.0;
 
   // Loop through the spectra and apply correction
@@ -204,10 +210,12 @@ double EQSANSTofStructure::getTofOffset(EventWorkspace_const_sptr inputWS,
   double chopper_frameskip_srcpulse_wl_1[4] = {0, 0, 0, 0};
 
   // Calculate the frame width
-  double frequency = dynamic_cast<TimeSeriesProperty<double> *>(
-                         inputWS->run().getLogData("frequency"))
-                         ->getStatistics()
-                         .mean;
+  auto frequencyLog = dynamic_cast<TimeSeriesProperty<double> *>(
+      inputWS->run().getLogData("frequency"));
+  if (!frequencyLog) {
+    throw std::runtime_error("Frequency log not found.");
+  }
+  double frequency = frequencyLog->getStatistics().mean;
   double tof_frame_width = 1.0e6 / frequency;
 
   double tmp_frame_width = tof_frame_width;
@@ -229,16 +237,20 @@ double EQSANSTofStructure::getTofOffset(EventWorkspace_const_sptr inputWS,
     // Read chopper information
     std::ostringstream phase_str;
     phase_str << "Phase" << i + 1;
-    chopper_set_phase[i] = dynamic_cast<TimeSeriesProperty<double> *>(
-                               inputWS->run().getLogData(phase_str.str()))
-                               ->getStatistics()
-                               .mean;
+    auto log = dynamic_cast<TimeSeriesProperty<double> *>(
+        inputWS->run().getLogData(phase_str.str()));
+    if (!log) {
+      throw std::runtime_error("Phase log not found.");
+    }
+    chopper_set_phase[i] = log->getStatistics().mean;
     std::ostringstream speed_str;
     speed_str << "Speed" << i + 1;
-    chopper_speed[i] = dynamic_cast<TimeSeriesProperty<double> *>(
-                           inputWS->run().getLogData(speed_str.str()))
-                           ->getStatistics()
-                           .mean;
+    log = dynamic_cast<TimeSeriesProperty<double> *>(
+        inputWS->run().getLogData(speed_str.str()));
+    if (!log) {
+      throw std::runtime_error("Speed log not found.");
+    }
+    chopper_speed[i] = log->getStatistics().mean;
 
     // Only process choppers with non-zero speed
     if (chopper_speed[i] <= 0)
diff --git a/Code/Mantid/Framework/Algorithms/src/FilterBadPulses.cpp b/Code/Mantid/Framework/Algorithms/src/FilterBadPulses.cpp
index d2969bfa70e95d0be559630b367ea92bf8b2e9bb..51276fe192e546d7c4ff530bd94b83cffb3a3eb3 100644
--- a/Code/Mantid/Framework/Algorithms/src/FilterBadPulses.cpp
+++ b/Code/Mantid/Framework/Algorithms/src/FilterBadPulses.cpp
@@ -95,6 +95,10 @@ void FilterBadPulses::exec() {
   Kernel::TimeSeriesProperty<double> *pcharge_log =
       dynamic_cast<Kernel::TimeSeriesProperty<double> *>(
           runlogs.getLogData(LOG_CHARGE_NAME));
+  if (!pcharge_log) {
+    throw std::logic_error("Failed to find \"" + LOG_CHARGE_NAME +
+                             "\" in sample logs");
+  }
   Kernel::TimeSeriesPropertyStatistics stats = pcharge_log->getStatistics();
 
   // check that the maximum value is greater than zero
diff --git a/Code/Mantid/Framework/Algorithms/src/FindPeakBackground.cpp b/Code/Mantid/Framework/Algorithms/src/FindPeakBackground.cpp
index 88616a2d66071ccf27b6a53f76875fcc0476e78e..5c6e1c1ed7bf74a941ae637d510e2cba003a4d99 100644
--- a/Code/Mantid/Framework/Algorithms/src/FindPeakBackground.cpp
+++ b/Code/Mantid/Framework/Algorithms/src/FindPeakBackground.cpp
@@ -201,7 +201,7 @@ void FindPeakBackground::exec() {
       }
     }
     size_t min_peak, max_peak;
-    double a0, a1, a2;
+    double a0 = 0., a1 = 0., a2 = 0.;
     int goodfit;
     if (peaks.size() > 0) {
       g_log.debug() << "Peaks' size = " << peaks.size()
@@ -214,23 +214,17 @@ void FindPeakBackground::exec() {
       min_peak = peaks[0].start;
       // extra point for histogram input
       max_peak = peaks[0].stop + sizex - sizey;
-      estimateBackground(inpX, inpY, l0, n, peaks[0].start, peaks[0].stop, a0,
-                         a1, a2);
       goodfit = 1;
     } else {
-      // assume background is 12 first and last points
-      g_log.debug("Peaks' size = 0 -> zero background.");
-      min_peak = l0 + 12;
-      max_peak = n - 13;
-      if (min_peak > sizey)
-        min_peak = sizey - 1;
-      // FIXME : as it is assumed that background is 12 first and 12 last, then
-      //         why not do a simple fit here!
-      a0 = 0.0;
-      a1 = 0.0;
-      a2 = 0.0;
-      goodfit = -1;
+      // assume the whole thing is background
+      g_log.debug("Peaks' size = 0 -> whole region assumed background");
+      min_peak = n;
+      max_peak = l0;
+
+      goodfit = 2;
     }
+    estimateBackground(inpX, inpY, l0, n, min_peak, max_peak,
+                       (peaks.size() > 0), a0, a1, a2);
 
     // Add a new row
     API::TableRow t = m_outPeakTableWS->getRow(0);
@@ -254,18 +248,18 @@ void FindPeakBackground::exec() {
 * @param i_max :: index of maximum in X to estimate background
 * @param p_min :: index of peak min in X to estimate background
 * @param p_max :: index of peak max in X to estimate background
+* @param hasPeak :: ban data in the peak range
 * @param out_bg0 :: interception
 * @param out_bg1 :: slope
 * @param out_bg2 :: a2 = 0
 */
-void FindPeakBackground::estimateBackground(
-    const MantidVec &X, const MantidVec &Y, const size_t i_min,
-    const size_t i_max, const size_t p_min, const size_t p_max, double &out_bg0,
+void FindPeakBackground::estimateBackground(const MantidVec &X, const MantidVec &Y, const size_t i_min,
+    const size_t i_max, const size_t p_min, const size_t p_max, const bool hasPeak, double &out_bg0,
     double &out_bg1, double &out_bg2) {
   // Validate input
   if (i_min >= i_max)
     throw std::runtime_error("i_min cannot larger or equal to i_max");
-  if (p_min >= p_max)
+  if ((hasPeak) && (p_min >= p_max))
     throw std::runtime_error("p_min cannot larger or equal to p_max");
 
   // set all parameters to zero
@@ -337,15 +331,18 @@ void FindPeakBackground::estimateBackground(
         determinant;
   }
 
-  // calculate the chisq - not normalized by the number of points
   double chisq_flat = 0.;
   double chisq_linear = 0.;
   double chisq_quadratic = 0.;
   if (sum != 0) {
+    double num_points = 0.;
+    // calculate the chisq - not normalized by the number of points
     for (size_t i = i_min; i < i_max; ++i) {
       if (i >= p_min && i < p_max)
         continue;
 
+      num_points += 1.;
+
       // accumulate for flat
       chisq_flat += (bg0_flat - Y[i]) * (bg0_flat - Y[i]);
 
@@ -358,6 +355,12 @@ void FindPeakBackground::estimateBackground(
              bg2_quadratic * X[i] * X[i] - Y[i];
       chisq_quadratic += (temp * temp);
     }
+
+    // convert to <reduced chisq> = chisq / (<number points> - <number
+    // parameters>)
+    chisq_flat = chisq_flat / (num_points - 1.);
+    chisq_linear = chisq_linear / (num_points - 2.);
+    chisq_quadratic = chisq_quadratic / (num_points - 3.);
   }
   const double INVALID_CHISQ(1.e10); // big invalid value
   if (m_backgroundType == "Flat") {
@@ -367,6 +370,14 @@ void FindPeakBackground::estimateBackground(
     chisq_quadratic = INVALID_CHISQ;
   }
 
+  g_log.debug() << "flat: " << bg0_flat << " + " << 0. << "x + " << 0.
+                << "x^2 reduced chisq=" << chisq_flat << "\n";
+  g_log.debug() << "line: " << bg0_linear << " + " << bg1_linear << "x + " << 0.
+                << "x^2  reduced chisq=" << chisq_linear << "\n";
+  g_log.debug() << "quad: " << bg0_quadratic << " + " << bg1_quadratic << "x + "
+                << bg2_quadratic << "x^2  reduced chisq=" << chisq_quadratic
+                << "\n";
+
   // choose the right background function to apply
   if ((chisq_quadratic < chisq_flat) && (chisq_quadratic < chisq_linear)) {
     out_bg0 = bg0_quadratic;
@@ -379,8 +390,8 @@ void FindPeakBackground::estimateBackground(
     out_bg0 = bg0_flat;
   }
 
-  g_log.debug() << "Estimated background: A0 = " << out_bg0
-                << ", A1 = " << out_bg1 << ", A2 = " << out_bg2 << "\n";
+  g_log.information() << "Estimated background: A0 = " << out_bg0
+                      << ", A1 = " << out_bg1 << ", A2 = " << out_bg2 << "\n";
 
   return;
 }
diff --git a/Code/Mantid/Framework/Algorithms/src/FindPeaks.cpp b/Code/Mantid/Framework/Algorithms/src/FindPeaks.cpp
index 17f88faab701a2333fbdffb9fc9757c23de320a3..b0ee0c9daa29ab1efd3f766ac748b9166f8625a9 100644
--- a/Code/Mantid/Framework/Algorithms/src/FindPeaks.cpp
+++ b/Code/Mantid/Framework/Algorithms/src/FindPeaks.cpp
@@ -296,6 +296,16 @@ void FindPeaks::generateOutputPeakParameterTable() {
     size_t numpeakpars = m_peakFunction->nParams();
     size_t numbkgdpars = m_backgroundFunction->nParams();
     m_numTableParams = numpeakpars + numbkgdpars;
+    if (m_peakFuncType == "Gaussian")
+        m_centre_index = 1;
+    else if (m_peakFuncType == "LogNormal")
+        m_centre_index = 1;
+    else if (m_peakFuncType == "Lorentzian")
+        m_centre_index = 1;
+    else if (m_peakFuncType == "PseudoVoigt")
+        m_centre_index = 2;
+    else
+        m_centre_index = m_numTableParams; // bad value
 
     for (size_t i = 0; i < numpeakpars; ++i)
       m_outPeakTableWS->addColumn("double", m_peakParameterNames[i]);
@@ -305,6 +315,7 @@ void FindPeaks::generateOutputPeakParameterTable() {
   } else {
     // Output centre, weight, height, A0, A1 and A2
     m_numTableParams = 6;
+    m_centre_index = 0;
     m_outPeakTableWS->addColumn("double", "centre");
     m_outPeakTableWS->addColumn("double", "width");
     m_outPeakTableWS->addColumn("double", "height");
@@ -339,6 +350,34 @@ FindPeaks::findPeaksGivenStartingPoints(const std::vector<double> &peakcentres,
   for (int spec = start; spec < end; ++spec) {
     const MantidVec &vecX = m_dataWS->readX(spec);
 
+    double practical_x_min = vecX.front();
+    double practical_x_max = vecX.back();
+    g_log.information() << "actual x-range = [" << practical_x_min << " -> " << practical_x_max << "]\n";
+    {
+        const MantidVec &vecY = m_dataWS->readY(spec);
+        const MantidVec &vecE = m_dataWS->readE(spec);
+        const size_t numY = vecY.size();
+        size_t i_min = 1;
+        for ( ; i_min < numY; ++i_min) {
+            if ((vecY[i_min] != 0.) || (vecE[i_min] != 0)) {
+                --i_min; // bring it back one
+                break;
+            }
+        }
+        practical_x_min = vecX[i_min];
+
+        size_t i_max = numY-2;
+        for ( ; i_max > i_min; --i_max) {
+            if ((vecY[i_max] != 0.) || (vecE[i_max] != 0)) {
+                ++i_max; // bring it back one
+                break;
+            }
+        }
+        g_log.warning() << "i_min = " << i_min << " i_max = " << i_max << "\n";
+        practical_x_max = vecX[i_max];
+    }
+    g_log.information() << "practical x-range = [" << practical_x_min << " -> " << practical_x_max << "]\n";
+
     for (std::size_t ipeak = 0; ipeak < numPeaks; ipeak++) {
       // Try to fit at this center
       double x_center = peakcentres[ipeak];
@@ -352,7 +391,7 @@ FindPeaks::findPeaksGivenStartingPoints(const std::vector<double> &peakcentres,
       g_log.information(infoss.str());
 
       // Check whether it is the in data range
-      if (x_center > vecX.front() && x_center < vecX.back()) {
+      if (x_center > practical_x_min && x_center < practical_x_max) {
         if (useWindows)
           fitPeakInWindow(m_dataWS, spec, x_center, fitwindows[2 * ipeak],
                           fitwindows[2 * ipeak + 1]);
@@ -374,7 +413,8 @@ FindPeaks::findPeaksGivenStartingPoints(const std::vector<double> &peakcentres,
       } else {
         g_log.warning() << "Given peak centre " << x_center
                         << " is out side of given data's range ("
-                        << vecX.front() << ", " << vecX.back() << ").\n";
+                        << practical_x_min << ", " << practical_x_max << ").\n";
+        addNonFitRecord(spec, x_center);
       }
 
     } // loop through the peaks specified
@@ -864,7 +904,7 @@ void FindPeaks::fitPeakInWindow(const API::MatrixWorkspace_sptr &input,
                       << ", x-max = " << xmax << "\n";
   if (xmin >= centre_guess || xmax <= centre_guess) {
     g_log.error("Peak centre is on the edge of Fit window. ");
-    addNonFitRecord(spectrum);
+    addNonFitRecord(spectrum, centre_guess);
     return;
   }
 
@@ -881,7 +921,7 @@ void FindPeaks::fitPeakInWindow(const API::MatrixWorkspace_sptr &input,
                   << " is out side of minimum x = " << xmin
                   << ".  Input X ragne = " << vecX.front() << ", "
                   << vecX.back() << "\n";
-    addNonFitRecord(spectrum);
+    addNonFitRecord(spectrum, centre_guess);
     return;
   }
 
@@ -890,7 +930,7 @@ void FindPeaks::fitPeakInWindow(const API::MatrixWorkspace_sptr &input,
   if (i_max < i_centre) {
     g_log.error() << "Input peak centre @ " << centre_guess
                   << " is out side of maximum x = " << xmax << "\n";
-    addNonFitRecord(spectrum);
+    addNonFitRecord(spectrum, centre_guess);
     return;
   }
 
@@ -922,26 +962,25 @@ void FindPeaks::fitSinglePeak(const API::MatrixWorkspace_sptr &input,
     ess << "Peak supposed at " << vecY[i_centre]
         << " does not have enough counts as " << m_leastMaxObsY;
     g_log.debug(ess.str());
-    addNonFitRecord(spectrum);
+    addNonFitRecord(spectrum, vecY[i_centre]);
     return;
   }
 
-  //-------------------------------------------------------------------------
-  // Estimate peak and background parameters for better fitting
-  //-------------------------------------------------------------------------
-  std::stringstream outss;
-  outss << "Fit single peak in X-range " << input->readX(spectrum)[i_min]
-        << ", " << input->readX(spectrum)[i_max] << ", centre at "
-        << input->readX(spectrum)[i_centre] << " (index = " << i_centre
-        << "). ";
-  g_log.information(outss.str());
+  {
+      std::stringstream outss;
+      outss << "Fit single peak in X-range " << vecX[i_min]
+               << ", " << vecX[i_max] << ", centre at "
+               << vecX[i_centre] << " (index = " << i_centre
+               << "). ";
+      g_log.information(outss.str());
+  }
 
   // Estimate background
   std::vector<double> vecbkgdparvalue(3, 0.);
   std::vector<double> vecpeakrange(3, 0.);
-  bool usefpdresult = findPeakBackground(input, spectrum, i_min, i_max,
+  int usefpdresult = findPeakBackground(input, spectrum, i_min, i_max,
                                          vecbkgdparvalue, vecpeakrange);
-  if (!usefpdresult) {
+  if (usefpdresult < 0) {
     // Estimate background roughly for a failed case
     estimateBackground(vecX, vecY, i_min, i_max, vecbkgdparvalue);
   }
@@ -973,7 +1012,7 @@ void FindPeaks::fitSinglePeak(const API::MatrixWorkspace_sptr &input,
   m_peakFunction->setHeight(est_height);
   m_peakFunction->setFwhm(est_fwhm);
 
-  if (!usefpdresult) {
+  if (usefpdresult < 0) {
     // Estimate peak range based on estimated linear background and peak
     // parameter estimated from observation
     if (!m_useObsCentre)
@@ -996,18 +1035,22 @@ void FindPeaks::fitSinglePeak(const API::MatrixWorkspace_sptr &input,
 
   bool fitsuccess = false;
   if (costfuncvalue < DBL_MAX && costfuncvalue >= 0. &&
-      m_peakFunction->height() > m_minHeight)
+      m_peakFunction->height() > m_minHeight) {
     fitsuccess = true;
+  }
+  if (fitsuccess && m_usePeakPositionTolerance) {
+      fitsuccess = (fabs(m_peakFunction->centre()-vecX[i_centre]) < m_peakPositionTolerance);
+  }
 
   //-------------------------------------------------------------------------
   // Process Fit result
   //-------------------------------------------------------------------------
   // Update output
   if (fitsuccess)
-    addInfoRow(spectrum, m_peakFunction, m_backgroundFunction, m_rawPeaksTable,
+      addInfoRow(spectrum, m_peakFunction, m_backgroundFunction, m_rawPeaksTable,
                costfuncvalue);
   else
-    addNonFitRecord(spectrum);
+      addNonFitRecord(spectrum, m_peakFunction->centre());
 
   return;
 }
@@ -1016,7 +1059,7 @@ void FindPeaks::fitSinglePeak(const API::MatrixWorkspace_sptr &input,
 /** Find peak background given a certain range by
   * calling algorithm "FindPeakBackground"
   */
-bool FindPeaks::findPeakBackground(const MatrixWorkspace_sptr &input,
+int FindPeaks::findPeakBackground(const MatrixWorkspace_sptr &input,
                                    int spectrum, size_t i_min, size_t i_max,
                                    std::vector<double> &vecBkgdParamValues,
                                    std::vector<double> &vecpeakrange) {
@@ -1038,22 +1081,21 @@ bool FindPeaks::findPeakBackground(const MatrixWorkspace_sptr &input,
       estimate->getProperty("OutputWorkspace");
 
   // Determine whether to use FindPeakBackground's result.
-  bool usefitresult = false;
+  int fitresult = -1;
   if (peaklisttablews->columnCount() < 7)
     throw std::runtime_error(
         "No 7th column for use FindPeakBackground result or not. ");
 
   if (peaklisttablews->rowCount() > 0) {
-    int useit = peaklisttablews->Int(0, 6);
-    if (useit > 0)
-      usefitresult = true;
+    int fitresult = peaklisttablews->Int(0, 6);
+    g_log.information() << "fitresult=" << fitresult << "\n";
   }
 
   // Local check whether FindPeakBackground gives a reasonable value
   vecpeakrange.resize(2);
 
-  if (usefitresult) {
-    // Use FitPeakBackgroud's reuslt
+  if (fitresult > 0) {
+    // Use FitPeakBackgroud's result
     size_t i_peakmin, i_peakmax;
     i_peakmin = peaklisttablews->Int(0, 1);
     i_peakmax = peaklisttablews->Int(0, 2);
@@ -1079,18 +1121,20 @@ bool FindPeaks::findPeakBackground(const MatrixWorkspace_sptr &input,
       vecBkgdParamValues[2] = bg2;
 
       g_log.information()
-          << "Backgroun parameters (from FindPeakBackground) A0, A1, A2 = "
-          << bg0 << ", " << bg1 << ", " << bg2 << "\n";
+          << "Background parameters (from FindPeakBackground) A0=" << bg0
+          << ", A1=" << bg1 << ", A2=" << bg2 << "\n";
 
       vecpeakrange[0] = vecX[i_peakmin];
       vecpeakrange[1] = vecX[i_peakmax];
     } else {
       // Do manual estimation again
-      usefitresult = false;
       g_log.debug(
           "FindPeakBackground result is ignored due to wrong in peak range. ");
     }
   }
+  else {
+      g_log.information("Failed to get background estimation\n");
+  }
 
   std::stringstream outx;
   outx << "FindPeakBackground Result: Given window (" << vecX[i_min] << ", "
@@ -1098,7 +1142,7 @@ bool FindPeaks::findPeakBackground(const MatrixWorkspace_sptr &input,
        << ", " << vecpeakrange[1] << "). ";
   g_log.information(outx.str());
 
-  return usefitresult;
+  return fitresult;
 }
 
 //----------------------------------------------------------------------------------------------
@@ -1421,8 +1465,10 @@ void FindPeaks::addInfoRow(const size_t spectrum,
       a2 = bkgdfunction->getParameter("A2");
 
     t << a0 << a1 << a2;
+    g_log.warning() << "cen=" << peakcentre << " fwhm=" << fwhm << " height=" << height
+                    << " a0=" << a0 << " a0=" << a1 << " a2=" << a2;
   }
-
+  g_log.warning() << " chsq=" << mincost << "\n";
   // Minimum cost function value
   t << mincost;
 
@@ -1432,17 +1478,23 @@ void FindPeaks::addInfoRow(const size_t spectrum,
 //----------------------------------------------------------------------------------------------
 /** Add the fit record (failure) to output workspace
   * @param spectrum :: spectrum where the peak is
+  * @param centre :: position of the peak centre
   */
-void FindPeaks::addNonFitRecord(const size_t spectrum) {
+void FindPeaks::addNonFitRecord(const size_t spectrum, const double centre) {
   // Add a new row
   API::TableRow t = m_outPeakTableWS->appendRow();
 
+  g_log.information() << "Failed to fit peak at " << centre << "\n";
   // 1st column
   t << static_cast<int>(spectrum);
 
   // Parameters
-  for (std::size_t i = 0; i < m_numTableParams; i++)
-    t << 0.;
+  for (std::size_t i = 0; i < m_numTableParams; i++) {
+      if (i == m_centre_index)
+          t << centre;
+      else
+          t << 0.;
+  }
 
   // HUGE chi-square
   t << DBL_MAX;
@@ -1491,7 +1543,7 @@ FindPeaks::callFitPeak(const MatrixWorkspace_sptr &dataws, int wsindex,
                        const std::vector<double> &vec_fitwindow,
                        const std::vector<double> &vec_peakrange,
                        int minGuessFWHM, int maxGuessFWHM,
-                       int guessedFWHMStep) {
+                       int guessedFWHMStep, int estBackResult) {
   std::stringstream dbss;
   dbss << "[Call FitPeak] Fit 1 peak at X = " << peakfunction->centre()
        << " of spectrum " << wsindex;
@@ -1509,10 +1561,16 @@ FindPeaks::callFitPeak(const MatrixWorkspace_sptr &dataws, int wsindex,
                            guessedFWHMStep, fitwithsteppedfwhm);
   fitpeak.setPeakRange(vec_peakrange[0], vec_peakrange[1]);
 
-  if (m_highBackground)
-    fitpeak.highBkgdFit();
-  else
-    fitpeak.simpleFit();
+  if (estBackResult == 1) {
+      g_log.information("simpleFit");
+      fitpeak.simpleFit();
+  } else if (m_highBackground) {
+      g_log.information("highBkgdFit");
+      fitpeak.highBkgdFit();
+  } else {
+      g_log.information("simpleFit");
+      fitpeak.simpleFit();
+  }
 
   double costfuncvalue = fitpeak.getFitCostFunctionValue();
   std::string dbinfo = fitpeak.getDebugMessage();
diff --git a/Code/Mantid/Framework/Algorithms/src/FitPeak.cpp b/Code/Mantid/Framework/Algorithms/src/FitPeak.cpp
index 717266e8e355475c27bf92354e64f25eea004e35..992cd848fb732ce2a20888957aefe6f911b18122 100644
--- a/Code/Mantid/Framework/Algorithms/src/FitPeak.cpp
+++ b/Code/Mantid/Framework/Algorithms/src/FitPeak.cpp
@@ -39,8 +39,9 @@ namespace Algorithms {
   */
 FitOneSinglePeak::FitOneSinglePeak()
     : m_fitMethodSet(false), m_peakRangeSet(false), m_peakWidthSet(false),
-      m_peakWindowSet(false), m_usePeakPositionTolerance(false), m_wsIndex(0),
-      m_numFitCalls(0), m_sstream("") {}
+      m_peakWindowSet(false), m_usePeakPositionTolerance(false),
+      m_wsIndex(0), m_minimizer("Levenberg-MarquardtMD"), m_costFunction("Least squares"), m_numFitCalls(0), m_sstream("")
+ {}
 
 //----------------------------------------------------------------------------------------------
 /** Destructor for FitOneSinglePeak
@@ -544,6 +545,7 @@ void FitOneSinglePeak::highBkgdFit() {
   // Fit the composite function as final
   double compcost = fitCompositeFunction(m_peakFunc, m_bkgdFunc, m_dataWS,
                                          m_wsIndex, m_minFitX, m_maxFitX);
+  m_bestRwp = compcost;
 
   m_sstream << "MultStep-Fit: Best Fitted Peak: " << m_peakFunc->asString()
             << ". Final " << m_costFunction << " = " << compcost << "\n"
@@ -661,8 +663,7 @@ double FitOneSinglePeak::fitFunctionSD(IFunction_sptr fitfunc,
   fit->setProperty("CalcErrors", true);
 
   // Execute fit and get result of fitting background
-  m_sstream << "FitSingleDomain: Fit " << fit->asString()
-            << "; StartX = " << xmin << ", EndX = " << xmax << ".\n";
+  m_sstream << "FitSingleDomain: " << fit->asString() << ".\n";
 
   fit->executeAsChildAlg();
   if (!fit->isExecuted()) {
@@ -797,8 +798,10 @@ double FitOneSinglePeak::fitCompositeFunction(
   // so far the best Rwp
   bool modecal = true;
   // FIXME - This is not a good practise...
+  double backRwp = fitFunctionSD(bkgdfunc, dataws, wsindex, startx, endx, modecal);
+  m_sstream << "Background: Pre-fit Goodness = " << backRwp << "\n";
   m_bestRwp = fitFunctionSD(compfunc, dataws, wsindex, startx, endx, modecal);
-  m_sstream << "Peak+Backgruond: Pre-fit Goodness = " << m_bestRwp << "\n";
+  m_sstream << "Peak+Background: Pre-fit Goodness = " << m_bestRwp << "\n";
 
   map<string, double> bkuppeakmap, bkupbkgdmap;
   push(peakfunc, bkuppeakmap);
@@ -820,11 +823,11 @@ double FitOneSinglePeak::fitCompositeFunction(
               << errorreason << "\n";
 
   double goodness_final = DBL_MAX;
-  if (goodness <= m_bestRwp) {
+  if (goodness <= m_bestRwp && goodness <= backRwp) {
     // Fit for composite function renders a better result
     goodness_final = goodness;
     processNStoreFitResult(goodness_final, true);
-  } else if (goodness > m_bestRwp && m_bestRwp < DBL_MAX) {
+  } else if (goodness > m_bestRwp && m_bestRwp < DBL_MAX && m_bestRwp <= backRwp) {
     // A worse result is got.  Revert to original function parameters
     m_sstream << "Fit peak/background composite function FAILS to render a "
                  "better solution. "
@@ -833,6 +836,7 @@ double FitOneSinglePeak::fitCompositeFunction(
 
     pop(bkuppeakmap, peakfunc);
     pop(bkupbkgdmap, bkgdfunc);
+    goodness_final = m_bestRwp;
   } else {
     m_sstream << "Fit peak-background function fails in all approaches! \n";
   }
diff --git a/Code/Mantid/Framework/Algorithms/src/GetDetOffsetsMultiPeaks.cpp b/Code/Mantid/Framework/Algorithms/src/GetDetOffsetsMultiPeaks.cpp
index af9da586f37ee08398e19805273dcb3654d209c9..ac0bc7b27c8f427c9891143d65b3fab6ccba7a28 100644
--- a/Code/Mantid/Framework/Algorithms/src/GetDetOffsetsMultiPeaks.cpp
+++ b/Code/Mantid/Framework/Algorithms/src/GetDetOffsetsMultiPeaks.cpp
@@ -582,13 +582,22 @@ FitPeakOffsetResult GetDetOffsetsMultiPeaks::calculatePeakOffset(
     const MantidVec &Y = m_inputWS->readY(wi);
     const int YLength = static_cast<int>(Y.size());
     double sumY = 0.0;
-    for (int i = 0; i < YLength; i++)
+    size_t numNonEmptyBins = 0;
+    for (int i = 0; i < YLength; i++) {
       sumY += Y[i];
+      if (Y[i] > 0.)
+          numNonEmptyBins += 1;
+    }
     if (sumY < 1.e-30) {
       // Dead detector will be masked
       fr.offset = BAD_OFFSET;
       fr.fitoffsetstatus = "dead det";
     }
+    if (numNonEmptyBins <= 3) {
+        // Another dead detector check
+        fr.offset = BAD_OFFSET;
+        fr.fitoffsetstatus = "dead det";
+    }
   }
 
   // Calculate peak offset for 'good' detector
@@ -961,10 +970,13 @@ void GetDetOffsetsMultiPeaks::generatePeaksList(
 
   // Check
   size_t numrows = peakslist->rowCount();
-  if (numrows != peakPositionRef.size())
-    throw std::runtime_error("Number of peaks in PeaksList (from FindPeaks) is "
-                             "not same as number of "
-                             "referenced peaks' positions. ");
+  if (numrows != peakPositionRef.size()) {
+      std::stringstream msg;
+      msg << "Number of peaks in PeaksList (from FindPeaks="
+          << numrows << ") is not same as number of "
+          << "referenced peaks' positions (" << peakPositionRef.size() << ")";
+    throw std::runtime_error(msg.str());
+  }
 
   std::vector<double> vec_widthDivPos;
   std::vector<double> vec_offsets;
@@ -1181,7 +1193,7 @@ void GetDetOffsetsMultiPeaks::addInfoToReportWS(
     m_resolutionWS->dataE(wi)[0] = offsetresult.dev_resolution;
   } else {
     // Only add successfully calculated value
-    m_resolutionWS->dataY(wi)[0] = -0.0;
+    m_resolutionWS->dataY(wi)[0] = 0.0;
     m_resolutionWS->dataE(wi)[0] = 0.0;
   }
 
@@ -1217,7 +1229,7 @@ void GetDetOffsetsMultiPeaks::addInfoToReportWS(
 
     double numdelta = static_cast<double>(numpeaksfitted);
     double stddev = 0.;
-    if (numpeaksfitted > 1)
+    if (numpeaksfitted > 1.)
       stddev = sqrt(sumdelta2 / numdelta -
                     (sumdelta1 / numdelta) * (sumdelta1 / numdelta));
 
diff --git a/Code/Mantid/Framework/Algorithms/src/NormaliseByCurrent.cpp b/Code/Mantid/Framework/Algorithms/src/NormaliseByCurrent.cpp
index ec43dff2439ea8856ed70919068b0ae88c8cad2e..c64efff6df28d05da99b06481f5fdd882f4da7d6 100644
--- a/Code/Mantid/Framework/Algorithms/src/NormaliseByCurrent.cpp
+++ b/Code/Mantid/Framework/Algorithms/src/NormaliseByCurrent.cpp
@@ -61,7 +61,11 @@ double NormaliseByCurrent::extractCharge(
     Property *chargeProperty = run.getLogData("proton_charge_by_period");
     ArrayProperty<double> *chargePropertyArray =
         dynamic_cast<ArrayProperty<double> *>(chargeProperty);
-    charge = chargePropertyArray->operator()()[periodNumber - 1];
+    if (chargePropertyArray) {
+      charge = chargePropertyArray->operator()()[periodNumber - 1];
+    } else {
+      throw std::runtime_error("Proton charge log not found.");
+    }
   } else {
     try {
       charge = inputWS->run().getProtonCharge();
diff --git a/Code/Mantid/Framework/Algorithms/src/StripPeaks.cpp b/Code/Mantid/Framework/Algorithms/src/StripPeaks.cpp
index 984de74fe4119509b4d296b850659a756209407e..a12cb52837252d4e13c21d1cc4fe098c173bbb33 100644
--- a/Code/Mantid/Framework/Algorithms/src/StripPeaks.cpp
+++ b/Code/Mantid/Framework/Algorithms/src/StripPeaks.cpp
@@ -109,6 +109,8 @@ API::ITableWorkspace_sptr StripPeaks::findPeaks(API::MatrixWorkspace_sptr WS) {
   bool highbackground = getProperty("HighBackground");
   std::vector<double> peakpositions = getProperty("PeakPositions");
   double peakpostol = getProperty("PeakPositionTolerance");
+  if (peakpostol < 0.)
+      peakpostol = EMPTY_DBL();
 
   // Set up and execute algorithm
   bool showlog = true;
@@ -213,12 +215,39 @@ StripPeaks::removePeaks(API::MatrixWorkspace_const_sptr input,
                       << ". Error: Peak fit with too wide peak width" << width
                       << " denoted by chi^2 = " << chisq << " <= 0. \n";
     }
+    {
+        auto left = lower_bound(X.begin(), X.end(), centre);
+        double delta_d = (*left) - (*(left-1));
+        if ((width/delta_d) < 1.) {
+            g_log.warning() << "StripPeaks():  Peak Index = " << i
+                            << " @ X = " << centre
+                            << "  Error: Peak fit with too narrow of peak "
+                            << "delta_d = " << delta_d
+                            << " sigma/delta_d = " << (width/delta_d) << "\n";
+            continue;
+        }
+    }
 
     g_log.information() << "Subtracting peak " << i << " from spectrum "
                         << peakslist->getRef<int>("spectrum", i)
                         << " at x = " << centre << " h = " << height
                         << " s = " << width << " chi2 = " << chisq << "\n";
 
+    {   // log the background function
+        double a0 = 0.;
+        double a1 = 0.;
+        double a2 = 0.;
+        const std::vector<std::string> columnNames = peakslist->getColumnNames();
+        if (std::find(columnNames.begin(), columnNames.end(), "A0") != columnNames.end())
+            a0 = peakslist->getRef<double>("A0", i);
+        if (std::find(columnNames.begin(), columnNames.end(), "A1") != columnNames.end())
+            a1 = peakslist->getRef<double>("A1", i);
+        if (std::find(columnNames.begin(), columnNames.end(), "A2") != columnNames.end())
+            a2 = peakslist->getRef<double>("A2", i);
+        g_log.information() << "     background = " << a0 << " + "
+                            << a1 << " x + " << a2 << " x^2\n";
+    }
+
     // Loop over the spectrum elements
     const int spectrumLength = static_cast<int>(Y.size());
     for (int j = 0; j < spectrumLength; ++j) {
diff --git a/Code/Mantid/Framework/Algorithms/test/StripPeaksTest.h b/Code/Mantid/Framework/Algorithms/test/StripPeaksTest.h
index 8e3614fa09699e5f226ed53da78356a2d50c9bc9..8f0d2cf54a102f7025befa780ad67368ad673f33 100644
--- a/Code/Mantid/Framework/Algorithms/test/StripPeaksTest.h
+++ b/Code/Mantid/Framework/Algorithms/test/StripPeaksTest.h
@@ -36,8 +36,8 @@ public:
 
       // Spectrum 1
       const double x = (X[i]+X[i+1])/2;
-      double funcVal = 2500*exp(-0.5*pow((x-3.14)/0.012,2));
-      funcVal += 1000*exp(-0.5*pow((x-1.22)/0.01,2));
+      double funcVal = 2500*exp(-0.5*pow((x-3.14)/0.022,2));
+      funcVal += 1000*exp(-0.5*pow((x-1.22)/0.02,2));
       Y1[i] = 5000 + funcVal;
       E1[i] = sqrt(Y1[i]);
     }
diff --git a/Code/Mantid/Framework/Crystal/CMakeLists.txt b/Code/Mantid/Framework/Crystal/CMakeLists.txt
index 2883188735a0ce129e690cdaddeba2e504be9a13..fb86a1a5fc41282d095c5183d9a86fd4127065d9 100644
--- a/Code/Mantid/Framework/Crystal/CMakeLists.txt
+++ b/Code/Mantid/Framework/Crystal/CMakeLists.txt
@@ -214,6 +214,12 @@ if(UNITY_BUILD)
   enable_unity_build(Crystal SRC_FILES SRC_UNITY_IGNORE_FILES 10)
 endif(UNITY_BUILD)
 
+if (COVERALLS)
+    foreach( loop_var ${SRC_FILES} ${INC_FILES})
+      set_property(GLOBAL APPEND PROPERTY COVERAGE_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/${loop_var}")
+    endforeach(loop_var)
+endif()
+
 # Add the target for this directory
 add_library ( Crystal ${SRC_FILES} ${INC_FILES})
 # Set the name of the generated library
diff --git a/Code/Mantid/Framework/CurveFitting/CMakeLists.txt b/Code/Mantid/Framework/CurveFitting/CMakeLists.txt
index 071d416d4897cfd1dd939bee9362cf7c665f8f2a..a39e4c433ab8ccefd173e68f713a7740a2070bb3 100644
--- a/Code/Mantid/Framework/CurveFitting/CMakeLists.txt
+++ b/Code/Mantid/Framework/CurveFitting/CMakeLists.txt
@@ -335,6 +335,11 @@ set ( TEST_FILES
 	VoigtTest.h
 )
 
+if (COVERALLS)
+    foreach( loop_var ${SRC_FILES} ${INC_FILES})
+      set_property(GLOBAL APPEND PROPERTY COVERAGE_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/${loop_var}")
+    endforeach(loop_var)
+endif()
 
 if(UNITY_BUILD)
   include(UnityBuild)
diff --git a/Code/Mantid/Framework/DataHandling/CMakeLists.txt b/Code/Mantid/Framework/DataHandling/CMakeLists.txt
index 13074e09f670dace8be02e69fdd495d1567e2f9a..ceab2f6f9fba6b7000b8d95e8d1cf58f2fde7d0f 100644
--- a/Code/Mantid/Framework/DataHandling/CMakeLists.txt
+++ b/Code/Mantid/Framework/DataHandling/CMakeLists.txt
@@ -445,6 +445,11 @@ set ( TEST_FILES
 	XMLInstrumentParameterTest.h
 )
 
+if (COVERALLS)
+    foreach( loop_var ${SRC_FILES} ${INC_FILES})
+      set_property(GLOBAL APPEND PROPERTY COVERAGE_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/${loop_var}")
+    endforeach(loop_var)
+endif()
 
 if(UNITY_BUILD)
   include(UnityBuild)
diff --git a/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/AppendGeometryToSNSNexus.h b/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/AppendGeometryToSNSNexus.h
index a02abe22617634cd39193239804391523a72ae83..82d4978d6b021e440694cf523f18c3400b8a0800 100644
--- a/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/AppendGeometryToSNSNexus.h
+++ b/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/AppendGeometryToSNSNexus.h
@@ -76,17 +76,14 @@ private:
   /// Are we going to make a copy of the NeXus file to operate on ?
   bool m_makeNexusCopy;
 
-  /// Algorithm progress keeper
-  API::Progress *progress;
-
   /// The workspace to load instrument and logs
   API::MatrixWorkspace_sptr ws;
 
   /// Was the instrument loaded?
-  bool instrument_loaded_correctly;
+  bool m_instrumentLoadedCorrectly;
 
   /// Were the logs loaded?
-  bool logs_loaded_correctly;
+  bool m_logsLoadedCorrectly;
 };
 
 } // namespace DataHandling
diff --git a/Code/Mantid/Framework/DataHandling/src/AppendGeometryToSNSNexus.cpp b/Code/Mantid/Framework/DataHandling/src/AppendGeometryToSNSNexus.cpp
index 87765f23b5cd677a68cbb3c9da79610ba950f6ec..a4f22442efce17b553a40dd701d4968dbbab8ceb 100644
--- a/Code/Mantid/Framework/DataHandling/src/AppendGeometryToSNSNexus.cpp
+++ b/Code/Mantid/Framework/DataHandling/src/AppendGeometryToSNSNexus.cpp
@@ -23,7 +23,9 @@ DECLARE_ALGORITHM(AppendGeometryToSNSNexus)
 //----------------------------------------------------------------------------------------------
 /** Constructor
  */
-AppendGeometryToSNSNexus::AppendGeometryToSNSNexus() {}
+AppendGeometryToSNSNexus::AppendGeometryToSNSNexus()
+    : m_makeNexusCopy(false), m_instrumentLoadedCorrectly(false),
+      m_logsLoadedCorrectly(false) {}
 
 //----------------------------------------------------------------------------------------------
 /** Destructor
@@ -144,23 +146,23 @@ void AppendGeometryToSNSNexus::exec() {
   if (m_instrument == "HYSPEC" || m_instrument == "HYSPECA" ||
       m_instrument == "SNAP") {
     g_log.debug() << "Run LoadNexusLogs Child Algorithm." << std::endl;
-    logs_loaded_correctly = runLoadNexusLogs(m_filename, ws, this);
+    m_logsLoadedCorrectly = runLoadNexusLogs(m_filename, ws, this);
 
-    if (!logs_loaded_correctly)
+    if (!m_logsLoadedCorrectly)
       throw std::runtime_error("Failed to run LoadNexusLogs Child Algorithm.");
   }
 
   g_log.debug() << "Run LoadInstrument Child Algorithm." << std::endl;
-  instrument_loaded_correctly = runLoadInstrument(m_idf_filename, ws, this);
+  m_instrumentLoadedCorrectly = runLoadInstrument(m_idf_filename, ws, this);
 
-  if (!instrument_loaded_correctly)
+  if (!m_instrumentLoadedCorrectly)
     throw std::runtime_error("Failed to run LoadInstrument Child Algorithm.");
 
   // Get the number of detectors (just for progress reporting)
   // Get the number of histograms/detectors
   const size_t numDetectors = ws->getInstrument()->getDetectorIDs().size();
 
-  this->progress = new API::Progress(this, 0.0, 1.0, numDetectors);
+  API::Progress progress(this, 0.0, 1.0, numDetectors);
 
   // Get the instrument
   Geometry::Instrument_const_sptr instrument = ws->getInstrument();
@@ -250,7 +252,7 @@ void AppendGeometryToSNSNexus::exec() {
 
                 nxfile.closeGroup(); // close NXdetector
 
-                this->progress->report(dets.size());
+                progress.report(dets.size());
               } else {
                 throw std::runtime_error(
                     "Could not find any detectors for the bank named " +
diff --git a/Code/Mantid/Framework/DataHandling/src/FilterEventsByLogValuePreNexus.cpp b/Code/Mantid/Framework/DataHandling/src/FilterEventsByLogValuePreNexus.cpp
index 5cc06ebf6e86a781b91f52a8d8ad9840a1affc7b..7a1cdbedc406bad20d23cd982068f19e4bbf93cb 100644
--- a/Code/Mantid/Framework/DataHandling/src/FilterEventsByLogValuePreNexus.cpp
+++ b/Code/Mantid/Framework/DataHandling/src/FilterEventsByLogValuePreNexus.cpp
@@ -202,8 +202,15 @@ static string generateMappingfileName(EventWorkspace_sptr &wksp) {
 /** Constructor
 */
 FilterEventsByLogValuePreNexus::FilterEventsByLogValuePreNexus()
-    : Mantid::API::IFileLoader<Kernel::FileDescriptor>(), eventfile(NULL),
-      m_maxNumEvents(0) {}
+    : Mantid::API::IFileLoader<Kernel::FileDescriptor>(), proton_charge_tot(0),
+      detid_max(0), eventfile(NULL), num_events(0), num_pulses(0), numpixel(0),
+      num_good_events(0), num_error_events(0), num_bad_events(0),
+      num_wrongdetid_events(0), num_ignored_events(0), first_event(0),
+      m_maxNumEvents(0), using_mapping_file(false), loadOnlySomeSpectra(false),
+      longest_tof(0.0), shortest_tof(0.0), parallelProcessing(false),
+      pulsetimesincreasing(false), m_throwError(true), m_examEventLog(false),
+      m_pixelid2exam(0), m_numevents2write(0), m_freqHz(0), istep(0),
+      m_dbPixelID(0), m_useDBOutput(false), m_corretctTOF(false) {}
 
 //----------------------------------------------------------------------------------------------
 /** Desctructor
@@ -740,13 +747,22 @@ void FilterEventsByLogValuePreNexus::doStatToEventLog(size_t mindex) {
       max_dt = temp_dt;
   }
 
-  double avg_dt = static_cast<double>(sum_dt) / static_cast<double>(nbins - 1);
+  if ( nbins - 1 ) {
+    double avg_dt = static_cast<double>(sum_dt) / static_cast<double>(nbins - 1);
+    g_log.information() << "Event log of map index " << mindex
+      << ": Avg(dt) = " << avg_dt * 1.0E-9
+      << ", Min(dt) = " << static_cast<double>(min_dt) * 1.0E-9
+      << ", Max(dt) = " << static_cast<double>(max_dt) * 1.0E-9
+      << "\n";
+  } else {
+    g_log.information() << "Event log of map index " << mindex
+      << ": Avg(dt) = " << static_cast<double>(sum_dt) * 1.0E-9
+      << ", Min(dt) = " << static_cast<double>(min_dt) * 1.0E-9
+      << ", Max(dt) = " << static_cast<double>(max_dt) * 1.0E-9
+      << "\n";
+
+  }
 
-  g_log.information() << "Event log of map index " << mindex
-                      << ": Avg(dt) = " << avg_dt * 1.0E-9
-                      << ", Min(dt) = " << static_cast<double>(min_dt) * 1.0E-9
-                      << ", Max(dt) = " << static_cast<double>(max_dt) * 1.0E-9
-                      << "\n";
   g_log.information() << "Number of zero-interval eveng log = " << numzeros
                       << "\n";
 
diff --git a/Code/Mantid/Framework/DataHandling/src/SaveISISNexus.cpp b/Code/Mantid/Framework/DataHandling/src/SaveISISNexus.cpp
index ade4e26476fde8bd4e6abdb9cbf629614bfd6739..9313b64044e0758ba5cb268c6ed74b878b9953f1 100644
--- a/Code/Mantid/Framework/DataHandling/src/SaveISISNexus.cpp
+++ b/Code/Mantid/Framework/DataHandling/src/SaveISISNexus.cpp
@@ -37,7 +37,10 @@ using namespace Kernel;
 using namespace API;
 
 /// Empty default constructor
-SaveISISNexus::SaveISISNexus() : Algorithm() {}
+SaveISISNexus::SaveISISNexus()
+    : Algorithm(), m_isisRaw(), handle(), rawFile(), nper(0), nsp(0), ntc(0),
+      nmon(0), ndet(0), counts_link(), period_index_link(),
+      spectrum_index_link(), time_of_flight_link(), time_of_flight_raw_link() {}
 
 /** Initialisation method.
  *
diff --git a/Code/Mantid/Framework/DataHandling/src/SaveNexusProcessed.cpp b/Code/Mantid/Framework/DataHandling/src/SaveNexusProcessed.cpp
index 7f0833ecbf64939ceacdca1f557b728e71a76248..c6778b15c89d26ddd5777b780f86d93942d5e3b0 100644
--- a/Code/Mantid/Framework/DataHandling/src/SaveNexusProcessed.cpp
+++ b/Code/Mantid/Framework/DataHandling/src/SaveNexusProcessed.cpp
@@ -36,7 +36,7 @@ typedef NeXus::NexusFileIO::optional_size_t optional_size_t;
 DECLARE_ALGORITHM(SaveNexusProcessed)
 
 /// Empty default constructor
-SaveNexusProcessed::SaveNexusProcessed() : Algorithm() {}
+SaveNexusProcessed::SaveNexusProcessed() : Algorithm(), m_timeProgInit(0.0), prog() {}
 
 //-----------------------------------------------------------------------------------------------
 /** Initialisation method.
diff --git a/Code/Mantid/Framework/DataHandling/src/SaveToSNSHistogramNexus.cpp b/Code/Mantid/Framework/DataHandling/src/SaveToSNSHistogramNexus.cpp
index 5199815d7124e54304aeb297e5518368933aa5ae..2db400089273d08c819a10da4b8de63da8b4dc06 100644
--- a/Code/Mantid/Framework/DataHandling/src/SaveToSNSHistogramNexus.cpp
+++ b/Code/Mantid/Framework/DataHandling/src/SaveToSNSHistogramNexus.cpp
@@ -39,7 +39,7 @@ using namespace DataObjects;
 using namespace Geometry;
 
 /// Empty default constructor
-SaveToSNSHistogramNexus::SaveToSNSHistogramNexus() : Algorithm() {}
+SaveToSNSHistogramNexus::SaveToSNSHistogramNexus() : Algorithm(), prog(), m_compress(false), links_count(0), inId(), outId() {}
 
 /** Initialisation method.
  *
diff --git a/Code/Mantid/Framework/DataObjects/CMakeLists.txt b/Code/Mantid/Framework/DataObjects/CMakeLists.txt
index 318f1d982611be403ce982adcc414c1a928cc833..734324adf0aaf055e8673074407ac2254a7a1eca 100644
--- a/Code/Mantid/Framework/DataObjects/CMakeLists.txt
+++ b/Code/Mantid/Framework/DataObjects/CMakeLists.txt
@@ -178,6 +178,12 @@ if(UNITY_BUILD)
   enable_unity_build(DataObjects SRC_FILES SRC_UNITY_IGNORE_FILES 10)
 endif(UNITY_BUILD)
 
+if (COVERALLS)
+    foreach( loop_var ${SRC_FILES} ${INC_FILES})
+      set_property(GLOBAL APPEND PROPERTY COVERAGE_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/${loop_var}")
+    endforeach(loop_var)
+endif()
+
 # Use a precompiled header where they are supported
 enable_precompiled_headers( inc/MantidDataObjects/PrecompiledHeader.h SRC_FILES )
 # Add the target for this directory
diff --git a/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/MDEventWorkspace.h b/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/MDEventWorkspace.h
index a1e927591f525c2ef21ea726a0b0d3d65cdf4e86..7aa12bd47f0dcda39112e843c59c6e928fb3cd80 100644
--- a/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/MDEventWorkspace.h
+++ b/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/MDEventWorkspace.h
@@ -162,6 +162,9 @@ public:
   /// and close back-up files.
   virtual void clearFileBacked(bool LoadFileBackedData);
 
+  /// Preferred visual normalization method.
+  virtual Mantid::API::MDNormalization displayNormalization() const;
+
 protected:
   /** MDBox containing all of the events in the workspace. */
   MDBoxBase<MDE, nd> *data;
diff --git a/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/MDHistoWorkspace.h b/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/MDHistoWorkspace.h
index 67a4238e2aac3f5ca77faa5426620a87a89ac0a8..d990b398465bdbfaa08bc6d849901a04c5811a7b 100644
--- a/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/MDHistoWorkspace.h
+++ b/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/MDHistoWorkspace.h
@@ -381,6 +381,9 @@ public:
   /// Virutal constructor.
   boost::shared_ptr<IMDHistoWorkspace> clone() const;
 
+  /// Preferred visual normalization method.
+  virtual Mantid::API::MDNormalization displayNormalization() const;
+
 private:
   void initVertexesArray();
 
diff --git a/Code/Mantid/Framework/DataObjects/src/MDEventWorkspace.cpp b/Code/Mantid/Framework/DataObjects/src/MDEventWorkspace.cpp
index 6fe12748021e7675555bc45748cb5042b14c3aab..f901ec4eeebe2e41c6bb47113f9a8a0b10ef5f52 100644
--- a/Code/Mantid/Framework/DataObjects/src/MDEventWorkspace.cpp
+++ b/Code/Mantid/Framework/DataObjects/src/MDEventWorkspace.cpp
@@ -799,6 +799,13 @@ TMDE(void MDEventWorkspace)::setCoordinateSystem(
   m_coordSystem = coordSystem;
 }
 
+/**
+Return the preferred normalization to use for visualization.
+*/
+TMDE(MDNormalization MDEventWorkspace)::displayNormalization() const {
+  return VolumeNormalization; // volume normalization preferred for display purposes.
+}
+
 } // namespace DataObjects
 
 } // namespace Mantid
diff --git a/Code/Mantid/Framework/DataObjects/src/MDHistoWorkspace.cpp b/Code/Mantid/Framework/DataObjects/src/MDHistoWorkspace.cpp
index ffd19c151f406eb4a905239352a685e7aeae4964..2382517f7dbe77c0c6cbd1e1aa010814da1e9b7f 100644
--- a/Code/Mantid/Framework/DataObjects/src/MDHistoWorkspace.cpp
+++ b/Code/Mantid/Framework/DataObjects/src/MDHistoWorkspace.cpp
@@ -1224,5 +1224,12 @@ boost::shared_ptr<IMDHistoWorkspace> MDHistoWorkspace::clone() const {
   return boost::shared_ptr<IMDHistoWorkspace>(new MDHistoWorkspace(*this));
 }
 
+/**
+Preferred normalization to use for visual purposes.
+*/
+MDNormalization MDHistoWorkspace::displayNormalization() const {
+  return NumEventsNormalization; // Normalize by the number of events.
+}
+
 } // namespace Mantid
 } // namespace DataObjects
diff --git a/Code/Mantid/Framework/GPUAlgorithms/CMakeLists.txt b/Code/Mantid/Framework/GPUAlgorithms/CMakeLists.txt
index 3bbf129d9375b0b4a3f248e7637a6b30190a2835..280b31fec8a1555994ee1fa89f28bd17dab7803b 100644
--- a/Code/Mantid/Framework/GPUAlgorithms/CMakeLists.txt
+++ b/Code/Mantid/Framework/GPUAlgorithms/CMakeLists.txt
@@ -20,6 +20,11 @@ set ( KERNEL_FILES
 	GPUTester_kernel.cl
 )
 
+if (COVERALLS)
+    foreach( loop_var ${SRC_FILES} ${INC_FILES})
+      set_property(GLOBAL APPEND PROPERTY COVERAGE_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/${loop_var}")
+    endforeach(loop_var)
+endif()
 
 # Add the target for this directory
 add_library ( GPUAlgorithms ${SRC_FILES} ${INC_FILES} )
diff --git a/Code/Mantid/Framework/Geometry/CMakeLists.txt b/Code/Mantid/Framework/Geometry/CMakeLists.txt
index e3dcd91ad41ca2a0c92a4e1b8f274280b0f21460..7389720b3265828195bfbca561ffaed6c8955758 100644
--- a/Code/Mantid/Framework/Geometry/CMakeLists.txt
+++ b/Code/Mantid/Framework/Geometry/CMakeLists.txt
@@ -336,6 +336,11 @@ set ( GMOCK_TEST_FILES
   MDGeometryXMLBuilderTest.h
 )
 
+if (COVERALLS)
+    foreach( loop_var ${SRC_FILES} ${INC_FILES})
+      set_property(GLOBAL APPEND PROPERTY COVERAGE_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/${loop_var}")
+    endforeach(loop_var)
+endif()
 
 if(UNITY_BUILD)
   include(UnityBuild)
diff --git a/Code/Mantid/Framework/Geometry/inc/MantidGeometry/Crystal/Group.h b/Code/Mantid/Framework/Geometry/inc/MantidGeometry/Crystal/Group.h
index 0e7e562c557e102be9092f3716d62cc91351ad02..41dc4ef31e92b524daf2d48b6b40e2fa8c1d5f6e 100644
--- a/Code/Mantid/Framework/Geometry/inc/MantidGeometry/Crystal/Group.h
+++ b/Code/Mantid/Framework/Geometry/inc/MantidGeometry/Crystal/Group.h
@@ -134,6 +134,13 @@ public:
     Hexagonal
   };
 
+  enum GroupAxiom {
+    Closure,
+    Identity,
+    Inversion,
+    Associativity
+  };
+
   Group();
   Group(const std::string &symmetryOperationString);
   Group(const std::vector<SymmetryOperation> &symmetryOperations);
@@ -145,6 +152,7 @@ public:
   size_t order() const;
   CoordinateSystem getCoordinateSystem() const;
   std::vector<SymmetryOperation> getSymmetryOperations() const;
+  bool containsOperation(const SymmetryOperation &operation) const;
 
   Group operator*(const Group &other) const;
 
@@ -153,6 +161,9 @@ public:
   bool operator==(const Group &other) const;
   bool operator!=(const Group &other) const;
 
+  bool fulfillsAxiom(GroupAxiom axiom) const;
+  bool isGroup() const;
+
 protected:
   void setSymmetryOperations(
       const std::vector<SymmetryOperation> &symmetryOperations);
@@ -160,6 +171,11 @@ protected:
   CoordinateSystem getCoordinateSystemFromOperations(
       const std::vector<SymmetryOperation> &symmetryOperations) const;
 
+  bool isClosed() const;
+  bool hasIdentity() const;
+  bool eachElementHasInverse() const;
+  bool associativityHolds() const;
+
   std::vector<SymmetryOperation> m_allOperations;
   std::set<SymmetryOperation> m_operationSet;
   CoordinateSystem m_axisSystem;
@@ -175,6 +191,14 @@ template <typename T>
 Group_const_sptr create(const std::string &initializationString) {
   return boost::make_shared<const T>(initializationString);
 }
+
+/// Creates a Group sub-class of type T if T has a constructor that takes a
+/// vector of SymmetryOperations.
+template <typename T>
+Group_const_sptr
+create(const std::vector<SymmetryOperation> &symmetryOperations) {
+  return boost::make_shared<const T>(symmetryOperations);
+}
 }
 
 MANTID_GEOMETRY_DLL Group_const_sptr
diff --git a/Code/Mantid/Framework/Geometry/inc/MantidGeometry/Crystal/SymmetryOperation.h b/Code/Mantid/Framework/Geometry/inc/MantidGeometry/Crystal/SymmetryOperation.h
index d28a2837fd2e98daf690ee48e5c95f084c84cb56..aeef5601af896342ea6e9a66244743004c6fe7ae 100644
--- a/Code/Mantid/Framework/Geometry/inc/MantidGeometry/Crystal/SymmetryOperation.h
+++ b/Code/Mantid/Framework/Geometry/inc/MantidGeometry/Crystal/SymmetryOperation.h
@@ -125,7 +125,7 @@ public:
   SymmetryOperation(const SymmetryOperation &other);
   SymmetryOperation &operator=(const SymmetryOperation &other);
 
-  virtual ~SymmetryOperation() {}
+  ~SymmetryOperation() {}
 
   const Kernel::IntMatrix &matrix() const;
   const V3R &vector() const;
@@ -170,6 +170,11 @@ protected:
   std::string m_identifier;
 };
 
+MANTID_GEOMETRY_DLL std::ostream &operator<<(
+    std::ostream &stream, const SymmetryOperation &operation);
+MANTID_GEOMETRY_DLL std::istream &operator>>(std::istream &stream,
+                                             SymmetryOperation &operation);
+
 MANTID_GEOMETRY_DLL V3R getWrappedVector(const V3R &vector);
 MANTID_GEOMETRY_DLL Kernel::V3D getWrappedVector(const Kernel::V3D &vector);
 
diff --git a/Code/Mantid/Framework/Geometry/src/Crystal/Group.cpp b/Code/Mantid/Framework/Geometry/src/Crystal/Group.cpp
index 8eb35261ee09a635977655938b05afd04c5e8595..e82bc33fe48999610a3a73270d8d3eb64603dec4 100644
--- a/Code/Mantid/Framework/Geometry/src/Crystal/Group.cpp
+++ b/Code/Mantid/Framework/Geometry/src/Crystal/Group.cpp
@@ -52,6 +52,12 @@ std::vector<SymmetryOperation> Group::getSymmetryOperations() const {
   return m_allOperations;
 }
 
+/// Returns true if the group contains the supplied operation.
+bool Group::containsOperation(const SymmetryOperation &operation) const {
+  return std::find(m_allOperations.begin(), m_allOperations.end(), operation) !=
+         m_allOperations.end();
+}
+
 /**
  * Multiplication operator of two groups.
  *
@@ -101,6 +107,39 @@ bool Group::operator!=(const Group &other) const {
   return !(this->operator==(other));
 }
 
+/// Checks whether a certain group axiom is fulfilled, can be used as a more
+/// fine-grained alternative to isGroup().
+bool Group::fulfillsAxiom(GroupAxiom axiom) const {
+  switch (axiom) {
+  case Closure:
+    return isClosed();
+  case Identity:
+    return hasIdentity();
+  case Inversion:
+    return eachElementHasInverse();
+  case Associativity:
+    return associativityHolds();
+  default:
+    return false;
+  }
+}
+
+/**
+ * Returns whether the group fulfills the four group axioms
+ *
+ * When a Group is constructed from a list of symmetry operations, no checks
+ * are performed whether this set of operations fulfills the four group axioms,
+ * i.e. whether it is a group at all. If you are not sure whether a set of
+ * symmetry operations is a group, construct one and look at the return value
+ * of this method.
+ *
+ * @return True if group axioms are fulfilled, false otherwise.
+ */
+bool Group::isGroup() const {
+  return isClosed() && hasIdentity() && eachElementHasInverse() &&
+         associativityHolds();
+}
+
 /// Assigns symmetry operations, throws std::invalid_argument if vector is
 /// empty.
 void Group::setSymmetryOperations(
@@ -131,7 +170,67 @@ Group::CoordinateSystem Group::getCoordinateSystemFromOperations(
   return Group::Orthogonal;
 }
 
-/// Convenience operator* for directly multiplying groups using shared pointers.
+/// Returns true if the group is closed, i.e. all elements of G * G are in G.
+bool Group::isClosed() const {
+  Group result = (*this) * (*this);
+
+  // If the order is different, there are additional or fewer elements
+  if (result.order() != order()) {
+    return false;
+  }
+
+  // Also, all operations need to be equal.
+  std::vector<SymmetryOperation> ops = result.getSymmetryOperations();
+  for (size_t i = 0; i < ops.size(); ++i) {
+    if (ops[i] != m_allOperations[i]) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+/// Returns true if the group has the identity element.
+bool Group::hasIdentity() const {
+  // Since the identity element does not change, this is an easy check.
+  return containsOperation(SymmetryOperation());
+}
+
+/// Returns true if the inverse of each element is in the group
+bool Group::eachElementHasInverse() const {
+  // Iterate through all operations, check that the inverse is in the group.
+  for (auto op = m_allOperations.begin(); op != m_allOperations.end(); ++op) {
+    if (!containsOperation((*op).inverse())) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+/**
+ * Checks that associativity holds, i.e. (a*b)*c == a*(b*c)
+ *
+ * In fact, this method returns always true, because associativity is implicitly
+ * contained in the definition of the binary operator of SymmetryOperation:
+ *
+ *      (S1 * S2) * S3
+ *      = (W1*W2, W1*w2 + w1) * S3
+ *      = (W1*W2*W3, W1*W2*w3 + W1*w2 + w1)
+ *
+ *      S1 * (S2 * S3)
+ *      = S1 * (W2*W3, W2*w3 + w2)
+ *      = (W1*W2*W3, W1*W2*w3 + W1*w2 + w1)
+ *
+ * No matter what symmetry operations are chosen, this always holds. However,
+ * for completeness the method has been added anyway.
+ *
+ * @return True if associativity holds
+ */
+bool Group::associativityHolds() const { return true; }
+
+/// Convenience operator* for directly multiplying groups using shared
+/// pointers.
 Group_const_sptr operator*(const Group_const_sptr &lhs,
                            const Group_const_sptr &rhs) {
   if (!lhs || !rhs) {
diff --git a/Code/Mantid/Framework/Geometry/src/Crystal/SymmetryOperation.cpp b/Code/Mantid/Framework/Geometry/src/Crystal/SymmetryOperation.cpp
index afc64229a1423409b2cad6d4bb527f7277d4b00c..96fcbaf8c8151ae43d31063606034f1144307cdb 100644
--- a/Code/Mantid/Framework/Geometry/src/Crystal/SymmetryOperation.cpp
+++ b/Code/Mantid/Framework/Geometry/src/Crystal/SymmetryOperation.cpp
@@ -271,5 +271,31 @@ Kernel::V3D getWrappedVector(const Kernel::V3D &vector) {
   return wrappedVector;
 }
 
+/// Stream output operator, writes the identifier to stream.
+std::ostream &operator<<(std::ostream &stream,
+                         const SymmetryOperation &operation) {
+  stream << "[" + operation.identifier() + "]";
+
+  return stream;
+}
+
+/// Reads identifier from stream and tries to parse as a symbol.
+std::istream &operator>>(std::istream &stream, SymmetryOperation &operation) {
+  std::string identifier;
+  std::getline(stream, identifier);
+
+  size_t i = identifier.find_first_of('[');
+  size_t j = identifier.find_last_of(']');
+
+  if (i == std::string::npos || j == std::string::npos) {
+    throw std::runtime_error(
+        "Cannot construct SymmetryOperation from identifier: " + identifier);
+  }
+
+  operation = SymmetryOperation(identifier.substr(i + 1, j - i - 1));
+
+  return stream;
+}
+
 } // namespace Geometry
 } // namespace Mantid
diff --git a/Code/Mantid/Framework/Geometry/src/Instrument/IDFObject.cpp b/Code/Mantid/Framework/Geometry/src/Instrument/IDFObject.cpp
index cc58677b36077d7e44f281a820c876539fcef2e0..35e8dd10d470dd820076b929ce8337965b9bd00f 100644
--- a/Code/Mantid/Framework/Geometry/src/Instrument/IDFObject.cpp
+++ b/Code/Mantid/Framework/Geometry/src/Instrument/IDFObject.cpp
@@ -1,5 +1,7 @@
 #include "MantidGeometry/Instrument/IDFObject.h"
+#include "MantidKernel/ChecksumHelper.h"
 #include <Poco/DateTimeFormatter.h>
+#include <Poco/String.h>
 
 namespace Mantid {
 namespace Geometry {
@@ -87,7 +89,9 @@ Gets the idf file as a mangled name.
 @return the idf file as a mangled name.
 */
 std::string IDFObject::getMangledName() const {
-  return this->getFileNameOnly() + this->getFormattedLastModified();
+  std::string idfText = Kernel::ChecksumHelper::loadFile(getFileFullPathStr(),true);
+  std::string checksum = Kernel::ChecksumHelper::sha1FromString(Poco::trim(idfText));
+  return this->getFileNameOnly() + checksum;
 }
 
 /**
diff --git a/Code/Mantid/Framework/Geometry/src/Instrument/InstrumentDefinitionParser.cpp b/Code/Mantid/Framework/Geometry/src/Instrument/InstrumentDefinitionParser.cpp
index f14e379c81cbc756d4a8456a16a36e581701a44c..7a1242493c94d906691087439cdae7bab1560d4b 100644
--- a/Code/Mantid/Framework/Geometry/src/Instrument/InstrumentDefinitionParser.cpp
+++ b/Code/Mantid/Framework/Geometry/src/Instrument/InstrumentDefinitionParser.cpp
@@ -11,11 +11,13 @@
 #include "MantidGeometry/Rendering/vtkGeometryCacheReader.h"
 #include "MantidGeometry/Rendering/vtkGeometryCacheWriter.h"
 #include "MantidKernel/ConfigService.h"
+#include "MantidKernel/ChecksumHelper.h"
 #include "MantidKernel/Logger.h"
 #include "MantidKernel/ProgressBase.h"
 #include "MantidKernel/UnitFactory.h"
 #include "MantidKernel/Strings.h"
 
+#include <Poco/String.h>
 #include <Poco/DOM/Document.h>
 #include <Poco/DOM/DOMParser.h>
 #include <Poco/DOM/DOMWriter.h>
@@ -27,6 +29,7 @@
 
 #include <boost/make_shared.hpp>
 #include <boost/assign/list_of.hpp>
+#include <MantidKernel/ChecksumHelper.h>
 
 using namespace Mantid;
 using namespace Mantid::Kernel;
@@ -151,19 +154,16 @@ void InstrumentDefinitionParser::initialize(
  *attribute of the XML contents
  * */
 std::string InstrumentDefinitionParser::getMangledName() {
+  
   // Use the file in preference if possible.
   if (this->m_xmlFile->exists()) {
     return m_xmlFile->getMangledName();
-  } else if (!pDoc.isNull()) {
-    std::string lastModified = pRootElem->getAttribute("last-modified");
-    if (lastModified.empty()) {
-      g_log.warning() << "The IDF that you are using doesn't contain a "
-                         "'last-modified' field. ";
-      g_log.warning() << "You may not get the correct definition file loaded."
-                      << std::endl;
-    }
-    return m_instName + lastModified;
-  } else {
+  } 
+  auto xml = Poco::trim(m_instrument->getXmlText());
+  if (!(xml.empty())) {
+    std::string checksum = Kernel::ChecksumHelper::sha1FromString(xml);
+    return m_instName + checksum;
+  } else  {
     throw std::runtime_error(
         "Call InstrumentDefinitionParser::initialize() before getMangledName.");
   }
diff --git a/Code/Mantid/Framework/Geometry/test/GroupTest.h b/Code/Mantid/Framework/Geometry/test/GroupTest.h
index 3ea24cf65c5c0fb5e82b68264bde3b72abc8f39c..b3256f6850575970d514b890b17e6d8a68aec962 100644
--- a/Code/Mantid/Framework/Geometry/test/GroupTest.h
+++ b/Code/Mantid/Framework/Geometry/test/GroupTest.h
@@ -220,6 +220,76 @@ public:
     TS_ASSERT(!lessThan(v7, v1));
   }
 
+  void testContainsOperation() {
+    Group group("x,y,z; -x,-y,-z");
+
+    std::vector<SymmetryOperation> ops = group.getSymmetryOperations();
+    TS_ASSERT(group.containsOperation(ops[0]));
+    TS_ASSERT(group.containsOperation(ops[1]));
+
+    SymmetryOperation mirror =
+        SymmetryOperationFactory::Instance().createSymOp("x,y,-z");
+
+    TS_ASSERT(!group.containsOperation(mirror));
+  }
+
+  void testGroupAxiomClosure() {
+    Group properGroup("x,y,z; -x,-y,-z; x,y,-z; -x,-y,z");
+    TS_ASSERT(properGroup.fulfillsAxiom(Group::Closure));
+
+    // Is not closed anymore
+    Group noClosure("x,y,z; -x,-y,-z; x,y,-z");
+    TS_ASSERT(!noClosure.fulfillsAxiom(Group::Closure));
+
+    // But the other axioms still hold
+    TS_ASSERT(noClosure.fulfillsAxiom(Group::Identity));
+    TS_ASSERT(noClosure.fulfillsAxiom(Group::Inversion));
+    TS_ASSERT(noClosure.fulfillsAxiom(Group::Associativity));
+  }
+
+  void testGroupAxiomIdentity() {
+    Group properGroup("x,y,z; -x,-y,-z; x,y,-z; -x,-y,z");
+    TS_ASSERT(properGroup.fulfillsAxiom(Group::Identity));
+
+    // Is does not have identity anymore
+    Group noIdentity("-x,-y,-z; x,y,-z");
+    TS_ASSERT(!noIdentity.fulfillsAxiom(Group::Identity));
+
+    // Closure is lost as well
+    TS_ASSERT(!noIdentity.fulfillsAxiom(Group::Closure));
+
+    // While the other two still hold
+    TS_ASSERT(noIdentity.fulfillsAxiom(Group::Inversion));
+    TS_ASSERT(noIdentity.fulfillsAxiom(Group::Associativity));
+  }
+
+  void testGroupAxiomInversion() {
+    Group properGroup("x,y,z; -x,-y,-z; x,y,-z; -x,-y,z");
+    TS_ASSERT(properGroup.fulfillsAxiom(Group::Inversion));
+
+    // Is does not have the identity anymore
+    Group noInversion("x,y,z; -y,x,z");
+    TS_ASSERT(!noInversion.fulfillsAxiom(Group::Inversion));
+
+    // Closure is lost as well
+    TS_ASSERT(!noInversion.fulfillsAxiom(Group::Closure));
+
+    // While the other two still hold
+    TS_ASSERT(noInversion.fulfillsAxiom(Group::Associativity));
+    TS_ASSERT(noInversion.fulfillsAxiom(Group::Identity));
+  }
+
+  void testIsGroup() {
+    Group properGroup("x,y,z; -x,-y,-z; x,y,-z; -x,-y,z");
+    TS_ASSERT(properGroup.isGroup());
+
+    Group noClosure("x,y,z; -x,-y,-z; x,y,-z");
+    TS_ASSERT(!noClosure.isGroup());
+
+    Group noIdentity("-x,-y,-z; x,y,-z; -x,-y,z");
+    TS_ASSERT(!noIdentity.isGroup());
+  }
+
   void testSmartPointerOperators() {
     // We take pointgroup -1
     std::vector<SymmetryOperation> inversion;
diff --git a/Code/Mantid/Framework/Geometry/test/IDFObjectTest.h b/Code/Mantid/Framework/Geometry/test/IDFObjectTest.h
index 36c7f0e9ba9581e92176338042c0272d5ee89c19..ff93226299f6413ec5d612071c4cf47a78e99a79 100644
--- a/Code/Mantid/Framework/Geometry/test/IDFObjectTest.h
+++ b/Code/Mantid/Framework/Geometry/test/IDFObjectTest.h
@@ -8,6 +8,11 @@
 #include <Poco/Path.h>
 #include <Poco/DateTimeFormatter.h>
 #include <Poco/Thread.h>
+#include <Poco/SHA1Engine.h>
+#include <Poco/String.h>
+#include <Poco/DigestStream.h>
+
+#include <boost/regex.hpp>
 
 using Mantid::Geometry::IDFObject;
 using Mantid::Kernel::ConfigService;
@@ -97,9 +102,41 @@ public:
   {
     const std::string filename = ConfigService::Instance().getInstrumentDirectory() + "/IDFs_for_UNIT_TESTING/IDF_for_UNIT_TESTING.xml";
     
-    Poco::File file(filename);
-    auto head = "IDF_for_UNIT_TESTING.xml";
-    auto tail = Poco::DateTimeFormatter::format(file.getLastModified(), "%Y-%d-%mT%H:%M:%S");
+    Poco::Path path(filename);
+
+    using Poco::DigestEngine;
+    using Poco::SHA1Engine;
+    using Poco::DigestOutputStream;
+
+    std::ifstream filein(filename.c_str(), std::ios::in | std::ios::binary);
+    if (!filein) {
+      TS_FAIL("Cannot open file: " + filename);
+      return;
+    }
+
+    std::string contents;
+    filein.seekg(0, std::ios::end);
+    contents.resize(filein.tellg());
+    filein.seekg(0, std::ios::beg);
+    filein.read(&contents[0], contents.size());
+    filein.close();
+
+    //convert to unix line endings
+    static boost::regex eol("\\R"); // \R is Perl syntax for matching any EOL sequence
+    contents = boost::regex_replace(contents, eol, "\n"); // converts all to LF
+
+    //and trim
+    contents = Poco::trim(contents);
+
+    SHA1Engine sha1;
+    DigestOutputStream outstr(sha1);
+    outstr << contents;
+    outstr.flush(); // to pass everything to the digest engine
+
+
+
+    auto head = path.getFileName();
+    auto tail = DigestEngine::digestToHex(sha1.digest());
     
     IDFObject obj(filename);
 
diff --git a/Code/Mantid/Framework/Geometry/test/PointGroupTest.h b/Code/Mantid/Framework/Geometry/test/PointGroupTest.h
index 0fd1f3159f44621aeb5150314179e077882d5799..765bcdcd7125a60ea0384c5724fe9bbd3c0f2b1f 100644
--- a/Code/Mantid/Framework/Geometry/test/PointGroupTest.h
+++ b/Code/Mantid/Framework/Geometry/test/PointGroupTest.h
@@ -24,6 +24,8 @@ public:
     {
         PointGroup_sptr testedPointGroup = PointGroupFactory::Instance().createPointGroup(name);
 
+        TSM_ASSERT(name + ": Does not fulfill group axioms!", testedPointGroup->isGroup());
+
         std::vector<V3D> equivalents = testedPointGroup->getEquivalents(hkl);
         // check that the number of equivalent reflections is as expected.
         TSM_ASSERT_EQUALS(name + ": Expected " + boost::lexical_cast<std::string>(numEquiv) + " equivalents, got " + boost::lexical_cast<std::string>(equivalents.size()) + " instead.", equivalents.size(), numEquiv);
diff --git a/Code/Mantid/Framework/Geometry/test/SymmetryOperationTest.h b/Code/Mantid/Framework/Geometry/test/SymmetryOperationTest.h
index 8db030c8868304b8f8b0637bc568fd777bc3617a..6eb759f2bea15be875837d487714a67da3df0b60 100644
--- a/Code/Mantid/Framework/Geometry/test/SymmetryOperationTest.h
+++ b/Code/Mantid/Framework/Geometry/test/SymmetryOperationTest.h
@@ -6,6 +6,7 @@
 #include "MantidGeometry/Crystal/SymmetryOperation.h"
 #include "MantidGeometry/Crystal/SymmetryOperationSymbolParser.h"
 
+#include "MantidKernel/Exception.h"
 #include "MantidKernel/V3D.h"
 
 #include <boost/make_shared.hpp>
@@ -276,6 +277,38 @@ public:
         TS_ASSERT_EQUALS(fourFoldZ^4, identity);
     }
 
+    void testStreamOperatorOut()
+    {
+        SymmetryOperation mirror("x,-y,z");
+
+        std::stringstream stream;
+        stream << mirror;
+
+        TS_ASSERT_EQUALS(stream.str(), "[x,-y,z]");
+    }
+
+    void testStreamOperatorIn()
+    {
+        std::stringstream stream;
+        stream << "[x,-y,z]";
+
+        SymmetryOperation mirror;
+        TS_ASSERT_DIFFERS(mirror.identifier(), "x,-y,z");
+
+        TS_ASSERT_THROWS_NOTHING(stream >> mirror);
+        TS_ASSERT_EQUALS(mirror.identifier(), "x,-y,z");
+
+        // no []
+        std::stringstream invalidBrackets;
+        invalidBrackets << "x,-y,z";
+        TS_ASSERT_THROWS(invalidBrackets >> mirror, std::runtime_error);
+
+        // invalid string
+        std::stringstream invalid;
+        invalid << "[someString]";
+        TS_ASSERT_THROWS(invalid >> mirror, Exception::ParseError);
+    }
+
 private:
     V3D applyOrderTimes(const SymmetryOperation &symOp, const V3D &vector)
     {
diff --git a/Code/Mantid/Framework/ICat/CMakeLists.txt b/Code/Mantid/Framework/ICat/CMakeLists.txt
index f559f9857ef2005102f355b0d882f91edeb3d51c..09c23e440c19493c68bbe2636d519ec307409728 100644
--- a/Code/Mantid/Framework/ICat/CMakeLists.txt
+++ b/Code/Mantid/Framework/ICat/CMakeLists.txt
@@ -65,6 +65,12 @@ set ( TEST_FILES
 	CompositeCatalogTest.h
 )
 
+if (COVERALLS)
+    foreach( loop_var ${SRC_FILES} ${INC_FILES})
+      set_property(GLOBAL APPEND PROPERTY COVERAGE_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/${loop_var}")
+    endforeach(loop_var)
+endif()
+
 if(UNITY_BUILD)
   include(UnityBuild)
   enable_unity_build(ICat SRC_FILES SRC_UNITY_IGNORE_FILES 10)
diff --git a/Code/Mantid/Framework/ICat/src/GSoap/stdsoap2.cpp b/Code/Mantid/Framework/ICat/src/GSoap/stdsoap2.cpp
index 042b3e75c62f0966c97cbdc5a5ac5dc22aeea36e..fa96113266c73be27a22d3373c46429c5964c357 100644
--- a/Code/Mantid/Framework/ICat/src/GSoap/stdsoap2.cpp
+++ b/Code/Mantid/Framework/ICat/src/GSoap/stdsoap2.cpp
@@ -2775,7 +2775,7 @@ struct soap_nlist *SOAP_FMAC2
         }
       }
     }
-    if (!p || !p->id)
+    if (!p->id)
       i = -1;
   }
   if (i >= 0)
@@ -4318,7 +4318,9 @@ again:
         soap->fclosesocket(soap, sk);
         return SOAP_INVALID_SOCKET;
       }
-      if (endpoint)
+      //if (endpoint) 
+      // flagged by coverity: useless check as soap_tag_cmp(...) would fail
+      // before reacing this point
         strncpy(soap->endpoint, endpoint,
                 sizeof(soap->endpoint) - 1); /* restore */
       soap->mode = m;
@@ -15664,7 +15666,7 @@ static int soap_try_connect_command(struct soap *soap, int http_command,
         soap->fpoll(soap)) {
       soap->error = SOAP_OK;
 #ifndef WITH_LEAN
-      if (!strncmp(endpoint, "soap.udp:", 9))
+      if (!endpoint || !strncmp(endpoint, "soap.udp:", 9))
         soap->omode |= SOAP_IO_UDP;
       else
 #endif
@@ -16739,9 +16741,10 @@ void SOAP_FMAC2 soap_stream_fault(struct soap *soap, std::ostream &os) {
     s = *soap_faultstring(soap);
     d = soap_check_faultdetail(soap);
     os << (soap->version ? "SOAP 1." : "Error ")
-       << (soap->version ? (int)soap->version : soap->error) << " fault: " << *c
-       << "[" << (v ? v : "no subcode") << "]" << std::endl << "\""
-       << (s ? s : "[no reason]") << "\"" << std::endl
+       << (soap->version ? (int)soap->version : soap->error)
+       << " fault: " << (*c ? *c : "")
+       << "[" << (v ? v : "no subcode") << "]" << std::endl
+       << "\"" << (s ? s : "[no reason]") << "\"" << std::endl
        << "Detail: " << (d ? d : "[no detail]") << std::endl;
   }
 }
diff --git a/Code/Mantid/Framework/ISISLiveData/CMakeLists.txt b/Code/Mantid/Framework/ISISLiveData/CMakeLists.txt
index 056e097543e5c9cde4229610557468a69a661836..583bb56c1fb3766a4960e397f8a957d8263356bc 100644
--- a/Code/Mantid/Framework/ISISLiveData/CMakeLists.txt
+++ b/Code/Mantid/Framework/ISISLiveData/CMakeLists.txt
@@ -12,6 +12,11 @@ set ( INC_FILES
 set ( TEST_FILES
 )
 
+if (COVERALLS)
+    foreach( loop_var ${SRC_FILES} ${INC_FILES})
+      set_property(GLOBAL APPEND PROPERTY COVERAGE_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/${loop_var}")
+    endforeach(loop_var)
+endif()
 
 # Use a precompiled header where they are supported
 #enable_precompiled_headers( inc/MantidISISLiveData/PrecompiledHeader.h SRC_FILES )
diff --git a/Code/Mantid/Framework/Kernel/CMakeLists.txt b/Code/Mantid/Framework/Kernel/CMakeLists.txt
index a5b35d0d880fff93e69f34fe33c6eb86b603468a..277ca71f2b05cd685c8754dd910c04f07349f8a5 100644
--- a/Code/Mantid/Framework/Kernel/CMakeLists.txt
+++ b/Code/Mantid/Framework/Kernel/CMakeLists.txt
@@ -360,6 +360,12 @@ set ( TEST_FILES
 	WriteLockTest.h
 )
 
+if (COVERALLS)
+    foreach( loop_var ${SRC_FILES} ${INC_FILES})
+      set_property(GLOBAL APPEND PROPERTY COVERAGE_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/${loop_var}")
+    endforeach(loop_var)
+endif()
+
 if ( ${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
     LIST( APPEND SRC_FILES src/NetworkProxyOSX.cpp )
     SET( NETWORK_LIBRARIES "-framework SystemConfiguration" "-framework CoreFoundation"  "-framework CoreServices")
diff --git a/Code/Mantid/Framework/Kernel/inc/MantidKernel/ChecksumHelper.h b/Code/Mantid/Framework/Kernel/inc/MantidKernel/ChecksumHelper.h
index 54a6b5fcf22e78c4d73b20cfa446924512861f84..51ae61d6180dd36dee62017ab52b8b8e72b2404d 100644
--- a/Code/Mantid/Framework/Kernel/inc/MantidKernel/ChecksumHelper.h
+++ b/Code/Mantid/Framework/Kernel/inc/MantidKernel/ChecksumHelper.h
@@ -31,15 +31,18 @@ namespace Kernel {
   Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
 namespace ChecksumHelper {
+//loads a file, optionally converting line endings
+MANTID_KERNEL_DLL std::string loadFile(const std::string &filepath, const bool unixEOL);
 /// create a md5 checksum from a string
 MANTID_KERNEL_DLL std::string md5FromString(const std::string &input);
-
 /// create a SHA-1 checksum from a string
 MANTID_KERNEL_DLL std::string sha1FromString(const std::string &input);
 /// create a SHA-1 checksum from a file
-MANTID_KERNEL_DLL std::string sha1FromFile(const std::string &filepath);
+MANTID_KERNEL_DLL std::string sha1FromFile(const std::string &filepath, const bool unixEOL);
 /// create a git checksum from a file (these match the git hash-object command)
 MANTID_KERNEL_DLL std::string gitSha1FromFile(const std::string &filepath);
+
+
 }
 
 } // namespace Kernel
diff --git a/Code/Mantid/Framework/Kernel/src/ChecksumHelper.cpp b/Code/Mantid/Framework/Kernel/src/ChecksumHelper.cpp
index c4e50074f2e9564880935870ee22915715a0f48f..c34bcdd9c3ba95808db7fd71d9f716b78ff3711b 100644
--- a/Code/Mantid/Framework/Kernel/src/ChecksumHelper.cpp
+++ b/Code/Mantid/Framework/Kernel/src/ChecksumHelper.cpp
@@ -1,8 +1,6 @@
 #include "MantidKernel/ChecksumHelper.h"
 
 #include <boost/regex.hpp>
-#include <boost/shared_array.hpp>
-
 #include <Poco/MD5Engine.h>
 #include <Poco/SHA1Engine.h>
 #include <Poco/DigestStream.h>
@@ -16,30 +14,7 @@ namespace Kernel {
 namespace ChecksumHelper {
 namespace // anonymous
     {
-/**
- * Load contents of file into a string. The line endings are preserved
- * @param filepath Full path to the file to be opened
- * @param unixEOL If true convert all lineendings to Unix-style \n
- */
-std::string loadFile(const std::string &filepath, const bool unixEOL = false) {
-  std::ifstream filein(filepath.c_str(), std::ios::in | std::ios::binary);
-  if (!filein)
-    return "";
-
-  std::string contents;
-  filein.seekg(0, std::ios::end);
-  contents.resize(filein.tellg());
-  filein.seekg(0, std::ios::beg);
-  filein.read(&contents[0], contents.size());
-  filein.close();
 
-  if (unixEOL) {
-    static boost::regex eol(
-        "\\R"); // \R is Perl syntax for matching any EOL sequence
-    contents = boost::regex_replace(contents, eol, "\n"); // converts all to LF
-  }
-  return contents;
-}
 
 /**
  * Create sha1 out of data and an optional header
@@ -95,12 +70,13 @@ std::string sha1FromString(const std::string &input) {
 
 /** Creates a SHA-1 checksum from a file
 * @param filepath The path to the file
+* @param unixEOL If true convert all lineendings to Unix-style \n
 * @returns a checksum string
 **/
-std::string sha1FromFile(const std::string &filepath) {
+std::string sha1FromFile(const std::string &filepath, const bool unixEOL = false) {
   if (filepath.empty())
     return "";
-  return ChecksumHelper::createSHA1(loadFile(filepath));
+  return ChecksumHelper::createSHA1(loadFile(filepath,unixEOL));
 }
 
 /** Creates a git checksum from a file (these match the git hash-object
@@ -117,12 +93,40 @@ std::string gitSha1FromFile(const std::string &filepath) {
   if (filepath.empty())
     return "";
   const bool unixEOL(true);
-  std::string contents = loadFile(filepath, unixEOL);
+  std::string contents = ChecksumHelper::loadFile(filepath, unixEOL);
   std::stringstream header;
   header << "blob " << contents.size() << '\0';
   return ChecksumHelper::createSHA1(contents, header.str());
 }
 
+/**
+ * Load contents of file into a string. The line endings are preserved
+ * @param filepath Full path to the file to be opened
+ * @param unixEOL If true convert all lineendings to Unix-style \n
+ */
+std::string loadFile(const std::string &filepath, const bool unixEOL = false) {
+
+  std::ifstream filein(filepath.c_str(), std::ios::in | std::ios::binary);
+  if (!filein)
+    return "";
+
+  std::string contents;
+  filein.seekg(0, std::ios::end);
+  contents.resize(filein.tellg());
+  filein.seekg(0, std::ios::beg);
+  filein.read(&contents[0], contents.size());
+  filein.close();
+
+  if (unixEOL) {
+    static boost::regex eol(
+        "\\R"); // \R is Perl syntax for matching any EOL sequence
+    contents = boost::regex_replace(contents, eol, "\n"); // converts all to LF
+  }
+  return contents;
+}
+
+
+
 } // namespace ChecksumHelper
 } // namespace Kernel
 } // namespace Mantid
diff --git a/Code/Mantid/Framework/Kernel/src/NexusDescriptor.cpp b/Code/Mantid/Framework/Kernel/src/NexusDescriptor.cpp
index 39755715bc32b9ab8a774b25a8bd76494e12d44e..f05232f4cb511d9c0480bd7ef033a8fc040fc90f 100644
--- a/Code/Mantid/Framework/Kernel/src/NexusDescriptor.cpp
+++ b/Code/Mantid/Framework/Kernel/src/NexusDescriptor.cpp
@@ -50,8 +50,12 @@ bool isHDFHandle(FILE *fileHandle, NexusDescriptor::Version version) {
   // HDF4 check requires 4 bytes,  HDF5 check requires 8 bytes
   // Use same buffer and waste a few bytes if only checking HDF4
   unsigned char buffer[8] = {'0', '0', '0', '0', '0', '0', '0', '0'};
-  std::fread(static_cast<void *>(&buffer), sizeof(unsigned char),
-             NexusDescriptor::HDF5SignatureSize, fileHandle);
+  if (NexusDescriptor::HDF5SignatureSize !=
+      std::fread(static_cast<void *>(&buffer), sizeof(unsigned char),
+                 NexusDescriptor::HDF5SignatureSize, fileHandle)) {
+    throw std::runtime_error("Error while reading file");
+  }
+
   // Number of bytes read doesn't matter as if it is not enough then the memory
   // simply won't match
   // as the buffer has been "zeroed"
diff --git a/Code/Mantid/Framework/Kernel/test/ChecksumHelperTest.h b/Code/Mantid/Framework/Kernel/test/ChecksumHelperTest.h
index 865474f634f93149a8c69eaa49e812e98358305b..173f974d3077d455500878dc48f21432ae529c0d 100644
--- a/Code/Mantid/Framework/Kernel/test/ChecksumHelperTest.h
+++ b/Code/Mantid/Framework/Kernel/test/ChecksumHelperTest.h
@@ -38,7 +38,7 @@ public:
     const std::string data = "ChecksumHelperTest_testSha1FromFile Test this string out for size in a file";
     createFile(filename,data);
 
-    std::string response = ChecksumHelper::sha1FromFile(filename);
+    std::string response = ChecksumHelper::sha1FromFile(filename,false);
     TSM_ASSERT_EQUALS("The calculated SHA-1 hash is not as expected", "363cbe9c113b8bcba9e0aa94dbe45e67856ff26b", response);
     Poco::File(filename).remove();
   }
diff --git a/Code/Mantid/Framework/LiveData/CMakeLists.txt b/Code/Mantid/Framework/LiveData/CMakeLists.txt
index a0b01e63b42cb3e1f64ce278782583412c260dca..b3fdfac21fce4d904b1a38561dc59a06a63156d1 100644
--- a/Code/Mantid/Framework/LiveData/CMakeLists.txt
+++ b/Code/Mantid/Framework/LiveData/CMakeLists.txt
@@ -52,6 +52,11 @@ set ( TEST_FILES
 	StartLiveDataTest.h
 )
 
+if (COVERALLS)
+    foreach( loop_var ${SRC_FILES} ${INC_FILES})
+      set_property(GLOBAL APPEND PROPERTY COVERAGE_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/${loop_var}")
+    endforeach(loop_var)
+endif()
 
 if(UNITY_BUILD)
   include(UnityBuild)
diff --git a/Code/Mantid/Framework/MDAlgorithms/CMakeLists.txt b/Code/Mantid/Framework/MDAlgorithms/CMakeLists.txt
index 73fc2144b86b398491e308b110931badc8154aa3..713d54044439989426f8c4ebee92aecccf08fd62 100644
--- a/Code/Mantid/Framework/MDAlgorithms/CMakeLists.txt
+++ b/Code/Mantid/Framework/MDAlgorithms/CMakeLists.txt
@@ -346,6 +346,12 @@ set ( GMOCK_TEST_FILES
 	BinMDTest.h
 )
 
+if (COVERALLS)
+    foreach( loop_var ${SRC_FILES} ${INC_FILES})
+      set_property(GLOBAL APPEND PROPERTY COVERAGE_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/${loop_var}")
+    endforeach(loop_var)
+endif()
+
 if(UNITY_BUILD)
   include(UnityBuild)
   enable_unity_build(MDAlgorithms SRC_FILES SRC_UNITY_IGNORE_FILES 10)
diff --git a/Code/Mantid/Framework/MDAlgorithms/src/MergeMDFiles.cpp b/Code/Mantid/Framework/MDAlgorithms/src/MergeMDFiles.cpp
index 03f3afd4a056a53ad85884b9eb0a7ff0e6ee62d1..64e9e5341dfabedc15876c5bed59aaf561a1cd6e 100644
--- a/Code/Mantid/Framework/MDAlgorithms/src/MergeMDFiles.cpp
+++ b/Code/Mantid/Framework/MDAlgorithms/src/MergeMDFiles.cpp
@@ -350,6 +350,9 @@ void MergeMDFiles::exec() {
   // pDiskBuffer = NULL;
   MultipleFileProperty *multiFileProp =
       dynamic_cast<MultipleFileProperty *>(getPointerToProperty("Filenames"));
+  if (!multiFileProp) {
+    throw std::logic_error("Filenames property must have MultipleFileProperty type.");
+  }
   m_Filenames =
       MultipleFileProperty::flattenFileNames(multiFileProp->operator()());
   if (m_Filenames.size() == 0)
diff --git a/Code/Mantid/Framework/MDAlgorithms/src/WeightedMeanMD.cpp b/Code/Mantid/Framework/MDAlgorithms/src/WeightedMeanMD.cpp
index d1d780dd4b1cc997e5aa2ec3d986e5e5ebc1a57f..a4fcc17bdbe2250d8d8f2624dbd412e3e2205a68 100644
--- a/Code/Mantid/Framework/MDAlgorithms/src/WeightedMeanMD.cpp
+++ b/Code/Mantid/Framework/MDAlgorithms/src/WeightedMeanMD.cpp
@@ -45,6 +45,10 @@ void WeightedMeanMD::execHistoHisto(
   MDHistoWorkspaceIterator *rhs_it =
       dynamic_cast<MDHistoWorkspaceIterator *>(operand->createIterator());
 
+  if (!lhs_it || !rhs_it) {
+    throw std::logic_error("Histo iterators have wrong type.");
+  }
+
   do {
     double lhs_s = lhs_it->getSignal();
     double lhs_err = lhs_it->getError();
diff --git a/Code/Mantid/Framework/MPIAlgorithms/CMakeLists.txt b/Code/Mantid/Framework/MPIAlgorithms/CMakeLists.txt
index 7d245cdf0caa66eec18f084da1204ca246ba07af..664666802fe69b2eba0ea9a1570279650609bab7 100644
--- a/Code/Mantid/Framework/MPIAlgorithms/CMakeLists.txt
+++ b/Code/Mantid/Framework/MPIAlgorithms/CMakeLists.txt
@@ -11,6 +11,12 @@ set ( TEST_FILES BroadcastWorkspaceTest.h
                  GatherWorkspacesTest.h
 )
 
+if (COVERALLS)
+    foreach( loop_var ${SRC_FILES} ${INC_FILES})
+      set_property(GLOBAL APPEND PROPERTY COVERAGE_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/${loop_var}")
+    endforeach(loop_var)
+endif()
+
 # Add the target for this directory
 add_library ( MPIAlgorithms ${SRC_FILES} ${INC_FILES} )
 # Set the name of the generated library
diff --git a/Code/Mantid/Framework/MatlabAPI/CMakeLists.txt b/Code/Mantid/Framework/MatlabAPI/CMakeLists.txt
index 2923171c59a1538de1eb77b9d212182b525e9af0..14cb3025ea4d23b4e8648b6de2808a7fb284ce81 100644
--- a/Code/Mantid/Framework/MatlabAPI/CMakeLists.txt
+++ b/Code/Mantid/Framework/MatlabAPI/CMakeLists.txt
@@ -4,6 +4,12 @@ set ( SRC_FILES
 
 set ( INC_FILES )
 
+if (COVERALLS)
+    foreach( loop_var ${SRC_FILES} ${INC_FILES})
+      set_property(GLOBAL APPEND PROPERTY COVERAGE_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/${loop_var}")
+    endforeach(loop_var)
+endif()
+
 add_definitions ( -DIN_MANTID_MATLAB_API -DMATLAB_MEX_FILE=1 )
 
 include_directories ( inc )
diff --git a/Code/Mantid/Framework/Nexus/CMakeLists.txt b/Code/Mantid/Framework/Nexus/CMakeLists.txt
index be0de2a44fb6b8d5fd1a9030f02d677b58c3d400..2208a123dae48c3426145edd0a98ec3f8a5444aa 100644
--- a/Code/Mantid/Framework/Nexus/CMakeLists.txt
+++ b/Code/Mantid/Framework/Nexus/CMakeLists.txt
@@ -14,6 +14,12 @@ set ( TEST_FILES
 	test/NexusAPITest.h
 )
 
+if (COVERALLS)
+    foreach( loop_var ${SRC_FILES} ${INC_FILES})
+      set_property(GLOBAL APPEND PROPERTY COVERAGE_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/${loop_var}")
+    endforeach(loop_var)
+endif()
+
 add_definitions ( -DIN_NEXUS_CPP_LIBRARY )
 
 # Add the target for this directory
diff --git a/Code/Mantid/Framework/Nexus/src/MuonNexusReader.cpp b/Code/Mantid/Framework/Nexus/src/MuonNexusReader.cpp
index bdcda4d395f4254cf185c09b3fc8d919f8f72797..594dc6d35b4d754ce18b5e55e0353563a411072f 100644
--- a/Code/Mantid/Framework/Nexus/src/MuonNexusReader.cpp
+++ b/Code/Mantid/Framework/Nexus/src/MuonNexusReader.cpp
@@ -25,8 +25,10 @@ using namespace Mantid;
 
 /// Default constructor
 MuonNexusReader::MuonNexusReader()
-    : nexus_instrument_name(), corrected_times(NULL), counts(NULL),
-      detectorGroupings(NULL) {}
+    : nexus_instrument_name(), nexus_samplename(), nexusLogCount(0),
+      startTime_time_t(), t_nsp1(0), t_ntc1(0), t_nper(0),
+      corrected_times(NULL), counts(NULL), detectorGroupings(NULL),
+      numDetectors(0) {}
 
 /// Destructor deletes temp storage
 MuonNexusReader::~MuonNexusReader() {
diff --git a/Code/Mantid/Framework/Nexus/src/NexusFileIO.cpp b/Code/Mantid/Framework/Nexus/src/NexusFileIO.cpp
index 0984355bcd319cfefa9c8fa190b44751c277b85b..9427b662c74f4a5a06f34f748334a713dd7845c8 100644
--- a/Code/Mantid/Framework/Nexus/src/NexusFileIO.cpp
+++ b/Code/Mantid/Framework/Nexus/src/NexusFileIO.cpp
@@ -629,7 +629,7 @@ void NexusFileIO::writeNexusVectorColumn(
 int NexusFileIO::writeNexusTableWorkspace(
     const API::ITableWorkspace_const_sptr &itableworkspace,
     const char *group_name) const {
-  NXstatus status = 0;
+  NXstatus status = NX_ERROR;
 
   boost::shared_ptr<const TableWorkspace> tableworkspace =
       boost::dynamic_pointer_cast<const TableWorkspace>(itableworkspace);
@@ -637,7 +637,7 @@ int NexusFileIO::writeNexusTableWorkspace(
       boost::dynamic_pointer_cast<const PeaksWorkspace>(itableworkspace);
 
   if (!tableworkspace && !peakworkspace)
-    return ((status == NX_ERROR) ? 3 : 0);
+    return 3;
 
   // write data entry
   status = NXmakegroup(fileID, group_name, "NXdata");
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 fcc183d733263ba15e6d8caa45e6da57f2058f76..a45564593a6ad1c076fa89fab96e26f91c1dd08a 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/Group.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/Group.cpp
@@ -5,8 +5,11 @@
 #include <boost/python/enum.hpp>
 #include <boost/python/scope.hpp>
 #include <boost/python/list.hpp>
+#include <boost/python/stl_iterator.hpp>
+#include <boost/python/make_constructor.hpp>
+#include <boost/python/register_ptr_to_python.hpp>
 
-using Mantid::Geometry::Group;
+using namespace Mantid::Geometry;
 using Mantid::Geometry::SymmetryOperation;
 
 using namespace boost::python;
@@ -23,15 +26,22 @@ namespace {
       return pythonSymOps;
     }
 
-    boost::python::list getSymmetryOperations(Group &self) {
-      const std::vector<SymmetryOperation> &symOps = self.getSymmetryOperations();
+    Group_sptr constructGroupFromString(const std::string &initializerString) {
+        return boost::const_pointer_cast<Group>(GroupFactory::create<Group>(initializerString));
+    }
 
-      boost::python::list pythonSymOps;
-      for (auto it = symOps.begin(); it != symOps.end(); ++it) {
-        pythonSymOps.append(*it);
-      }
+    Group_sptr constructGroupFromVector(const std::vector<SymmetryOperation> &symOps) {
+        return boost::const_pointer_cast<Group>(GroupFactory::create<Group>(symOps));
+    }
 
-      return pythonSymOps;
+    Group_sptr constructGroupFromPythonList(const boost::python::list &symOpList) {
+        std::vector<SymmetryOperation> operations;
+
+        for(int i = 0; i < len(symOpList); ++i) {
+            operations.push_back(boost::python::extract<SymmetryOperation>(symOpList[i]));
+        }
+
+        return boost::const_pointer_cast<Group>(GroupFactory::create<Group>(operations));
     }
 }
 
@@ -39,13 +49,28 @@ namespace {
 void export_Group()
 // clang-format on
 {
+
+  register_ptr_to_python<boost::shared_ptr<Group> >();
+
   enum_<Group::CoordinateSystem>("CoordinateSystem")
       .value("Orthogonal", Group::Orthogonal)
       .value("Hexagonal", Group::Hexagonal);
 
+  enum_<Group::GroupAxiom>("GroupAxiom")
+      .value("Closure", Group::Closure)
+      .value("Identity", Group::Identity)
+      .value("Inversion", Group::Inversion)
+      .value("Associativity", Group::Associativity);
+
   class_<Group, boost::noncopyable>("Group", no_init)
+      .def("__init__", make_constructor(&constructGroupFromString), "Construct a group from the provided initializer string.")
+      .def("__init__", make_constructor(&constructGroupFromVector), "Construct a group from the provided symmetry operation list.")
+      .def("__init__", make_constructor(&constructGroupFromPythonList), "Construct a group from a python generated symmetry operation list.")
       .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.");
+      .def("getSymmetryOperations", &Group::getSymmetryOperations, "Returns the symmetry operations contained in the group.")
+      .def("getSymmetryOperationStrings", &getSymmetryOperationStrings, "Returns the x,y,z-strings for the contained symmetry operations.")
+      .def("containsOperation", &Group::containsOperation, "Checks whether a SymmetryOperation is included in Group.")
+      .def("isGroup", &Group::isGroup, "Checks whether the contained symmetry operations fulfill the group axioms.")
+      .def("fulfillsAxiom", &Group::fulfillsAxiom, "Checks if the contained symmetry operations fulfill the specified group axiom.");
 }
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 05a248a351113df6623a402aa315f6c240e5e10e..9fe505484c966257154584dc2ac6afa3a8a1cfc5 100644
--- a/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/SymmetryOperation.cpp
+++ b/Code/Mantid/Framework/PythonInterface/mantid/geometry/src/Exports/SymmetryOperation.cpp
@@ -2,6 +2,7 @@
 #include "MantidGeometry/Crystal/SymmetryOperation.h"
 #include "MantidPythonInterface/kernel/Converters/PyObjectToV3D.h"
 #include "MantidPythonInterface/kernel/Converters/PyObjectToMatrix.h"
+#include "MantidPythonInterface/kernel/StlExportDefinitions.h"
 
 #include <boost/python/class.hpp>
 #include <boost/python/enum.hpp>
@@ -10,6 +11,7 @@
 #include <boost/python/register_ptr_to_python.hpp>
 
 using Mantid::Geometry::SymmetryOperation;
+using Mantid::PythonInterface::std_vector_exporter;
 
 using namespace boost::python;
 
@@ -40,5 +42,7 @@ void export_SymmetryOperation()
           .def("transformCoordinates", &applyToCoordinates, "Returns transformed coordinates. For transforming HKLs, use transformHKL.")
           .def("transformHKL", &applyToVector, "Returns transformed HKLs. For transformation of coordinates use transformCoordinates.")
           .def("apply", &applyToVector, "An alias for transformHKL.");
+
+  std_vector_exporter<Mantid::Geometry::SymmetryOperation>::wrap("std_vector_symmetryoperation");
 }
 
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFitPeaks.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFitPeaks.py
index 9b9ef08e7b1e0a619d32ed830a3937d346dbe972..0fed4c447ec9f37099b6540b003467fc5adc4f3f 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFitPeaks.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFitPeaks.py
@@ -63,6 +63,8 @@ class EnginXFitPeaks(PythonAlgorithm):
             centre = row['centre']
             width = row['width']
             height = row['height']
+            if width <= 0.:
+                continue
 
             # Sigma value of the peak, assuming Gaussian shape
             sigma = width / (2 * math.sqrt(2 * math.log(2)))
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFocus.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFocus.py
index a5aa41c6400cd48d3295b9039835d146e7585597..b6adb8b02bc621d425438767d4e5efff62c1363f 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFocus.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFocus.py
@@ -16,14 +16,14 @@ class EnginXFocus(PythonAlgorithm):
         self.declareProperty(FileProperty("Filename", "", FileAction.Load),\
     		"Run to focus")
 
-        self.declareProperty(WorkspaceProperty("OutputWorkspace", "", Direction.Output),\
-    		"A workspace with focussed data")
+        self.declareProperty("Bank", 1, "Which bank to focus")
 
         self.declareProperty(ITableWorkspaceProperty("DetectorPositions", "", Direction.Input,\
                 PropertyMode.Optional),\
     		"Calibrated detector positions. If not specified, default ones are used.")
 
-        self.declareProperty("Bank", 1, "Which bank to focus")
+        self.declareProperty(WorkspaceProperty("OutputWorkspace", "", Direction.Output),\
+                             "A workspace with focussed data")
 
 
 
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py
index d98f568175e3981e77b9b1f52b611ee35f9420a1..ed0e74c2e29ce09f5792944214474879cc64bbf0 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py
@@ -57,6 +57,10 @@ class ElasticWindowMultiple(DataProcessorAlgorithm):
         self.declareProperty(name='SampleEnvironmentLogName', defaultValue='sample',
                              doc='Name of the sample environment log entry')
 
+        sampEnvLogVal_type = ['last value', 'average']
+        self.declareProperty('SampleEnvironmentLogValue', 'last value', StringListValidator(sampEnvLogVal_type),
+                             doc='Value selection of the sample environment log entry')
+
         self.declareProperty(WorkspaceProperty('OutputInQ', '', Direction.Output),
                              doc='Output workspace in Q')
 
@@ -260,6 +264,7 @@ class ElasticWindowMultiple(DataProcessorAlgorithm):
 
         self._plot = self.getProperty('Plot').value
         self._sample_log_name = self.getPropertyValue('SampleEnvironmentLogName')
+        self._sample_log_value = self.getPropertyValue('SampleEnvironmentLogValue')
 
         self._input_workspaces = self.getProperty('InputWorkspaces').value
         self._q_workspace = self.getPropertyValue('OutputInQ')
@@ -318,7 +323,10 @@ class ElasticWindowMultiple(DataProcessorAlgorithm):
         if self._sample_log_name in run:
             # Look for temperature in logs in workspace
             tmp = run[self._sample_log_name].value
-            temp = tmp[len(tmp) - 1]
+            value_action = {'last value': lambda x: x[len(x)-1],
+                             'average': lambda x: x.mean()
+                             }
+            temp = value_action[self._sample_log_value](tmp)
             logger.debug('Temperature %d K found for run: %s' % (temp, run_name))
             return temp
 
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectCalibration.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectCalibration.py
index 0e4251bda48a0cbb86f90b2aa33999209416b793..d274cf2d9534358bac497f1108a09441fbeb4ec5 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectCalibration.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectCalibration.py
@@ -1,4 +1,4 @@
-#pylint: disable=no-init
+#pylint: disable=no-init,too-many-instance-attributes
 from mantid.kernel import *
 from mantid.api import *
 from mantid.simpleapi import *
@@ -15,6 +15,7 @@ class IndirectCalibration(DataProcessorAlgorithm):
     _spec_range = None
     _intensity_scale = None
     _plot = None
+    _run_numbers = None
 
 
     def category(self):
@@ -29,16 +30,19 @@ class IndirectCalibration(DataProcessorAlgorithm):
         self.declareProperty(StringArrayProperty(name='InputFiles'),
                              doc='Comma separated list of input files')
 
-        self.declareProperty(IntArrayProperty(name='DetectorRange', values=[0, 1],\
-                             validator=IntArrayMandatoryValidator()),
+        self.declareProperty(IntArrayProperty(name='DetectorRange',
+                                              values=[0, 1],
+                                              validator=IntArrayMandatoryValidator()),
                              doc='Range of detectors.')
 
-        self.declareProperty(FloatArrayProperty(name='PeakRange', values=[0.0, 100.0],\
-                             validator=FloatArrayMandatoryValidator()),
+        self.declareProperty(FloatArrayProperty(name='PeakRange',
+                                                values=[0.0, 100.0],
+                                                validator=FloatArrayMandatoryValidator()),
                              doc='Time of flight range over the peak.')
 
-        self.declareProperty(FloatArrayProperty(name='BackgroundRange', values=[0.0, 1000.0],\
-                             validator=FloatArrayMandatoryValidator()),
+        self.declareProperty(FloatArrayProperty(name='BackgroundRange',
+                                                values=[0.0, 1000.0],
+                                                validator=FloatArrayMandatoryValidator()),
                              doc='Time of flight range over the background.')
 
         self.declareProperty(name='ScaleFactor', defaultValue=1.0,
@@ -47,11 +51,11 @@ class IndirectCalibration(DataProcessorAlgorithm):
         self.declareProperty(name='Plot', defaultValue=False,
                              doc='Plot the calibration data as a spectra plot.')
 
-        self.declareProperty(WorkspaceProperty('OutputWorkspace', '', direction=Direction.Output),
+        self.declareProperty(WorkspaceProperty('OutputWorkspace', '',
+                                               direction=Direction.Output),
                              doc='Output workspace for calibration data.')
 
 
-
     def validateInputs(self):
         """
         Validates input ranges.
@@ -84,57 +88,81 @@ class IndirectCalibration(DataProcessorAlgorithm):
 
 
     def PyExec(self):
+        from mantid import logger
+        from IndirectCommon import getInstrRun
+
         self._setup()
 
         runs = []
+        self._run_numbers = list()
         for in_file in self._input_files:
             (_, filename) = os.path.split(in_file)
             (root, _) = os.path.splitext(filename)
             try:
-                Load(Filename=in_file, OutputWorkspace=root,\
-                    SpectrumMin=int(self._spec_range[0]), SpectrumMax=int(self._spec_range[1]),\
-                    LoadLogFiles=False)
+                Load(Filename=in_file,
+                     OutputWorkspace=root,
+                     SpectrumMin=int(self._spec_range[0]),
+                     SpectrumMax=int(self._spec_range[1]),
+                     LoadLogFiles=False)
+
                 runs.append(root)
             except (RuntimeError,ValueError) as exc:
                 logger.error('Could not load raw file "%s": %s' % (in_file, str(exc)))
 
         calib_ws_name = 'calibration'
         if len(runs) > 1:
-            MergeRuns(InputWorkspaces=",".join(runs), OutputWorkspace=calib_ws_name)
+            MergeRuns(InputWorkspaces=",".join(runs),
+                      OutputWorkspace=calib_ws_name)
             factor = 1.0 / len(runs)
-            Scale(InputWorkspace=calib_ws_name, OutputWorkspace=calib_ws_name, Factor=factor)
+            Scale(InputWorkspace=calib_ws_name,
+                  OutputWorkspace=calib_ws_name,
+                  Factor=factor)
         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')
+        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])
+        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')
+        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))
 
-        Scale(InputWorkspace=calib_ws_name, OutputWorkspace=calib_ws_name,
-              Factor=self._intensity_scale, Operation='Multiply')
+        Scale(InputWorkspace=calib_ws_name,
+              OutputWorkspace=calib_ws_name,
+              Factor=self._intensity_scale,
+              Operation='Multiply')
 
-        RenameWorkspace(InputWorkspace=calib_ws_name, OutputWorkspace=self._out_ws)
+        RenameWorkspace(InputWorkspace=calib_ws_name,
+                        OutputWorkspace=self._out_ws)
 
         # Remove old workspaces
         if len(runs) > 1:
             for run in runs:
                 DeleteWorkspace(Workspace=run)
 
+        self._add_logs()
         self.setProperty('OutputWorkspace', self._out_ws)
-        self._post_process()
+
+        if self._plot:
+            from mantidplot import plotBin
+            plotBin(mtd[self._out_ws], 0)
 
 
     def _setup(self):
@@ -156,22 +184,26 @@ class IndirectCalibration(DataProcessorAlgorithm):
         self._plot = self.getProperty('Plot').value
 
 
-    def _post_process(self):
+    def _add_logs(self):
         """
-        Handles adding logs and plotting.
+        Handles adding sample logs.
         """
 
         # Add sample logs to output workspace
+        sample_logs = [
+                ('calib_peak_min', self._peak_range[0]),
+                ('calib_peak_max', self._peak_range[1]),
+                ('calib_back_min', self._back_range[0]),
+                ('calib_back_max', self._back_range[1]),
+                ('calib_run_numbers', ','.join(self._run_numbers))
+            ]
+
         if self._intensity_scale is not None:
-            AddSampleLog(Workspace=self._out_ws, LogName='Scale Factor', LogType='Number', LogText=str(self._intensity_scale))
-        AddSampleLog(Workspace=self._out_ws, LogName='Peak Min', LogType='Number', LogText=str(self._peak_range[0]))
-        AddSampleLog(Workspace=self._out_ws, LogName='Peak Max', LogType='Number', LogText=str(self._peak_range[1]))
-        AddSampleLog(Workspace=self._out_ws, LogName='Back Min', LogType='Number', LogText=str(self._back_range[0]))
-        AddSampleLog(Workspace=self._out_ws, LogName='Back Max', LogType='Number', LogText=str(self._back_range[1]))
+            sample_logs.append(('calib_scale_factor', self._intensity_scale))
 
-        if self._plot:
-            from mantidplot import plotBin
-            plotBin(mtd[self._out_ws], 0)
+        AddSampleLogMultiple(Workspace=self._out_ws,
+                             LogNames=[log[0] for log in sample_logs],
+                             LogValues=[log[1] for log in sample_logs])
 
 
 # Register algorithm with Mantid
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLReduction.py
index cf45d1e32bf5952253cdbcde5d80b19f029b493f..46a2ab2ef65625e133efa4a15d87f8767f11a637 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLReduction.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLReduction.py
@@ -334,11 +334,12 @@ class IndirectILLReduction(DataProcessorAlgorithm):
         ConvertAxisByFormula(InputWorkspace=grouped_ws,
                              OutputWorkspace=red_ws,
                              Axis='X',
-                             Formula=formula,
-                             AxisTitle='Energy transfer',
-                             AxisUnits='meV')
+                             Formula=formula)
 
-        xnew = mtd[red_ws].readX(0)  # energy array
+        red_ws_p = mtd[red_ws]
+        red_ws_p.getAxis(0).setUnit('DeltaE')
+
+        xnew = red_ws_p.readX(0)  # energy array
         logger.information('Energy range : %f to %f' % (xnew[0], xnew[-1]))
 
         DeleteWorkspace(grouped_ws)
diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py
index ccb99c495c428848ed0da6b786c7f64e1c9b25b7..d481719f5c1521b607c1d2736b7a009d341b257a 100644
--- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py
+++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py
@@ -19,6 +19,7 @@ class IndirectResolution(DataProcessorAlgorithm):
     _plot = None
     _save = None
 
+
     def category(self):
         return 'Workflow\\Inelastic;PythonAlgorithms;Inelastic'
 
@@ -61,8 +62,11 @@ class IndirectResolution(DataProcessorAlgorithm):
                                                direction=Direction.Output),
                              doc='Output resolution workspace.')
 
+
     def PyExec(self):
+
         #from IndirectCommon import getWSprefix
+
         self._setup()
 
         ISISIndirectEnergyTransfer(Instrument=self._instrument,
@@ -77,13 +81,20 @@ class IndirectResolution(DataProcessorAlgorithm):
         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)
+            Scale(InputWorkspace=icon_ws,
+                  OutputWorkspace=icon_ws,
+                  Factor=self._scale_factor)
 
-        CalculateFlatBackground(InputWorkspace=icon_ws, OutputWorkspace=self._out_ws,
-                                StartX=self._background[0], EndX=self._background[1],
-                                Mode='Mean', OutputMode='Subtract Background')
+        CalculateFlatBackground(InputWorkspace=icon_ws,
+                                OutputWorkspace=self._out_ws,
+                                StartX=self._background[0],
+                                EndX=self._background[1],
+                                Mode='Mean',
+                                OutputMode='Subtract Background')
 
-        Rebin(InputWorkspace=self._out_ws, OutputWorkspace=self._out_ws, Params=self._rebin_string)
+        Rebin(InputWorkspace=self._out_ws,
+              OutputWorkspace=self._out_ws,
+              Params=self._rebin_string)
 
         self._post_process()
         self.setProperty('OutputWorkspace', self._out_ws)
@@ -115,31 +126,27 @@ class IndirectResolution(DataProcessorAlgorithm):
         Handles adding logs, saving and plotting.
         """
 
-        use_scale_factor = self._scale_factor == 1.0
-        AddSampleLog(Workspace=self._out_ws, LogName='scale',
-                     LogType='String', LogText=str(use_scale_factor))
-        if use_scale_factor:
-            AddSampleLog(Workspace=self._out_ws, LogName='scale_factor',
-                         LogType='Number', LogText=str(self._scale_factor))
+        sample_logs = [
+                ('res_back_start', self._background[0]),
+                ('res_back_end', self._background[1])
+            ]
 
-        AddSampleLog(Workspace=self._out_ws, LogName='back_start',
-                     LogType='Number', LogText=str(self._background[0]))
-        AddSampleLog(Workspace=self._out_ws, LogName='back_end',
-                     LogType='Number', LogText=str(self._background[1]))
+        if self._scale_factor != 1.0:
+            sample_logs.append(('res_scale_factor', self._scale_factor))
 
         rebin_params = self._rebin_string.split(',')
         if len(rebin_params) == 3:
-            AddSampleLog(Workspace=self._out_ws, LogName='rebin_low',
-                         LogType='Number', LogText=rebin_params[0])
-            AddSampleLog(Workspace=self._out_ws, LogName='rebin_width',
-                         LogType='Number', LogText=rebin_params[1])
-            AddSampleLog(Workspace=self._out_ws, LogName='rebin_high',
-                         LogType='Number', LogText=rebin_params[2])
+            sample_logs.append(('rebin_low', rebin_params[0]))
+            sample_logs.append(('rebin_width', rebin_params[1]))
+            sample_logs.append(('rebin_high', rebin_params[2]))
+
+        AddSampleLogMultiple(Workspace=self._out_ws,
+                             LogNames=[log[0] for log in sample_logs],
+                             LogValues=[log[1] for log in sample_logs])
 
         self.setProperty('OutputWorkspace', self._out_ws)
 
         if self._save:
-            logger.information("Resolution file saved to default save directory.")
             SaveNexusProcessed(InputWorkspace=self._out_ws, Filename=self._out_ws + '.nxs')
 
         if self._plot:
diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/CMakeLists.txt b/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/CMakeLists.txt
index 51852e94c51fee7c5853c2230e3b6de78285ceae..0a03316888ee6f52c89b0d38835bcd1b59b56f6a 100644
--- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/CMakeLists.txt
+++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/CMakeLists.txt
@@ -16,6 +16,7 @@ set ( TEST_PY_FILES
   SpaceGroupTest.py
   SymmetryElementTest.py
   SymmetryOperationTest.py
+  GroupTest.py
 )
 
 check_tests_valid ( ${CMAKE_CURRENT_SOURCE_DIR} ${TEST_PY_FILES} )
diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/GroupTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/GroupTest.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b9cf681a4e3091287922016bd8dcc4e698147d0
--- /dev/null
+++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/GroupTest.py
@@ -0,0 +1,33 @@
+#pylint: disable=no-init,invalid-name,too-many-public-methods
+import unittest
+from mantid.geometry import Group, SpaceGroupFactory
+
+class GroupTest(unittest.TestCase):
+    def test_creationFromString(self):
+        group = Group('x,y,z')
+        self.assertEqual(group.getOrder(), 1)
+
+        self.assertRaises(RuntimeError, Group, 'invalid')
+
+    def test_creationFromVector(self):
+        spaceGroup = SpaceGroupFactory.createSpaceGroup("P 63/m m c")
+        symOps = spaceGroup.getSymmetryOperations()
+
+        group = Group(symOps)
+        self.assertEqual(group.getOrder(), spaceGroup.getOrder())
+
+    def test_creationFromPythonList(self):
+        spaceGroup = SpaceGroupFactory.createSpaceGroup("P 63/m m c")
+
+        # Construct python list of only certain symmetry operations
+        symOps = [x for x in spaceGroup.getSymmetryOperations() if x.getOrder() == 6]
+
+        group = Group(symOps)
+        self.assertEqual(group.getOrder(), len(symOps))
+
+        # But the constructed group is not actually a group
+        self.assertFalse(group.isGroup())
+
+
+if __name__ == '__main__':
+    unittest.main()
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 b9234dff1be89faa4a30a7bfe770bad14aed90ee..1aecf67682f46260815559ba7e6786a308e494d8 100644
--- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/CMakeLists.txt
+++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/CMakeLists.txt
@@ -17,6 +17,10 @@ set ( TEST_PY_FILES
   DakotaChiSquaredTest.py
   DensityOfStatesTest.py
   DSFinterpTest.py
+  EnginXCalibrateFullTest.py
+  EnginXCalibrateTest.py
+  EnginXFitPeaksTest.py
+  EnginXFocusTest.py
   FilterLogByTimeTest.py
   FindReflectometryLinesTest.py
   FlatPlatePaalmanPingsCorrectionTest.py
diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/EnginXCalibrateFullTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/EnginXCalibrateFullTest.py
new file mode 100644
index 0000000000000000000000000000000000000000..aba6a0574f88cc41d0375d646f9c445c616121e7
--- /dev/null
+++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/EnginXCalibrateFullTest.py
@@ -0,0 +1,64 @@
+import unittest
+from mantid.simpleapi import *
+from mantid.api import *
+
+class EnginXCalibrateFullTest(unittest.TestCase):
+
+    def test_issues_with_properties(self):
+        """
+        Handle in/out property errors appropriately.
+        """
+
+        # No Filename property (required)
+        self.assertRaises(RuntimeError,
+                          EnginXCalibrateFull,
+                          File='foo', Bank=1)
+
+        # Wrong filename
+        self.assertRaises(RuntimeError,
+                          EnginXCalibrateFull,
+                          File='bar_file_is_not_there.not', Bank=2)
+
+        # mispelled ExpectedPeaks
+        self.assertRaises(RuntimeError,
+                          EnginXCalibrateFull,
+                          Filename='ENGINX00228061.nxs', Bank=2, Peaks='2')
+
+        # all fine, except missing DetectorPositions (output)
+        self.assertRaises(RuntimeError,
+                          EnginXCalibrateFull,
+                          Filename='ENGINX00228061.nxs', Bank=2)
+
+    def test_wrong_fit_fails_gracefully(self):
+        """
+        Checks a bad run fails reasonably.
+        """
+
+        # This should produce fitting 'given peak center ... is outside of data range'
+        # warnings and finally raise after a 'some peaks not found' error
+        self.assertRaises(RuntimeError,
+                          EnginXCalibrateFull,
+                          Filename="ENGINX00228061.nxs", ExpectedPeaks=[0.01], Bank=1,
+                          DetectorPositions='out_det_positions_table')
+
+
+    def test_run_ok_but_bad_data(self):
+        """
+        Tests a run that doesn't go well becaus of inappropriate data is used here.
+        """
+
+        # This is not a realistic CalibrateFull run, but it just runs fine
+        # for testing purposes. A test with real (much larger) data that produces
+        # a correct fit is included in system tests
+        tbl_name = 'det_peaks_tbl'
+        det_peaks_tbl = CreateEmptyTableWorkspace()
+        self.assertRaises(RuntimeError,
+                          EnginXCalibrateFull,
+                          Filename="ENGINX00228061.nxs", Bank=2,
+                          ExpectedPeaks='0.915, 1.257, 1.688',
+                          DetectorPositions=tbl_name)
+
+
+
+if __name__ == '__main__':
+    unittest.main()
diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/EnginXCalibrateTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/EnginXCalibrateTest.py
new file mode 100644
index 0000000000000000000000000000000000000000..37a1672a174185206d8de1f36d9b55b29ceb9ada
--- /dev/null
+++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/EnginXCalibrateTest.py
@@ -0,0 +1,70 @@
+import unittest
+from mantid.simpleapi import *
+from mantid.api import *
+
+class EnginXCalibrateTest(unittest.TestCase):
+
+    def test_issues_with_properties(self):
+        """
+        Tests proper error handling when passing wrong properties or not passing required
+        ones.
+        """
+
+        # No Filename property (required)
+        self.assertRaises(RuntimeError,
+                          EnginXCalibrate,
+                          File='foo', Bank=1)
+
+        # Wrong filename
+        self.assertRaises(RuntimeError,
+                          EnginXCalibrate,
+                          File='foo_is_not_there', Bank=2)
+
+        # mispelled ExpectedPeaks
+        tbl = CreateEmptyTableWorkspace(OutputWorkspace='test_table')
+        self.assertRaises(RuntimeError,
+                          EnginXCalibrate,
+                          Filename='ENGINX00228061.nxs', DetectorPositions=tbl, Bank=2, Peaks='2')
+
+        # mispelled DetectorPositions
+        self.assertRaises(RuntimeError,
+                          EnginXCalibrate,
+                          Filename='ENGINX00228061.nxs', Detectors=tbl, Bank=2, Peaks='2')
+
+        # There's no output workspace
+        self.assertRaises(RuntimeError,
+                          EnginXCalibrate,
+                          File='foo', Bank=1, OutputWorkspace='nop')
+
+
+    def test_fails_gracefully(self):
+        """
+        Checks a bad run.
+        """
+
+        # This should produce 'given peak center ... is outside of data range' warnings
+        # and finally raise after a 'some peaks not found' error
+        self.assertRaises(RuntimeError,
+                          EnginXCalibrate,
+                          Filename="ENGINX00228061.nxs", ExpectedPeaks=[0.2, 0.4], Bank=2)
+
+
+    def test_runs_ok(self):
+        """
+        Checks normal operation.
+        """
+
+        difc, zero = EnginXCalibrate(Filename="ENGINX00228061.nxs",
+                                     ExpectedPeaks=[1.6, 1.1, 1.8], Bank=2)
+        # There are platform specific differences in final parameter values
+        # For example, debian: 369367.57492582797; win7: 369242.28850305633
+        expected_difc = 369367.57492582797
+        # assertLess would be nices, but only available in unittest >= 2.7
+        self.assertTrue(abs((expected_difc-difc)/expected_difc) < 5e-3)
+        expected_zero = -223297.87349744083
+        self.assertTrue(abs((expected_zero-zero)/expected_zero) < 5e-3)
+
+
+
+if __name__ == '__main__':
+    unittest.main()
diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/EnginXFitPeaksTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/EnginXFitPeaksTest.py
new file mode 100644
index 0000000000000000000000000000000000000000..70b7e79936c5e58d9f030428bee0156ac37866cc
--- /dev/null
+++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/EnginXFitPeaksTest.py
@@ -0,0 +1,166 @@
+import unittest
+from mantid.simpleapi import *
+from mantid.api import *
+
+class EnginXFitPeaksTest(unittest.TestCase):
+
+    def test_wrong_properties(self):
+        """
+        Handle in/out property issues appropriately.
+        """
+
+        ws_name = 'out_ws'
+        peak = "name=BackToBackExponential, I=5000,A=1, B=1., X0=10000, S=150"
+        sws = CreateSampleWorkspace(Function="User Defined", UserDefinedFunction=peak,
+                                    NumBanks=1, BankPixelWidth=1, XMin=5000, XMax=30000,
+                                    BinWidth=5, OutputWorkspace=ws_name)
+
+        # No InputWorkspace property (required)
+        self.assertRaises(RuntimeError,
+                          EnginXFitPeaks,
+                          WorkspaceIndex=0, ExpectedPeaks='0.51, 0.72')
+
+        # Wrong WorkspaceIndex value
+        self.assertRaises(RuntimeError,
+                          EnginXFitPeaks,
+                          InputWorkspace=ws_name,
+                          WorkspaceIndex=-3, ExpectedPeaks='0.51, 0.72')
+
+        # Wrong property
+        self.assertRaises(RuntimeError,
+                          EnginXFitPeaks,
+                          InputWorkspace=ws_name, BankPixelFoo=33,
+                          WorkspaceIndex=0, ExpectedPeaks='0.51, 0.72')
+
+        # Wrong ExpectedPeaks value
+        self.assertRaises(ValueError,
+                          EnginXFitPeaks,
+                          InputWorkspace=ws_name,
+                          WorkspaceIndex=0, ExpectedPeaks='a')
+
+
+    def _check_output_ok(self, ws, ws_name='', y_dim_max=1, yvalues=None):
+        """
+        Checks expected output values from the fits
+        """
+
+        peak_def = "name=BackToBackExponential, I=4000,A=1, B=1.5, X0=10000, S=150"
+        sws = CreateSampleWorkspace(Function="User Defined", UserDefinedFunction=peak_def,
+                                    NumBanks=1, BankPixelWidth=1, XMin=5000, XMax=30000,
+                                    BinWidth=5)
+
+        # Missing input workspace
+        self.assertRaises(RuntimeError,
+                          EnginXFitPeaks,
+                          WorkspaceIndex=0, ExpectedPeaks=[0.0, 1.0])
+
+        # Wrong index
+        self.assertRaises(RuntimeError,
+                          EnginXFitPeaks,
+                          InputWorkspace=sws,
+                          WorkspaceIndex=-5, ExpectedPeaks=[0.0, 1.0])
+
+
+    def test_fitting_fails_ok(self):
+        """
+        Tests acceptable response (appropriate exception) when fitting doesn't work well
+        """
+
+        peak_def = "name=BackToBackExponential, I=8000, A=1, B=1.2, X0=10000, S=150"
+        sws = CreateSampleWorkspace(Function="User Defined",
+                                    UserDefinedFunction=peak_def,
+                                    NumBanks=1, BankPixelWidth=1,
+                                    XMin=10000, XMax=30000, BinWidth=10, Random=1)
+        # these should raise because of issues with the peak center - data range
+        self.assertRaises(RuntimeError,
+                          EnginXFitPeaks,
+                          sws, 0, [0.5, 2.5])
+        EditInstrumentGeometry(Workspace=sws, L2=[1.0], Polar=[90], PrimaryFlightPath=50)
+        self.assertRaises(RuntimeError,
+                          EnginXFitPeaks,
+                          sws, 0, [1, 3])
+
+        # this should fail because of nan/infinity issues
+        peak_def = "name=BackToBackExponential, I=12000, A=1, B=1.5, X0=10000, S=350"
+        sws = CreateSampleWorkspace(Function="User Defined", UserDefinedFunction=peak_def,
+                                    NumBanks=1, BankPixelWidth=1,
+                                    XMin=10000, XMax=30000, BinWidth=10)
+        EditInstrumentGeometry(Workspace=sws, L2=[1.0], Polar=[35], PrimaryFlightPath=35)
+        self.assertRaises(RuntimeError,
+                          EnginXFitPeaks,
+                          sws, 0, [1, 2, 3])
+
+        # this should fail because FindPeaks doesn't initialize/converge well
+        peak_def = "name=BackToBackExponential, I=90000, A=0.1, B=0.5, X0=5000, S=400"
+        sws = CreateSampleWorkspace(Function="User Defined", UserDefinedFunction=peak_def,
+                                    NumBanks=1, BankPixelWidth=1,
+                                    XMin=2000, XMax=30000, BinWidth=10)
+        EditInstrumentGeometry(Workspace=sws, L2=[1.0], Polar=[90], PrimaryFlightPath=50)
+        self.assertRaises(RuntimeError,
+                          EnginXFitPeaks,
+                          sws, 0, [0.6])
+
+
+    def test_fails_ok_1peak(self):
+        """
+        Tests fitting a single peak, which should raise because we need at least 2 peaks to
+        fit two parameters: difc and zero
+        """
+        peak_def = "name=BackToBackExponential, I=15000, A=1, B=1.2, X0=10000, S=400"
+        sws = CreateSampleWorkspace(Function="User Defined",
+                                    UserDefinedFunction=peak_def,
+                                    NumBanks=1, BankPixelWidth=1,
+                                    XMin=0, XMax=25000, BinWidth=10)
+        EditInstrumentGeometry(Workspace=sws, L2=[1.5], Polar=[90], PrimaryFlightPath=45)
+        self.assertRaises(RuntimeError,
+                          EnginXFitPeaks,
+                          sws, WorkspaceIndex=0, ExpectedPeaks='0.542')
+
+
+    def test_runs_ok_2peaks(self):
+        """
+        Tests fitting a couple of peaks.
+        """
+
+        peak_def1 = "name=BackToBackExponential, I=10000, A=1, B=0.5, X0=8000, S=350"
+        peak_def2 = "name=BackToBackExponential, I=8000, A=1, B=1.7, X0=20000, S=300"
+        sws = CreateSampleWorkspace(Function="User Defined",
+                                    UserDefinedFunction=peak_def1 + ";" + peak_def2,
+                                    NumBanks=1, BankPixelWidth=1,
+                                    XMin=5000, XMax=30000,
+                                    BinWidth=25)
+        EditInstrumentGeometry(Workspace=sws, L2=[1.5], Polar=[90], PrimaryFlightPath=50)
+        difc, zero = EnginXFitPeaks(sws, WorkspaceIndex=0, ExpectedPeaks=[0.4, 1.09])
+        # fitting results on some platforms (OSX) are different by ~0.07%
+        expected_difc = 17395.620526173196
+        self.assertTrue(abs((expected_difc-difc)/expected_difc) < 5e-3)
+        expected_zero = 1050.3378284424373
+        self.assertTrue(abs((expected_zero-zero)/expected_zero) < 5e-3)
+
+
+    def test_runs_ok_3peaks(self):
+        """
+        Tests fitting three clean peaks and different widths.
+        """
+
+        peak_def1 = "name=BackToBackExponential, I=10000, A=1, B=0.5, X0=8000, S=350"
+        peak_def2 = "name=BackToBackExponential, I=15000, A=1, B=1.7, X0=15000, S=100"
+        peak_def3 = "name=BackToBackExponential, I=8000, A=1, B=1.2, X0=20000, S=800"
+        sws = CreateSampleWorkspace(Function="User Defined",
+                                    UserDefinedFunction=
+                                    peak_def1 + ";" + peak_def2 + ";" + peak_def3,
+                                    NumBanks=1, BankPixelWidth=1,
+                                    XMin=5000, XMax=30000,
+                                    BinWidth=25)
+        EditInstrumentGeometry(Workspace=sws, L2=[1.5], Polar=[90], PrimaryFlightPath=50)
+        difc, zero = EnginXFitPeaks(sws, WorkspaceIndex=0, ExpectedPeaks=[0.4, 0.83, 1.09])
+        expected_difc = 17335.67250113934
+        # assertLess would be nices, but only available in unittest >= 2.7
+        self.assertTrue(abs((expected_difc-difc)/expected_difc) < 5e-3)
+        expected_zero = 950.9440922621866
+        self.assertTrue(abs((expected_zero-zero)/expected_zero) < 5e-3)
+
+
+
+if __name__ == '__main__':
+    unittest.main()
diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/EnginXFocusTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/EnginXFocusTest.py
new file mode 100644
index 0000000000000000000000000000000000000000..c794b6a6f30b54bd42711454c53fefaab0e88b75
--- /dev/null
+++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/EnginXFocusTest.py
@@ -0,0 +1,99 @@
+import unittest
+from mantid.simpleapi import *
+from mantid.api import *
+
+class EnginXFocusTest(unittest.TestCase):
+
+    def test_wrong_properties(self):
+        """
+        Tests proper error handling when passing wrong properties or not passing
+        required ones.
+        """
+
+        # No Filename property
+        self.assertRaises(RuntimeError,
+                          EnginXFocus,
+                          File='foo', Bank=1, OutputWorkspace='nop')
+
+        # Wrong filename
+        self.assertRaises(RuntimeError,
+                          EnginXFocus,
+                          File='foo_is_not_there', Bank=1, OutputWorkspace='nop')
+
+        # mispelled bank
+        self.assertRaises(RuntimeError,
+                          EnginXFocus,
+                          Filename='ENGINX00228061.nxs', bnk='2', OutputWorkspace='nop')
+
+        # mispelled DetectorsPosition
+        tbl = CreateEmptyTableWorkspace()
+        self.assertRaises(RuntimeError,
+                          EnginXFocus,
+                          Filename='ENGINX00228061.nxs', Detectors=tbl, OutputWorkspace='nop')
+
+
+    def _check_output_ok(self, ws, ws_name='', y_dim_max=1, yvalues=None):
+        """
+        Checks expected types, values, etc. of an output workspace from EnginXFocus.
+        """
+
+        self.assertTrue(isinstance(ws, MatrixWorkspace),
+                        'Output workspace should be a matrix workspace.')
+        self.assertEqual(ws.name(), ws_name)
+        self.assertEqual(ws.getTitle(), 'yscan;y=250.210')
+        self.assertEqual(ws.isHistogramData(), True)
+        self.assertEqual(ws.isDistribution(), True)
+        self.assertEqual(ws.getNumberHistograms(), 1)
+        self.assertEqual(ws.blocksize(), 98)
+        self.assertEqual(ws.getNEvents(), 98)
+        self.assertEqual(ws.getNumDims(), 2)
+        self.assertEqual(ws.YUnit(), 'Counts')
+        dimX = ws.getXDimension()
+        self.assertAlmostEqual( dimX.getMaximum(), 36938.078125)
+        self.assertEqual(dimX.getName(), 'Time-of-flight')
+        self.assertEqual(dimX.getUnits(), 'microsecond')
+        dimY = ws.getYDimension()
+        self.assertEqual(dimY.getMaximum(), y_dim_max)
+        self.assertEqual(dimY.getName(), 'Spectrum')
+        self.assertEqual(dimY.getUnits(), '')
+
+        if None == yvalues:
+            raise ValueError("No y-vals provided for test")
+        xvals = [10861.958645540433, 12192.372902418168, 13522.787159295902,
+                 14853.201416173637, 24166.101214317776, 34809.415269339654]
+        for i, bin in enumerate([0, 5, 10, 15, 50, 90]):
+            self.assertAlmostEqual( ws.readX(0)[bin], xvals[i])
+            self.assertAlmostEqual( ws.readY(0)[bin], yvalues[i])
+
+
+    def test_runs_ok(self):
+        """
+        Checks that output looks fine for normal operation conditions, (default) Bank=1
+        """
+
+        out_name = 'out'
+        out = EnginXFocus(Filename='ENGINX00228061.nxs', Bank=1, OutputWorkspace=out_name)
+
+        yvals = [0.0037582279159681957, 0.00751645583194, 0.0231963801368, 0.0720786940576,
+                 0.0615909620868, 0.00987979301753]
+        self._check_output_ok(ws=out, ws_name=out_name, y_dim_max=1, yvalues=yvals)
+
+
+    def test_runs_ok_bank2(self):
+        """
+        Checks that output looks fine for normal operation conditions, Bank=2
+        """
+
+        out_name = 'out_bank2'
+        out_bank2 = EnginXFocus(Filename="ENGINX00228061.nxs", Bank=2,
+                                OutputWorkspace=out_name)
+
+        yvals = [0, 0.0112746837479, 0.0394536605073, 0.0362013481777,
+                 0.0728500403862, 0.000870882282987]
+        self._check_output_ok(ws=out_bank2, ws_name=out_name, y_dim_max=1201,
+                              yvalues=yvals)
+
+
+
+if __name__ == '__main__':
+    unittest.main()
diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/IndirectILLReductionTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/IndirectILLReductionTest.py
index cee0df41dc627b48be8c28cf50c87bd8b35bea67..4da3123b7e33f8be77e95651dbbd9a97d4273462 100644
--- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/IndirectILLReductionTest.py
+++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/IndirectILLReductionTest.py
@@ -34,7 +34,7 @@ class IndirectILLReductionTest(unittest.TestCase):
         red_workspace = mtd[self.kwargs['ReducedWorkspace']]
 
         self.assertTrue(isinstance(red_workspace, mantid.api.MatrixWorkspace), "Should be a matrix workspace")
-        self.assertEqual("Energy transfer", red_workspace.getAxis(0).getUnit().caption())
+        self.assertEqual(red_workspace.getAxis(0).getUnit().unitID(), "DeltaE")
 
     def test_mirror_mode(self):
         self.kwargs['MirrorMode'] = True
@@ -48,16 +48,13 @@ class IndirectILLReductionTest(unittest.TestCase):
         right_red_workspace = mtd[self.kwargs['RightWorkspace']]
 
         self.assertTrue(isinstance(red_workspace, mantid.api.MatrixWorkspace), "Should be a matrix workspace")
-        self.assertEqual("Energy transfer", red_workspace.getAxis(0).getUnit().caption())
-        self.assertEqual("meV", red_workspace.getAxis(0).getUnit().symbol().ascii())
+        self.assertEqual(red_workspace.getAxis(0).getUnit().unitID(), "DeltaE")
 
         self.assertTrue(isinstance(left_red_workspace, mantid.api.MatrixWorkspace), "Should be a matrix workspace")
-        self.assertEqual("Energy transfer", left_red_workspace.getAxis(0).getUnit().caption())
-        self.assertEqual("meV", left_red_workspace.getAxis(0).getUnit().symbol().ascii())
+        self.assertEqual(left_red_workspace.getAxis(0).getUnit().unitID(), "DeltaE")
 
         self.assertTrue(isinstance(right_red_workspace, mantid.api.MatrixWorkspace), "Should be a matrix workspace")
-        self.assertEqual("Energy transfer", right_red_workspace.getAxis(0).getUnit().caption())
-        self.assertEqual("meV", right_red_workspace.getAxis(0).getUnit().symbol().ascii())
+        self.assertEqual(right_red_workspace.getAxis(0).getUnit().unitID(), "DeltaE")
 
     def test_mirror_mode_default_names(self):
         self.kwargs['MirrorMode'] = True
diff --git a/Code/Mantid/Framework/RemoteAlgorithms/CMakeLists.txt b/Code/Mantid/Framework/RemoteAlgorithms/CMakeLists.txt
index bef9b585d4ec4809d0a2e2c4819d795a1b92dca1..9b69bd26fb90e2bbd7e3c457e4ed2d2272e1d1d0 100644
--- a/Code/Mantid/Framework/RemoteAlgorithms/CMakeLists.txt
+++ b/Code/Mantid/Framework/RemoteAlgorithms/CMakeLists.txt
@@ -78,6 +78,12 @@ set ( TEST_FILES
 #)
 # No tests yet...
 
+if (COVERALLS)
+    foreach( loop_var ${SRC_FILES} ${INC_FILES})
+      set_property(GLOBAL APPEND PROPERTY COVERAGE_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/${loop_var}")
+    endforeach(loop_var)
+endif()
+
 # Not for now, remember later if convenient: Add a precompiled header where they are supported
 # enable_precompiled_headers ( inc/MantidRemoteAlgorithms/PrecompiledHeader.h SRC_FILES )
 
diff --git a/Code/Mantid/Framework/RemoteJobManagers/CMakeLists.txt b/Code/Mantid/Framework/RemoteJobManagers/CMakeLists.txt
index 864246c9578d445464a11b4652c6e5d0999efefa..80df6da77c32bd4af7c0eb71e6e833dddce83f54 100644
--- a/Code/Mantid/Framework/RemoteJobManagers/CMakeLists.txt
+++ b/Code/Mantid/Framework/RemoteJobManagers/CMakeLists.txt
@@ -26,6 +26,12 @@ set ( TEST_FILES
 #)
 # No Python tests yet...
 
+if (COVERALLS)
+    foreach( loop_var ${SRC_FILES} ${INC_FILES})
+      set_property(GLOBAL APPEND PROPERTY COVERAGE_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/${loop_var}")
+    endforeach(loop_var)
+endif()
+
 # Not for now, remember later if convenient: Add a precompiled header where they are supported
 # enable_precompiled_headers ( inc/MantidRemoteJobManagers/PrecompiledHeader.h SRC_FILES )
 
diff --git a/Code/Mantid/Framework/SINQ/CMakeLists.txt b/Code/Mantid/Framework/SINQ/CMakeLists.txt
index d4e8c944761ec4df5479db0980be04a8b3a6b214..21b85961503f5642fa4cccfb753c8bd153b04744 100644
--- a/Code/Mantid/Framework/SINQ/CMakeLists.txt
+++ b/Code/Mantid/Framework/SINQ/CMakeLists.txt
@@ -130,6 +130,11 @@ set ( TEST_FILES
 	UncertainValueTest.h
 )
 
+if (COVERALLS)
+    foreach( loop_var ${SRC_FILES} ${INC_FILES})
+      set_property(GLOBAL APPEND PROPERTY COVERAGE_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/${loop_var}")
+    endforeach(loop_var)
+endif()
 
 # Add a precompiled header where they are supported
 enable_precompiled_headers ( inc/MantidSINQ/PrecompiledHeader.h SRC_FILES )
diff --git a/Code/Mantid/Framework/ScriptRepository/CMakeLists.txt b/Code/Mantid/Framework/ScriptRepository/CMakeLists.txt
index 19d5d8dde51857b351e97f388974bd49ca9454a8..301327740d88d65ec2746429210eb3f45ff6d61e 100644
--- a/Code/Mantid/Framework/ScriptRepository/CMakeLists.txt
+++ b/Code/Mantid/Framework/ScriptRepository/CMakeLists.txt
@@ -11,6 +11,11 @@ set ( TEST_FILES
 	ScriptRepositoryTestImpl.h
 )
 
+if (COVERALLS)
+    foreach( loop_var ${SRCS_FILES} ${INC_FILES})
+      set_property(GLOBAL APPEND PROPERTY COVERAGE_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/${loop_var}")
+    endforeach(loop_var)
+endif()
 
 # Add the target for this directory
 add_library ( ScriptRepository ${SRC_FILES} ${INC_FILES} )
diff --git a/Code/Mantid/Framework/UserAlgorithms/CMakeLists.txt b/Code/Mantid/Framework/UserAlgorithms/CMakeLists.txt
index d563012295fde380f2683d600bad14d72a3182d5..948f8d23234704daec7e154c4dcce54b5d5e25ec 100644
--- a/Code/Mantid/Framework/UserAlgorithms/CMakeLists.txt
+++ b/Code/Mantid/Framework/UserAlgorithms/CMakeLists.txt
@@ -16,6 +16,12 @@ set ( INC_FILES HelloWorldAlgorithm.h
                 WorkspaceAlgorithm.h
 )
 
+if (COVERALLS)
+    foreach( loop_var ${SRC_FILES} ${INC_FILES})
+      set_property(GLOBAL APPEND PROPERTY COVERAGE_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/${loop_var}")
+    endforeach(loop_var)
+endif()
+
 if(UNITY_BUILD)
   include(UnityBuild)
   enable_unity_build(UserAlgorithms SRC_FILES SRC_UNITY_IGNORE_FILES 10)
diff --git a/Code/Mantid/Framework/WorkflowAlgorithms/CMakeLists.txt b/Code/Mantid/Framework/WorkflowAlgorithms/CMakeLists.txt
index 2d4b51d5b6419fdc8dea40a85f309392d3e9c9d4..4c72035f2b244257c83e15fc11329c9ef7de1f78 100644
--- a/Code/Mantid/Framework/WorkflowAlgorithms/CMakeLists.txt
+++ b/Code/Mantid/Framework/WorkflowAlgorithms/CMakeLists.txt
@@ -87,6 +87,12 @@ set ( TEST_PY_FILES
   SANSBeamFluxCorrectionTest.py 
 )
 
+if (COVERALLS)
+    foreach( loop_var ${SRC_FILES} ${INC_FILES})
+      set_property(GLOBAL APPEND PROPERTY COVERAGE_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/${loop_var}")
+    endforeach(loop_var)
+endif()
+
 if(UNITY_BUILD)
   include(UnityBuild)
   enable_unity_build(WorkflowAlgorithms SRC_FILES SRC_UNITY_IGNORE_FILES 10)
diff --git a/Code/Mantid/Framework/WorkflowAlgorithms/src/EQSANSDarkCurrentSubtraction.cpp b/Code/Mantid/Framework/WorkflowAlgorithms/src/EQSANSDarkCurrentSubtraction.cpp
index 9e8a2ed099e6298123803123a0176764bb43dfad..ccbee26771fb4b91b36ff055ef4b162a6576c613 100644
--- a/Code/Mantid/Framework/WorkflowAlgorithms/src/EQSANSDarkCurrentSubtraction.cpp
+++ b/Code/Mantid/Framework/WorkflowAlgorithms/src/EQSANSDarkCurrentSubtraction.cpp
@@ -133,25 +133,15 @@ void EQSANSDarkCurrentSubtraction::exec() {
   // Normalize the dark current and data to counting time
   double scaling_factor = 1.0;
   if (inputWS->run().hasProperty("proton_charge")) {
-    Mantid::Kernel::Property *prop =
-        inputWS->run().getProperty("proton_charge");
-    Mantid::Kernel::TimeSeriesProperty<double> *dp =
-        dynamic_cast<Mantid::Kernel::TimeSeriesProperty<double> *>(prop);
+    auto dp = inputWS->run().getTimeSeriesProperty<double>("proton_charge");
     double duration = dp->getStatistics().duration;
 
-    prop = darkWS->run().getProperty("proton_charge");
-    dp = dynamic_cast<Mantid::Kernel::TimeSeriesProperty<double> *>(prop);
+    dp = darkWS->run().getTimeSeriesProperty<double>("proton_charge");
     double dark_duration = dp->getStatistics().duration;
     scaling_factor = duration / dark_duration;
   } else if (inputWS->run().hasProperty("timer")) {
-    Mantid::Kernel::Property *prop = inputWS->run().getProperty("timer");
-    Mantid::Kernel::PropertyWithValue<double> *dp =
-        dynamic_cast<Mantid::Kernel::PropertyWithValue<double> *>(prop);
-    double duration = *dp;
-
-    prop = darkWS->run().getProperty("timer");
-    dp = dynamic_cast<Mantid::Kernel::PropertyWithValue<double> *>(prop);
-    double dark_duration = *dp;
+    double duration = inputWS->run().getPropertyValueAsType<double>("timer");
+    double dark_duration = darkWS->run().getPropertyValueAsType<double>("timer");;
     scaling_factor = duration / dark_duration;
   } else {
     output_message +=
diff --git a/Code/Mantid/Framework/WorkflowAlgorithms/src/EQSANSLoad.cpp b/Code/Mantid/Framework/WorkflowAlgorithms/src/EQSANSLoad.cpp
index 8a2fcae8bfed5f8d2db29916532b8aa1a1a571dc..bc51a55a93b46a1dc41e65f74b8bdc27de7814b4 100644
--- a/Code/Mantid/Framework/WorkflowAlgorithms/src/EQSANSLoad.cpp
+++ b/Code/Mantid/Framework/WorkflowAlgorithms/src/EQSANSLoad.cpp
@@ -593,10 +593,7 @@ void EQSANSLoad::exec() {
   int run_number = 0;
   std::string config_file = "";
   if (dataWS->run().hasProperty("run_number")) {
-    Mantid::Kernel::Property *prop = dataWS->run().getProperty("run_number");
-    Mantid::Kernel::PropertyWithValue<std::string> *dp =
-        dynamic_cast<Mantid::Kernel::PropertyWithValue<std::string> *>(prop);
-    const std::string run_str = *dp;
+    const std::string run_str = dataWS->run().getPropertyValueAsType<std::string>("run_number");
     Poco::NumberParser::tryParse(run_str, run_number);
     // Find a proper config file
     config_file = findConfigFile(run_number);
diff --git a/Code/Mantid/Framework/WorkflowAlgorithms/src/EQSANSMonitorTOF.cpp b/Code/Mantid/Framework/WorkflowAlgorithms/src/EQSANSMonitorTOF.cpp
index b0120225842426eee43e581d2563b09522640339..6b9de1045cc2608430b59656950347fc00f24447 100644
--- a/Code/Mantid/Framework/WorkflowAlgorithms/src/EQSANSMonitorTOF.cpp
+++ b/Code/Mantid/Framework/WorkflowAlgorithms/src/EQSANSMonitorTOF.cpp
@@ -73,19 +73,15 @@ void EQSANSMonitorTOF::exec() {
   double source_to_monitor = (monitor_z - source_z) * 1000.0;
 
   // Calculate the frame width
-  double frequency = dynamic_cast<TimeSeriesProperty<double> *>(
-                         inputWS->run().getLogData("frequency"))
-                         ->getStatistics()
-                         .mean;
+  auto log = inputWS->run().getTimeSeriesProperty<double>("frequency");
+  double frequency = log->getStatistics().mean;
   double tof_frame_width = 1.0e6 / frequency;
 
   // Determine whether we need frame skipping or not by checking the chopper
   // speed
   bool frame_skipping = false;
-  const double chopper_speed = dynamic_cast<TimeSeriesProperty<double> *>(
-                                   inputWS->run().getLogData("Speed1"))
-                                   ->getStatistics()
-                                   .mean;
+  log = inputWS->run().getTimeSeriesProperty<double>("Speed1");
+  const double chopper_speed = log->getStatistics().mean;
   if (std::fabs(chopper_speed - frequency / 2.0) < 1.0)
     frame_skipping = true;
 
@@ -211,10 +207,8 @@ double EQSANSMonitorTOF::getTofOffset(MatrixWorkspace_const_sptr inputWS,
   double chopper_frameskip_srcpulse_wl_1[4] = {0, 0, 0, 0};
 
   // Calculate the frame width
-  double frequency = dynamic_cast<TimeSeriesProperty<double> *>(
-                         inputWS->run().getLogData("frequency"))
-                         ->getStatistics()
-                         .mean;
+  auto log = inputWS->run().getTimeSeriesProperty<double>("frequency");
+  double frequency = log->getStatistics().mean;
   double tof_frame_width = 1.0e6 / frequency;
 
   double tmp_frame_width = tof_frame_width;
@@ -236,16 +230,12 @@ double EQSANSMonitorTOF::getTofOffset(MatrixWorkspace_const_sptr inputWS,
     // Read chopper information
     std::ostringstream phase_str;
     phase_str << "Phase" << i + 1;
-    chopper_set_phase[i] = dynamic_cast<TimeSeriesProperty<double> *>(
-                               inputWS->run().getLogData(phase_str.str()))
-                               ->getStatistics()
-                               .mean;
+    log = inputWS->run().getTimeSeriesProperty<double>(phase_str.str());
+    chopper_set_phase[i] = log->getStatistics().mean;
     std::ostringstream speed_str;
     speed_str << "Speed" << i + 1;
-    chopper_speed[i] = dynamic_cast<TimeSeriesProperty<double> *>(
-                           inputWS->run().getLogData(speed_str.str()))
-                           ->getStatistics()
-                           .mean;
+    log = inputWS->run().getTimeSeriesProperty<double>(speed_str.str());
+    chopper_speed[i] = log->getStatistics().mean;
 
     // Only process choppers with non-zero speed
     if (chopper_speed[i] <= 0)
diff --git a/Code/Mantid/Framework/WorkflowAlgorithms/src/EQSANSQ2D.cpp b/Code/Mantid/Framework/WorkflowAlgorithms/src/EQSANSQ2D.cpp
index 5dcf7f9d1ca86a7d6316cdac60a992f598ca4bcb..fdedcf9074f68177be3891380e98ae05df6525d8 100644
--- a/Code/Mantid/Framework/WorkflowAlgorithms/src/EQSANSQ2D.cpp
+++ b/Code/Mantid/Framework/WorkflowAlgorithms/src/EQSANSQ2D.cpp
@@ -33,10 +33,7 @@ void EQSANSQ2D::init() {
 /// @param inputWS :: input workspace
 /// @param pname :: name of the property to retrieve
 double getRunProperty(MatrixWorkspace_sptr inputWS, const std::string &pname) {
-  Mantid::Kernel::Property *prop = inputWS->run().getProperty(pname);
-  Mantid::Kernel::PropertyWithValue<double> *dp =
-      dynamic_cast<Mantid::Kernel::PropertyWithValue<double> *>(prop);
-  return *dp;
+  return inputWS->run().getPropertyValueAsType<double>(pname);
 }
 
 /// Execute algorithm
diff --git a/Code/Mantid/Framework/WorkflowAlgorithms/src/HFIRDarkCurrentSubtraction.cpp b/Code/Mantid/Framework/WorkflowAlgorithms/src/HFIRDarkCurrentSubtraction.cpp
index 0535a83180f36439d1872f080b8208ec76dec586..cbcbc6da35a9aba7d385f2f1896cf4ecfec50a29 100644
--- a/Code/Mantid/Framework/WorkflowAlgorithms/src/HFIRDarkCurrentSubtraction.cpp
+++ b/Code/Mantid/Framework/WorkflowAlgorithms/src/HFIRDarkCurrentSubtraction.cpp
@@ -157,10 +157,7 @@ double
 HFIRDarkCurrentSubtraction::getCountingTime(MatrixWorkspace_sptr inputWS) {
   // First, look whether we have the information in the log
   if (inputWS->run().hasProperty("timer")) {
-    Mantid::Kernel::Property *prop = inputWS->run().getProperty("timer");
-    Mantid::Kernel::PropertyWithValue<double> *dp =
-        dynamic_cast<Mantid::Kernel::PropertyWithValue<double> *>(prop);
-    return *dp;
+    return inputWS->run().getPropertyValueAsType<double>("timer");
   } else {
     // If we don't have the information in the log, use the default timer
     // spectrum
diff --git a/Code/Mantid/Framework/WorkflowAlgorithms/src/HFIRInstrument.cpp b/Code/Mantid/Framework/WorkflowAlgorithms/src/HFIRInstrument.cpp
index 8be6d3595e6d0c8d88e13f9d60316fe1661a8ea2..8cf05165b1772cbf2bf9442991965cfd9eda644f 100644
--- a/Code/Mantid/Framework/WorkflowAlgorithms/src/HFIRInstrument.cpp
+++ b/Code/Mantid/Framework/WorkflowAlgorithms/src/HFIRInstrument.cpp
@@ -87,11 +87,7 @@ void getDefaultBeamCenter(API::MatrixWorkspace_sptr dataWS, double &pixel_x,
 }
 
 double getSourceToSampleDistance(API::MatrixWorkspace_sptr dataWS) {
-  Mantid::Kernel::Property *prop =
-      dataWS->run().getProperty("number-of-guides");
-  Mantid::Kernel::PropertyWithValue<int> *dp =
-      dynamic_cast<Mantid::Kernel::PropertyWithValue<int> *>(prop);
-  const int nguides = *dp;
+  const int nguides = dataWS->run().getPropertyValueAsType<int>("number-of-guides");
 
   std::vector<std::string> pars =
       dataWS->getInstrument()->getStringParameter("aperture-distances");
diff --git a/Code/Mantid/Framework/WorkflowAlgorithms/src/HFIRSANSNormalise.cpp b/Code/Mantid/Framework/WorkflowAlgorithms/src/HFIRSANSNormalise.cpp
index c5839a664c39c000c895ffcfa8a40480fb25576d..07d56ebb5018fb7dac36589e124101f11c6b61eb 100644
--- a/Code/Mantid/Framework/WorkflowAlgorithms/src/HFIRSANSNormalise.cpp
+++ b/Code/Mantid/Framework/WorkflowAlgorithms/src/HFIRSANSNormalise.cpp
@@ -40,10 +40,7 @@ void HFIRSANSNormalise::exec() {
 
   // Get the monitor or timer
   boost::algorithm::to_lower(normalisation);
-  Mantid::Kernel::Property *prop = inputWS->run().getProperty(normalisation);
-  Mantid::Kernel::PropertyWithValue<double> *dp =
-      dynamic_cast<Mantid::Kernel::PropertyWithValue<double> *>(prop);
-  double norm_count = *dp;
+  double norm_count = inputWS->run().getPropertyValueAsType<double>(normalisation);
 
   double factor;
   if (boost::iequals(normalisation, "monitor")) {
diff --git a/Code/Mantid/Framework/WorkflowAlgorithms/src/RefReduction.cpp b/Code/Mantid/Framework/WorkflowAlgorithms/src/RefReduction.cpp
index a861fefdef291d4b5270482e8d423fd0e2e30be0..b0a3918e42043f2286dbcdedcb5552b672a9c6d4 100644
--- a/Code/Mantid/Framework/WorkflowAlgorithms/src/RefReduction.cpp
+++ b/Code/Mantid/Framework/WorkflowAlgorithms/src/RefReduction.cpp
@@ -515,10 +515,7 @@ IEventWorkspace_sptr RefReduction::loadData(const std::string dataRun,
       if (instrument.compare("REF_M") == 0) {
         double det_distance =
             rawWS->getInstrument()->getDetector(0)->getPos().Z();
-        Mantid::Kernel::Property *prop =
-            rawWS->run().getProperty("SampleDetDis");
-        Mantid::Kernel::TimeSeriesProperty<double> *dp =
-            dynamic_cast<Mantid::Kernel::TimeSeriesProperty<double> *>(prop);
+        auto dp = rawWS->run().getTimeSeriesProperty<double>("SampleDetDis");
         double sdd = dp->getStatistics().mean / 1000.0;
         IAlgorithm_sptr mvAlg =
             createChildAlgorithm("MoveInstrumentComponent", 0.2, 0.25);
@@ -635,9 +632,7 @@ double RefReduction::calculateAngleREFM(MatrixWorkspace_sptr workspace) {
 
   double direct_beam_pix = getProperty("DirectPixel");
   if (isEmpty(direct_beam_pix)) {
-    Mantid::Kernel::Property *prop = workspace->run().getProperty("DIRPIX");
-    Mantid::Kernel::TimeSeriesProperty<double> *dp =
-        dynamic_cast<Mantid::Kernel::TimeSeriesProperty<double> *>(prop);
+    auto dp = workspace->run().getTimeSeriesProperty<double>("DIRPIX");
     direct_beam_pix = dp->getStatistics().mean;
   }
 
@@ -662,13 +657,10 @@ double RefReduction::calculateAngleREFM(MatrixWorkspace_sptr workspace) {
 }
 
 double RefReduction::calculateAngleREFL(MatrixWorkspace_sptr workspace) {
-  Mantid::Kernel::Property *prop = workspace->run().getProperty("ths");
-  Mantid::Kernel::TimeSeriesProperty<double> *dp =
-      dynamic_cast<Mantid::Kernel::TimeSeriesProperty<double> *>(prop);
+  auto dp = workspace->run().getTimeSeriesProperty<double>("ths");
   const double ths = dp->getStatistics().mean;
 
-  prop = workspace->run().getProperty("tthd");
-  dp = dynamic_cast<Mantid::Kernel::TimeSeriesProperty<double> *>(prop);
+  dp = workspace->run().getTimeSeriesProperty<double>("tthd");
   const double tthd = dp->getStatistics().mean;
 
   double offset = getProperty("AngleOffset");
diff --git a/Code/Mantid/MantidPlot/pymantidplot/proxies.py b/Code/Mantid/MantidPlot/pymantidplot/proxies.py
index 052bb7f3bca2a37af9ba17fa10687b5e31c65a7d..90099772f1d850181a11b100b733da15ba0c14a3 100644
--- a/Code/Mantid/MantidPlot/pymantidplot/proxies.py
+++ b/Code/Mantid/MantidPlot/pymantidplot/proxies.py
@@ -8,6 +8,7 @@ from PyQt4 import QtCore, QtGui
 from PyQt4.QtCore import Qt, pyqtSlot
 import __builtin__
 import mantid
+import mantidqtpython
 
 #-----------------------------------------------------------------------------
 #--------------------------- MultiThreaded Access ----------------------------
@@ -906,3 +907,27 @@ class TiledWindowProxy(QtProxyObject):
         Clear the content this TiledWindow.
         """
         threadsafe_call(self._getHeldObject().clear)
+
+def showHelpPage(page_name=None):
+    """Show a page in the help system"""
+    window = threadsafe_call(mantidqtpython.MantidQt.API.InterfaceManager().showHelpPage, page_name)
+
+def showWikiPage(page_name=None):
+    """Show a wiki page through the help system"""
+    window = threadsafe_call(mantidqtpython.MantidQt.API.InterfaceManager().showWikiPage, page_name)
+
+def showAlgorithmHelp(algorithm=None, version=-1):
+    """Show an algorithm help page"""
+    window = threadsafe_call(mantidqtpython.MantidQt.API.InterfaceManager().showAlgorithmHelp, algorithm, version)
+
+def showConceptHelp(name=None):
+    """Show a concept help page"""
+    window = threadsafe_call(mantidqtpython.MantidQt.API.InterfaceManager().showConceptHelp, name)
+
+def showFitFunctionHelp(name=None):
+    """Show a fit function help page"""
+    window = threadsafe_call(mantidqtpython.MantidQt.API.InterfaceManager().showFitFunctionHelp, name)
+
+def showCustomInterfaceHelp(name=None):
+    """Show a custom interface help page"""
+    window = threadsafe_call(mantidqtpython.MantidQt.API.InterfaceManager().showCustomInterfaceHelp, name)
diff --git a/Code/Mantid/MantidPlot/src/AssociationsDialog.cpp b/Code/Mantid/MantidPlot/src/AssociationsDialog.cpp
index 583686c45c4b45b9bec982935da28d618fa24162..2dff8349714b005b3140e78c31045b75da958510 100644
--- a/Code/Mantid/MantidPlot/src/AssociationsDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/AssociationsDialog.cpp
@@ -135,43 +135,45 @@ void AssociationsDialog::changePlotAssociation(int curve, const QString& text)
   QStringList lst = text.split(",", QString::SkipEmptyParts);
   if (lst.count() == 1){
     c->setTitle(lst[0]);
-    if (graph->curveType(curve) == Graph::Box)
-      dynamic_cast<BoxCurve*>(c)->loadData();
-    else if (graph->curveType(curve) == Graph::Pie)
-      dynamic_cast<QwtPieCurve*>(c)->loadData();
+    if (auto b = dynamic_cast<BoxCurve*>(c))
+      b->loadData();
+    else if (auto p = dynamic_cast<QwtPieCurve*>(c))
+      p->loadData();
   } else if (lst.count() == 2){
     c->setXColumnName(lst[0].remove("(X)"));
     c->setTitle(lst[1].remove("(Y)"));
     c->loadData();
   } else if (lst.count() == 3){//curve with error bars
-    QwtErrorPlotCurve *er = dynamic_cast<QwtErrorPlotCurve *>(c);
-    QString xColName = lst[0].remove("(X)");
-    QString yColName = lst[1].remove("(Y)");
-    QString erColName = lst[2].remove("(xErr)").remove("(yErr)");
-    DataCurve *master_curve = graph->masterCurve(xColName, yColName);
-    if (!master_curve)
-      return;
-
-    int type = QwtErrorPlotCurve::Vertical;
-    if (text.contains("(xErr)"))
-      type = QwtErrorPlotCurve::Horizontal;
-    er->setDirection(type);
-    er->setTitle(erColName);
-    if (master_curve != er->masterCurve())
-      er->setMasterCurve(master_curve);
-    else
-      er->loadData();
+    if (QwtErrorPlotCurve *er = dynamic_cast<QwtErrorPlotCurve *>(c)) {
+      QString xColName = lst[0].remove("(X)");
+      QString yColName = lst[1].remove("(Y)");
+      QString erColName = lst[2].remove("(xErr)").remove("(yErr)");
+      DataCurve *master_curve = graph->masterCurve(xColName, yColName);
+      if (!master_curve)
+        return;
+
+      int type = QwtErrorPlotCurve::Vertical;
+      if (text.contains("(xErr)"))
+        type = QwtErrorPlotCurve::Horizontal;
+      er->setDirection(type);
+      er->setTitle(erColName);
+      if (master_curve != er->masterCurve())
+        er->setMasterCurve(master_curve);
+      else
+        er->loadData();
+    }
   } else if (lst.count() == 4) {
-    VectorCurve *v = dynamic_cast<VectorCurve *>(c);
-    v->setXColumnName(lst[0].remove("(X)"));
-    v->setTitle(lst[1].remove("(Y)"));
-
-    QString xEndCol = lst[2].remove("(X)").remove("(A)");
-    QString yEndCol = lst[3].remove("(Y)").remove("(M)");
-    if (v->vectorEndXAColName() != xEndCol || v->vectorEndYMColName() != yEndCol)
-      v->setVectorEnd(xEndCol, yEndCol);
-    else
-      v->loadData();
+    if (VectorCurve *v = dynamic_cast<VectorCurve *>(c)) {
+      v->setXColumnName(lst[0].remove("(X)"));
+      v->setTitle(lst[1].remove("(Y)"));
+
+      QString xEndCol = lst[2].remove("(X)").remove("(A)");
+      QString yEndCol = lst[3].remove("(Y)").remove("(M)");
+      if (v->vectorEndXAColName() != xEndCol || v->vectorEndYMColName() != yEndCol)
+        v->setVectorEnd(xEndCol, yEndCol);
+      else
+        v->loadData();
+    }
   }
   graph->notifyChanges();
 }
@@ -384,11 +386,12 @@ void AssociationsDialog::setGraph(Graph *g)
         if (it->rtti() != QwtPlotItem::Rtti_PlotCurve)
             continue;
 
-        if (dynamic_cast<const DataCurve *>(it)->type() != Graph::Function){
-            QString s = dynamic_cast<const DataCurve *>(it)->plotAssociation();
-            if (dynamic_cast<const DataCurve *>(it)->table()){
-                QString table = dynamic_cast<const DataCurve *>(it)->table()->objectName();
-                plotAssociationsList << table + ": " + s.remove(table + "_");
+        auto dataCurve = dynamic_cast<const DataCurve *>(it);
+        if (dataCurve && dataCurve->type() != Graph::Function){
+            QString s = dataCurve->plotAssociation();
+            if (auto table = dataCurve->table()){
+                QString tableName = table->objectName();
+                plotAssociationsList << tableName + ": " + s.remove(tableName + "_");
             }
         }
   }
diff --git a/Code/Mantid/MantidPlot/src/AxesDialog.cpp b/Code/Mantid/MantidPlot/src/AxesDialog.cpp
index 70b07044288a54f3c40a5a271fb080ce5dbffbb2..861a010e16a3d79023cbe3bfecafde66992d8355 100644
--- a/Code/Mantid/MantidPlot/src/AxesDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/AxesDialog.cpp
@@ -1165,9 +1165,9 @@ void AxesDialog::updateGrid()
       QList<MdiSubWindow *> windows = m_app->windowsList();
       foreach(MdiSubWindow *w, windows)
       {
-        if (w->isA("MultiLayer"))
+        if (auto multi = dynamic_cast<MultiLayer*>(w))
         {
-          QList<Graph *> layers = (dynamic_cast<MultiLayer*>(w))->layersList();
+          QList<Graph *> layers = multi->layersList();
           foreach(Graph *g, layers)
           {
             if (g->isPiePlot())
diff --git a/Code/Mantid/MantidPlot/src/AxisDetails.cpp b/Code/Mantid/MantidPlot/src/AxisDetails.cpp
index ea73a025c5889fe8c90d818d6c8e81564a792dd6..badf90ceef098fc9dfedab09401074077cbcfd6a 100644
--- a/Code/Mantid/MantidPlot/src/AxisDetails.cpp
+++ b/Code/Mantid/MantidPlot/src/AxisDetails.cpp
@@ -373,7 +373,7 @@ bool AxisDetails::valid()
     }
   }
   Table *w = m_app->table(m_cmbColName->currentText());
-  return m_initialised && m_app && m_graph && !((m_cmbAxisType->currentIndex() == ScaleDraw::Text || m_cmbAxisType->currentIndex() == ScaleDraw::ColHeader) && !w);
+  return m_initialised && m_graph && !((m_cmbAxisType->currentIndex() == ScaleDraw::Text || m_cmbAxisType->currentIndex() == ScaleDraw::ColHeader) && !w);
 }
 
 /** Applies the grid paremeters to the graphs
diff --git a/Code/Mantid/MantidPlot/src/ColorMapDialog.cpp b/Code/Mantid/MantidPlot/src/ColorMapDialog.cpp
index 4bb10322c6a949ce2839eb6019713f9bf28c3be8..b6fe6444c66ead984750553e4e9749d8162b1708 100644
--- a/Code/Mantid/MantidPlot/src/ColorMapDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/ColorMapDialog.cpp
@@ -34,31 +34,31 @@
 #include <QLayout>
 
 ColorMapDialog::ColorMapDialog(QWidget* parent, Qt::WFlags fl)
-	: QDialog(parent, fl)
+  : QDialog(parent, fl), applyBtn(NULL), closeBtn(NULL), editor(NULL), d_matrix(NULL)
 {
-setObjectName( "ColorMapDialog" );
-setWindowTitle(tr("MantidPlot") + " - " + tr("Custom Color Map"));
-editor = new ColorMapEditor();
+  setObjectName( "ColorMapDialog" );
+  setWindowTitle(tr("MantidPlot") + " - " + tr("Custom Color Map"));
+  editor = new ColorMapEditor();
 	
-applyBtn = new QPushButton(tr("&Apply"));
-connect(applyBtn, SIGNAL(clicked()), this, SLOT(apply()));
+  applyBtn = new QPushButton(tr("&Apply"));
+  connect(applyBtn, SIGNAL(clicked()), this, SLOT(apply()));
 
-closeBtn = new QPushButton(tr("&Close"));
-connect(closeBtn, SIGNAL(clicked()), this, SLOT(reject()));
+  closeBtn = new QPushButton(tr("&Close"));
+  connect(closeBtn, SIGNAL(clicked()), this, SLOT(reject()));
 
-QHBoxLayout* hb = new QHBoxLayout();
-hb->setSpacing(5);
-hb->addStretch();
-hb->addWidget(applyBtn);
-hb->addWidget(closeBtn);
-hb->addStretch();
+  QHBoxLayout* hb = new QHBoxLayout();
+  hb->setSpacing(5);
+  hb->addStretch();
+  hb->addWidget(applyBtn);
+  hb->addWidget(closeBtn);
+  hb->addStretch();
 	
-QVBoxLayout* vl = new QVBoxLayout(this);
-vl->setSpacing(0);
-vl->addWidget(editor);	
-vl->addLayout(hb);
+  QVBoxLayout* vl = new QVBoxLayout(this);
+  vl->setSpacing(0);
+  vl->addWidget(editor);
+  vl->addLayout(hb);
 	
-setMaximumWidth(editor->width() + 20);
+  setMaximumWidth(editor->width() + 20);
 }
 
 void ColorMapDialog::setMatrix(Matrix *m)
diff --git a/Code/Mantid/MantidPlot/src/ConfigDialog.cpp b/Code/Mantid/MantidPlot/src/ConfigDialog.cpp
index 0f05e50e681bbeda61323c300b2576507547fe9f..50f017b0e9f9eab3ed05df4733927bd9106317db 100644
--- a/Code/Mantid/MantidPlot/src/ConfigDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/ConfigDialog.cpp
@@ -254,6 +254,9 @@ void ConfigDialog::initTablesPage()
 void ConfigDialog::initPlotsPage()
 {
   ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+  if (!app) {
+    throw std::logic_error("Parent of ConfigDialog is not ApplicationWindow as expected.");
+  }
 
   plotsTabWidget = new QTabWidget();
 
@@ -364,6 +367,9 @@ void ConfigDialog::showFrameWidth(bool ok)
 void ConfigDialog::initPlots3DPage()
 {
   ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+  if (!app) {
+    throw std::logic_error("Parent of ConfigDialog is not ApplicationWindow as expected.");
+  }
   plots3D = new QWidget();
 
   QGroupBox * topBox = new QGroupBox();
@@ -1431,6 +1437,9 @@ void ConfigDialog::initCurveFittingTab()
   }
 
   ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+  if (!app) {
+    throw std::logic_error("Parent of ConfigDialog is not ApplicationWindow as expected.");
+  }
 
   // Set the correct default property
   QString setting = app->mantidUI->fitFunctionBrowser()->getAutoBackgroundString();
@@ -1505,6 +1514,9 @@ void ConfigDialog::initCurveFittingTab()
 void ConfigDialog::initOptionsPage()
 {
   ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+  if (!app) {
+    throw std::logic_error("Parent of ConfigDialog is not ApplicationWindow as expected.");
+  }
 
   plotOptions = new QWidget();
 
@@ -1692,6 +1704,9 @@ void ConfigDialog::initAxesPage()
 void ConfigDialog::initCurvesPage()
 {
   ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+  if (!app) {
+    throw std::logic_error("Parent of ConfigDialog is not ApplicationWindow as expected.");
+  }
 
   curves = new QWidget();
 
@@ -1743,6 +1758,9 @@ void ConfigDialog::initCurvesPage()
 void ConfigDialog::initFittingPage()
 {
   ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+  if (!app) {
+    throw std::logic_error("Parent of ConfigDialog is not ApplicationWindow as expected.");
+  }
   fitPage = new QWidget();
 
   groupBoxFittingCurve = new QGroupBox();
@@ -1821,6 +1839,9 @@ void ConfigDialog::initFittingPage()
 void ConfigDialog::initConfirmationsPage()
 {
   ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+  if (!app) {
+    throw std::logic_error("Parent of ConfigDialog is not ApplicationWindow as expected.");
+  }
   confirm = new QWidget();
 
   groupBoxConfirm = new QGroupBox();
@@ -1913,6 +1934,9 @@ void ConfigDialog::languageChange()
 {
   setWindowTitle( tr( "MantidPlot - Choose default settings" ) ); //Mantid
   ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+  if (!app) {
+    throw std::logic_error("Parent of ConfigDialog is not ApplicationWindow as expected.");
+  }
 
   // pages list
   itemsList->clear();
@@ -2363,10 +2387,10 @@ void ConfigDialog::apply()
       QList<MdiSubWindow *> windows = app->windowsList();
       foreach(MdiSubWindow *w, windows){
         w->setLocale(locale);
-        if(w->isA("Table"))
-          (dynamic_cast<Table *>(w))->updateDecimalSeparators();
-        else if(w->isA("Matrix"))
-          (dynamic_cast<Matrix *>(w))->resetView();
+        if(auto table = dynamic_cast<Table *>(w))
+          table->updateDecimalSeparators();
+        else if(auto matrix = dynamic_cast<Matrix *>(w))
+          matrix->resetView();
       }
       app->modifiedProject();
       QApplication::restoreOverrideCursor();
@@ -2548,6 +2572,9 @@ void ConfigDialog::updateCurveFitSettings()
   }
 
   ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+  if (!app) {
+    throw std::logic_error("Parent of ConfigDialog is not ApplicationWindow as expected.");
+  }
 
   // cfgSvc.setString("curvefitting.autoBackground", setting);
   app->mantidUI->fitFunctionBrowser()->setAutoBackgroundName(QString::fromStdString(setting));
@@ -2594,8 +2621,9 @@ void ConfigDialog::updateMantidOptionsTab()
      cfgSvc.setString("algorithms.categories.hidden",hiddenCategoryString);
 
     //update the algorithm tree
-    ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
-    app->mantidUI->updateAlgorithms();
+    if (ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget())) {
+      app->mantidUI->updateAlgorithms();
+    }
   }
 }
 
@@ -2802,6 +2830,9 @@ void ConfigDialog::gotoMantidDirectories()
 void ConfigDialog::switchToLanguage(int param)
 {
   ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+  if (!app) {
+    throw std::logic_error("Parent of ConfigDialog is not ApplicationWindow as expected.");
+  }
   app->switchToLanguage(param);
   languageChange();
 }
diff --git a/Code/Mantid/MantidPlot/src/ContourLinesEditor.cpp b/Code/Mantid/MantidPlot/src/ContourLinesEditor.cpp
index 38cde44c66f8bab74199e02321102ce9b6fd31c6..19ff48b3bf2c9a39d2da9d592d99f953a1315e9b 100644
--- a/Code/Mantid/MantidPlot/src/ContourLinesEditor.cpp
+++ b/Code/Mantid/MantidPlot/src/ContourLinesEditor.cpp
@@ -43,11 +43,25 @@
 #include <QPainter>
 #include <QGroupBox>
 
+#include <stdexcept>
+
 ContourLinesEditor::ContourLinesEditor(const QLocale& locale, int precision, QWidget* parent)
 				: QWidget(parent),
-				d_spectrogram(NULL),
-				d_locale(locale),
-				d_precision(precision)
+                                  table(NULL),
+                                  insertBtn(NULL),
+                                  deleteBtn(NULL),
+                                  d_spectrogram(NULL),
+                                  d_locale(locale),
+                                  d_precision(precision),
+                                  penDialog(NULL),
+                                  penColorBox(NULL),
+                                  penStyleBox(NULL),
+                                  penWidthBox(NULL),
+                                  applyAllColorBox(NULL),
+                                  applyAllWidthBox(NULL),
+                                  applyAllStyleBox(NULL),
+                                  d_pen_index(0),
+                                  d_pen_list()
 {
 	table = new QTableWidget();
 	table->setColumnCount(2);
@@ -169,16 +183,14 @@ void ContourLinesEditor::insertLevel()
 		return;
 
 	int row = table->currentRow();
-	DoubleSpinBox *sb = dynamic_cast<DoubleSpinBox*>(table->cellWidget(row, 0));
-	if (!sb)
-		return;
+	DoubleSpinBox *sb = table_cellWidget<DoubleSpinBox>(row, 0);
 
 	QwtDoubleInterval range = d_spectrogram->data().range();
 	double current_value = sb->value();
 	double previous_value = range.minValue ();
-	sb = dynamic_cast<DoubleSpinBox*>(table->cellWidget(row - 1, 0));
-	if (sb)
-		previous_value = sb->value();
+  sb = dynamic_cast<DoubleSpinBox*>(table->cellWidget(row - 1, 0));
+  if (sb)
+    previous_value = sb->value();
 
 	double val = 0.5*(current_value + previous_value);
 
@@ -410,3 +422,12 @@ ContourLinesEditor::~ContourLinesEditor()
 	if(penDialog)
         delete penDialog;
 }
+
+template<class Widget>
+Widget* ContourLinesEditor::table_cellWidget(int i, int j) const {
+  Widget *w = dynamic_cast<Widget*>(table->cellWidget(i, j));
+  if (!w) {
+    throw std::logic_error("Unexpected widget type in ContourLinesEditor.");
+  }
+  return w;
+}
diff --git a/Code/Mantid/MantidPlot/src/ContourLinesEditor.h b/Code/Mantid/MantidPlot/src/ContourLinesEditor.h
index 8efeab3ac9ca00cf4c8d4644bb321ac8f06b3076..231d47484f3932068c1a86543af75eac6023a445 100644
--- a/Code/Mantid/MantidPlot/src/ContourLinesEditor.h
+++ b/Code/Mantid/MantidPlot/src/ContourLinesEditor.h
@@ -78,6 +78,8 @@ protected slots:
 
 private:
 	void updatePenColumn();
+  template<class Widget>
+  Widget* table_cellWidget(int i, int j) const;
 
 	//! Table displaying the values ranges in the first column and their corresponding pens in the second column
 	QTableWidget *table;
diff --git a/Code/Mantid/MantidPlot/src/CurveRangeDialog.cpp b/Code/Mantid/MantidPlot/src/CurveRangeDialog.cpp
index 9240e1ca45ac37014ef33eac950acf3d8d1c34b6..8a2b2e5f1a1d31063bdbb24b0327a93e2c9474e4 100644
--- a/Code/Mantid/MantidPlot/src/CurveRangeDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/CurveRangeDialog.cpp
@@ -39,43 +39,43 @@
 #include <QSpinBox>
 
 CurveRangeDialog::CurveRangeDialog(QWidget* parent, Qt::WFlags fl )
-    : QDialog( parent, fl )
+  : QDialog( parent, fl ), d_curve(NULL), d_graph(NULL)
 {
-	setWindowTitle(tr("MantidPlot - Plot range"));
+    setWindowTitle(tr("MantidPlot - Plot range"));
     setName( "CurveRangeDialog" );
 
     QGroupBox *gb1 = new QGroupBox();
     QGridLayout *gl1 = new QGridLayout(gb1);
-	gl1->addWidget(new QLabel(tr("Data set: ")), 0, 0);
+    gl1->addWidget(new QLabel(tr("Data set: ")), 0, 0);
 
-	boxName = new QLabel();
-	gl1->addWidget(boxName, 0, 1);
+    boxName = new QLabel();
+    gl1->addWidget(boxName, 0, 1);
 
-	gl1->addWidget(new QLabel(tr("From row number")), 1, 0);
-	boxStart = new QSpinBox();
-	boxStart->setMinValue(1);
-	gl1->addWidget(boxStart, 1, 1);
+    gl1->addWidget(new QLabel(tr("From row number")), 1, 0);
+    boxStart = new QSpinBox();
+    boxStart->setMinValue(1);
+    gl1->addWidget(boxStart, 1, 1);
 
-	gl1->addWidget(new QLabel(tr("To row number")), 2, 0);
-	boxEnd = new QSpinBox();
-	boxEnd->setMinValue(1);
+    gl1->addWidget(new QLabel(tr("To row number")), 2, 0);
+    boxEnd = new QSpinBox();
+    boxEnd->setMinValue(1);
     gl1->addWidget(boxEnd, 2, 1);
     gl1->setRowStretch(3, 1);
 
-	buttonOK = new QPushButton(tr( "&OK" ));
+    buttonOK = new QPushButton(tr( "&OK" ));
     buttonOK->setDefault( true );
     buttonCancel = new QPushButton(tr( "&Close" ));
 
     QHBoxLayout *hl = new QHBoxLayout();
-	hl->addStretch();
- 	hl->addWidget(buttonOK);
-	hl->addWidget(buttonCancel);
+    hl->addStretch();
+    hl->addWidget(buttonOK);
+    hl->addWidget(buttonCancel);
 
     QVBoxLayout *vb = new QVBoxLayout(this);
     vb->addWidget(gb1);
     vb->addLayout(hl);
 
-	connect( buttonOK, SIGNAL( clicked() ), this, SLOT( accept() ) );
+    connect( buttonOK, SIGNAL( clicked() ), this, SLOT( accept() ) );
     connect( buttonCancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
 }
 
diff --git a/Code/Mantid/MantidPlot/src/CurvesDialog.cpp b/Code/Mantid/MantidPlot/src/CurvesDialog.cpp
index 8a9c171945776ea4a72d9f981f8a335c81e2001f..da5ec3162161ff93402f5388d7b9be53758798b0 100644
--- a/Code/Mantid/MantidPlot/src/CurvesDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/CurvesDialog.cpp
@@ -56,6 +56,9 @@ CurvesDialog::CurvesDialog( ApplicationWindow* app, Graph* g, Qt::WFlags fl )
     d_app(app),
     d_graph(g)
 {
+  if (!app) {
+    throw std::logic_error("Null ApplicationWindow pointer is passed to CurvesDialog.");
+  }
   setName( "CurvesDialog" );
   setWindowTitle( tr( "MantidPlot - Add/Remove curves" ) );
   setSizeGripEnabled(true);
@@ -197,7 +200,7 @@ void CurvesDialog::showCurveBtn(int)
   }
 
   PlotCurve *c = dynamic_cast<PlotCurve *>(it);
-  if (c->type() == Graph::Function)
+  if (c && c->type() == Graph::Function)
   {
     btnEditFunction->setEnabled(true);
     btnAssociations->setEnabled(false);
@@ -208,7 +211,7 @@ void CurvesDialog::showCurveBtn(int)
   btnAssociations->setEnabled(true);
 
   btnRange->setEnabled(true);
-  if (c->type() == Graph::ErrorBars)
+  if (c && c->type() == Graph::ErrorBars)
     btnRange->setEnabled(false);
 }
 
@@ -218,11 +221,8 @@ void CurvesDialog::showCurveRangeDialog()
   if (curve < 0)
     curve = 0;
 
-  if (d_app)
-  {
-    d_app->showCurveRangeDialog(d_graph, curve);
-    updateCurveRange();
-  }
+  d_app->showCurveRangeDialog(d_graph, curve);
+  updateCurveRange();
 }
 
 void CurvesDialog::showPlotAssociations()
@@ -233,8 +233,7 @@ void CurvesDialog::showPlotAssociations()
 
   close();
 
-  if (d_app)
-    d_app->showPlotAssociations(curve);
+  d_app->showPlotAssociations(curve);
 }
 
 void CurvesDialog::showFunctionDialog()
@@ -242,8 +241,7 @@ void CurvesDialog::showFunctionDialog()
   int currentRow = contents->currentRow();
   close();
 
-  if (d_app)
-    d_app->showFunctionDialog(d_graph, currentRow);
+  d_app->showFunctionDialog(d_graph, currentRow);
 }
 
 QSize CurvesDialog::sizeHint() const
@@ -284,40 +282,38 @@ void CurvesDialog::contextMenuEvent(QContextMenuEvent *e)
 
 void CurvesDialog::init()
 {
-  if (d_app){
-    bool currentFolderOnly = d_app->d_show_current_folder;
-    boxShowCurrentFolder->setChecked(currentFolderOnly);
-    showCurrentFolder(currentFolderOnly);
-
-    QStringList matrices = d_app->matrixNames();
-    if (!matrices.isEmpty ()){
-      boxMatrixStyle->show();
-      available->addItems(matrices);
-    }
+  bool currentFolderOnly = d_app->d_show_current_folder;
+  boxShowCurrentFolder->setChecked(currentFolderOnly);
+  showCurrentFolder(currentFolderOnly);
 
-    int style = d_app->defaultCurveStyle;
-    if (style == Graph::Line)
-      boxStyle->setCurrentItem(0);
-    else if (style == Graph::Scatter)
-      boxStyle->setCurrentItem(1);
-    else if (style == Graph::LineSymbols)
-      boxStyle->setCurrentItem(2);
-    else if (style == Graph::VerticalDropLines)
-      boxStyle->setCurrentItem(3);
-    else if (style == Graph::Spline)
-      boxStyle->setCurrentItem(4);
-    else if (style == Graph::VerticalSteps)
-      boxStyle->setCurrentItem(5);
-    else if (style == Graph::HorizontalSteps)
-      boxStyle->setCurrentItem(6);
-    else if (style == Graph::Area)
-      boxStyle->setCurrentItem(7);
-    else if (style == Graph::VerticalBars)
-      boxStyle->setCurrentItem(8);
-    else if (style == Graph::HorizontalBars)
-      boxStyle->setCurrentItem(9);
+  QStringList matrices = d_app->matrixNames();
+  if (!matrices.isEmpty ()){
+    boxMatrixStyle->show();
+    available->addItems(matrices);
   }
 
+  int style = d_app->defaultCurveStyle;
+  if (style == Graph::Line)
+    boxStyle->setCurrentItem(0);
+  else if (style == Graph::Scatter)
+    boxStyle->setCurrentItem(1);
+  else if (style == Graph::LineSymbols)
+    boxStyle->setCurrentItem(2);
+  else if (style == Graph::VerticalDropLines)
+    boxStyle->setCurrentItem(3);
+  else if (style == Graph::Spline)
+    boxStyle->setCurrentItem(4);
+  else if (style == Graph::VerticalSteps)
+    boxStyle->setCurrentItem(5);
+  else if (style == Graph::HorizontalSteps)
+    boxStyle->setCurrentItem(6);
+  else if (style == Graph::Area)
+    boxStyle->setCurrentItem(7);
+  else if (style == Graph::VerticalBars)
+    boxStyle->setCurrentItem(8);
+  else if (style == Graph::HorizontalBars)
+    boxStyle->setCurrentItem(9);
+
   QList<MdiSubWindow *> wList = d_app->windowsList();
   foreach(MdiSubWindow* w, wList)
   {
@@ -377,9 +373,6 @@ void CurvesDialog::addCurves()
 
 bool CurvesDialog::addCurve(const QString& name)
 {
-  if (!d_app)
-    return false;
-
   QStringList matrices = d_app->matrixNames();
   if (matrices.contains(name)){
     Matrix *m = d_app->matrix(name);
@@ -530,9 +523,11 @@ void CurvesDialog::showCurveRange(bool on )
       if (!it)
         continue;
 
-      if (it->rtti() == QwtPlotItem::Rtti_PlotCurve && (dynamic_cast<PlotCurve *>(it))->type() != Graph::Function){
-        DataCurve *c = dynamic_cast<DataCurve *>(it);
-        lst << c->title().text() + "[" + QString::number(c->startRow()+1) + ":" + QString::number(c->endRow()+1) + "]";
+      auto plotCurve = dynamic_cast<PlotCurve *>(it);
+      if (plotCurve && plotCurve->type() != Graph::Function){
+        if (DataCurve *c = dynamic_cast<DataCurve *>(it)) {
+          lst << c->title().text() + "[" + QString::number(c->startRow()+1) + ":" + QString::number(c->endRow()+1) + "]";
+        }
       } else
         lst << it->title().text();
     }
@@ -552,8 +547,6 @@ void CurvesDialog::updateCurveRange()
 
 void CurvesDialog::showCurrentFolder(bool currentFolder)
 {
-  if (!d_app)
-    return;
 
   d_app->d_show_current_folder = currentFolder;
   available->clear();
@@ -566,10 +559,11 @@ void CurvesDialog::showCurrentFolder(bool currentFolder)
         if (!w->inherits("Table"))
           continue;
 
-        Table *t = dynamic_cast<Table *>(w);
-        for (int i=0; i < t->numCols(); i++){
-          if(t->colPlotDesignation(i) == Table::Y)
-            columns << QString(t->objectName()) + "_" + t->colLabel(i);
+        if (Table *t = dynamic_cast<Table *>(w)) {
+          for (int i=0; i < t->numCols(); i++){
+            if(t->colPlotDesignation(i) == Table::Y)
+              columns << QString(t->objectName()) + "_" + t->colLabel(i);
+          }
         }
       }
       available->addItems(columns);
@@ -581,18 +575,15 @@ void CurvesDialog::showCurrentFolder(bool currentFolder)
 
 void CurvesDialog::closeEvent(QCloseEvent* e)
 {
-  if (d_app)
+  d_app->d_add_curves_dialog_size = this->size();
+  // Need to reenable close-on-empty behaviour so
+  // that deleting workspaces causes the empty graphs to
+  // disappear
+  QList<MdiSubWindow *> wList = d_app->windowsList();
+  foreach(MdiSubWindow* w, wList)
   {
-    d_app->d_add_curves_dialog_size = this->size();
-    // Need to reenable close-on-empty behaviour so
-    // that deleting workspaces causes the empty graphs to
-    // disappear
-    QList<MdiSubWindow *> wList = d_app->windowsList();
-    foreach(MdiSubWindow* w, wList)
-    {
-      MultiLayer* ml = dynamic_cast<MultiLayer*>(w);
-      if( ml ) ml->setCloseOnEmpty(true);
-    }
+    MultiLayer* ml = dynamic_cast<MultiLayer*>(w);
+    if( ml ) ml->setCloseOnEmpty(true);
   }
 
   e->accept();
diff --git a/Code/Mantid/MantidPlot/src/CustomActionDialog.cpp b/Code/Mantid/MantidPlot/src/CustomActionDialog.cpp
index a240c83753e55e6a642c722d126152e85f9e594b..e6867cfc82653909435c530d2fdc298a43f8c94b 100644
--- a/Code/Mantid/MantidPlot/src/CustomActionDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/CustomActionDialog.cpp
@@ -195,7 +195,12 @@ void CustomActionDialog::updateDisplayList()
 {
 	itemsList->clear();
 
-    QList<QAction *> actionsList = (dynamic_cast<ApplicationWindow *>(parentWidget()))->customActionsList();
+  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
+  if (!app) {
+    throw std::logic_error("Parent of CustomActionDialog is not ApplicationWindow as expected.");
+  }
+
+  QList<QAction *> actionsList = app->customActionsList();
 	foreach(QAction *action, actionsList){//add existing actions to the list widget
 	    QString text = action->text();
         QString shortcut = action->shortcut().toString();
@@ -263,7 +268,10 @@ bool CustomActionDialog::validUserInput()
 		folder = folderBox->text();
 	}
 
-	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
+  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
+  if (!app) {
+    throw std::logic_error("Parent of CustomActionDialog is not ApplicationWindow as expected.");
+  }
 	QList<QAction *>actions = app->customActionsList();
 
 	if (textBox->text().isEmpty()){
@@ -370,7 +378,10 @@ void CustomActionDialog::removeAction()
 	if (!action)
 		return;
 	
-    ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parentWidget());
+    ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
+    if (!app) {
+      throw std::logic_error("Parent of CustomActionDialog is not ApplicationWindow as expected.");
+    }
     QFile f(app->customActionsDirPath + "/" + action->text() + ".qca");
     f.remove();
 	
@@ -394,7 +405,10 @@ void CustomActionDialog::saveCurrentAction()
 	if ((toolBarBtn->isChecked() && w->objectName() != toolBarBox->currentText()) || 
 		(menuBtn->isChecked() && w->objectName() != menuBox->currentText())){
 		//relocate action: create a new one and delete the old
-		ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
+    ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
+    if (!app) {
+      throw std::logic_error("Parent of CustomActionDialog is not ApplicationWindow as expected.");
+    }
 		QAction *newAction = new QAction(app);
 		customizeAction(newAction);			
 		if (toolBarBtn->isChecked()){
@@ -427,6 +441,9 @@ void CustomActionDialog::saveAction(QAction *action)
         return;
 
     ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
+    if (!app) {
+      throw std::logic_error("Parent of CustomActionDialog is not ApplicationWindow as expected.");
+    }
     QString fileName = app->customActionsDirPath + "/" + action->text() + ".qca";
     QFile f(fileName);
 	if (!f.open( QIODevice::WriteOnly)){
diff --git a/Code/Mantid/MantidPlot/src/DataPickerTool.cpp b/Code/Mantid/MantidPlot/src/DataPickerTool.cpp
index aaba100a20cd9dd5a3e5539a41e4e0ec8bb2d701..e2879f39c5c89b0c56d86eae35ab6d019afd8c64 100644
--- a/Code/Mantid/MantidPlot/src/DataPickerTool.cpp
+++ b/Code/Mantid/MantidPlot/src/DataPickerTool.cpp
@@ -115,11 +115,13 @@ void DataPickerTool::setSelection(QwtPlotCurve *curve, int point_index)
   }
 
   setAxis(d_selected_curve->xAxis(), d_selected_curve->yAxis());
+  auto plotCurve = dynamic_cast<PlotCurve *>(d_selected_curve);
+  auto dataCurve = dynamic_cast<DataCurve*>(d_selected_curve);
 
   d_restricted_move_pos = QPoint(plot()->transform(xAxis(), d_selected_curve->x(d_selected_point)),
     plot()->transform(yAxis(), d_selected_curve->y(d_selected_point)));
 
-  if (dynamic_cast<PlotCurve *>(d_selected_curve)->type() == Graph::Function) 
+  if (plotCurve && plotCurve->type() == Graph::Function) 
   {
     QLocale locale = d_app->locale();
     emit statusText(QString("%1[%2]: x=%3; y=%4")
@@ -128,12 +130,12 @@ void DataPickerTool::setSelection(QwtPlotCurve *curve, int point_index)
       .arg(locale.toString(d_selected_curve->x(d_selected_point), 'G', d_app->d_decimal_digits))
       .arg(locale.toString(d_selected_curve->y(d_selected_point), 'G', d_app->d_decimal_digits)));
   }
-  else if (dynamic_cast<DataCurve*>(d_selected_curve))
+  else if (dataCurve)
   {
-    int row = dynamic_cast<DataCurve*>(d_selected_curve)->tableRow(d_selected_point);
+    int row = dataCurve->tableRow(d_selected_point);
 
-    Table *t = dynamic_cast<DataCurve*>(d_selected_curve)->table();
-    int xCol = t->colIndex(dynamic_cast<DataCurve*>(d_selected_curve)->xColumnName());
+    Table *t = dataCurve->table();
+    int xCol = t->colIndex(dataCurve->xColumnName());
     int yCol = t->colIndex(d_selected_curve->title().text());
 
     emit statusText(QString("%1[%2]: x=%3; y=%4")
@@ -164,14 +166,17 @@ bool DataPickerTool::eventFilter(QObject *obj, QEvent *event)
     event->accept();
     return true;
 
-  case QEvent::MouseMove:
-    if ( dynamic_cast<QMouseEvent *>(event)->modifiers() == Qt::ControlModifier )
-      d_move_mode = Vertical;
-    else if ( dynamic_cast<QMouseEvent *>(event)->modifiers() == Qt::AltModifier )
-      d_move_mode = Horizontal;
-    else
-      d_move_mode = Free;
-    break;
+  case QEvent::MouseMove: 
+    if (auto mouseEvent = dynamic_cast<QMouseEvent *>(event))
+    {
+      if ( mouseEvent->modifiers() == Qt::ControlModifier )
+        d_move_mode = Vertical;
+      else if ( mouseEvent->modifiers() == Qt::AltModifier )
+        d_move_mode = Horizontal;
+      else
+        d_move_mode = Free;
+      break;
+    }
 
   default:
     break;
diff --git a/Code/Mantid/MantidPlot/src/DataSetDialog.h b/Code/Mantid/MantidPlot/src/DataSetDialog.h
index 38e5413742dcee15e8851bc9951b1e2b4ab62c93..ba1b28d8a5c6c89cb8f03e812b88aef0529aa2c1 100644
--- a/Code/Mantid/MantidPlot/src/DataSetDialog.h
+++ b/Code/Mantid/MantidPlot/src/DataSetDialog.h
@@ -62,13 +62,12 @@ private:
   ApplicationWindow* d_app;
   Graph *d_graph;
   ApplicationWindow::Analysis d_operation;
-	QString windowTitle;
+  QString windowTitle;
 
-    QPushButton* buttonOk;
-	QPushButton* buttonCancel;
-    QGroupBox* groupBox1;
-    QCheckBox* boxShowFormula;
-	QComboBox* boxName;
+  QPushButton* buttonOk;
+  QPushButton* buttonCancel;
+  QGroupBox* groupBox1;
+  QComboBox* boxName;
 };
 
 #endif
diff --git a/Code/Mantid/MantidPlot/src/Differentiation.cpp b/Code/Mantid/MantidPlot/src/Differentiation.cpp
index aa9d5f3dafe904b56f44b8918dac79ca207b2f7f..09161f5cf24a1c4388b9a0969b03b3ab195d32c0 100644
--- a/Code/Mantid/MantidPlot/src/Differentiation.cpp
+++ b/Code/Mantid/MantidPlot/src/Differentiation.cpp
@@ -65,39 +65,48 @@ void Differentiation::init()
     d_min_points = 4;
 }
 
-void Differentiation::output()
-{
-    double *result = new double[d_n-1];
-	for (int i = 1; i < d_n-1; i++)
-		result[i]=0.5*((d_y[i+1]-d_y[i])/(d_x[i+1]-d_x[i]) + (d_y[i]-d_y[i-1])/(d_x[i]-d_x[i-1]));
+void Differentiation::output() {
+  std::vector<double> result(d_n - 1);
+  for (int i = 1; i < d_n - 1; i++)
+    result[i] = 0.5 * ((d_y[i + 1] - d_y[i]) / (d_x[i + 1] - d_x[i]) +
+                       (d_y[i] - d_y[i - 1]) / (d_x[i] - d_x[i - 1]));
 
-    ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
-    QLocale locale = app->locale();
-    QString tableName = app->generateUniqueName(QString(objectName()));
-    QString dataSet;
-	if (d_curve)
-		dataSet = d_curve->title().text();
-	else
-		dataSet = d_y_col_name;
+  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
+  if (!app) {
+    throw std::logic_error(
+        "Parent of Differentiation is not ApplicationWindow as expected.");
+  }
+  QLocale locale = app->locale();
+  QString tableName = app->generateUniqueName(QString(objectName()));
+  QString dataSet;
+  if (d_curve)
+    dataSet = d_curve->title().text();
+  else
+    dataSet = d_y_col_name;
 
-    d_result_table = app->newHiddenTable(tableName, tr("Derivative") + " " + tr("of","Derivative of")  + " " + dataSet, d_n-2, 2);
-	for (int i = 1; i < d_n-1; i++) {
-		d_result_table->setText(i-1, 0, locale.toString(d_x[i], 'g', app->d_decimal_digits));
-		d_result_table->setText(i-1, 1, locale.toString(result[i], 'g', app->d_decimal_digits));
-	}
-    delete[] result;
+  d_result_table = app->newHiddenTable(
+      tableName,
+      tr("Derivative") + " " + tr("of", "Derivative of") + " " + dataSet,
+      d_n - 2, 2);
+  for (int i = 1; i < d_n - 1; i++) {
+    d_result_table->setText(
+        i - 1, 0, locale.toString(d_x[i], 'g', app->d_decimal_digits));
+    d_result_table->setText(
+        i - 1, 1, locale.toString(result[i], 'g', app->d_decimal_digits));
+  }
 
-	if (d_graphics_display){
-		if (!d_output_graph)
-			d_output_graph = createOutputGraph()->activeGraph();
+  if (d_graphics_display) {
+    if (!d_output_graph)
+      d_output_graph = createOutputGraph()->activeGraph();
 
-    	d_output_graph->insertCurve(d_result_table, tableName + "_2", 0);
-    	QString legend = "\\l(1)" + tr("Derivative") + " " + tr("of","Derivative of") + " " + dataSet;
-    	LegendWidget *l = d_output_graph->legend();
-		if (l){
-    		l->setText(legend);
-    		l->repaint();
-        } else
-            d_output_graph->newLegend(legend);
-	}
+    d_output_graph->insertCurve(d_result_table, tableName + "_2", 0);
+    QString legend = "\\l(1)" + tr("Derivative") + " " +
+                     tr("of", "Derivative of") + " " + dataSet;
+    LegendWidget *l = d_output_graph->legend();
+    if (l) {
+      l->setText(legend);
+      l->repaint();
+    } else
+      d_output_graph->newLegend(legend);
+  }
 }
diff --git a/Code/Mantid/MantidPlot/src/ErrDialog.cpp b/Code/Mantid/MantidPlot/src/ErrDialog.cpp
index ee5792769849074dbe309c9977e885cccf806086..de2a40b79a205079f0b3e85185c1bb5e0469a833 100644
--- a/Code/Mantid/MantidPlot/src/ErrDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/ErrDialog.cpp
@@ -183,8 +183,11 @@ void ErrDialog::setSrcTables(QList<MdiSubWindow *> tables)
 
 void ErrDialog::selectSrcTable(int tabnr)
 {
-  colNamesBox->clear();
-  colNamesBox->addItems((dynamic_cast<Table*>(srcTables.at(tabnr)))->colNames());
+  auto table = dynamic_cast<Table*>(srcTables.at(tabnr));
+  if (table) {
+    colNamesBox->clear();
+    colNamesBox->addItems(table->colNames());
+  }
 }
 
 void ErrDialog::add()
diff --git a/Code/Mantid/MantidPlot/src/ExpDecayDialog.cpp b/Code/Mantid/MantidPlot/src/ExpDecayDialog.cpp
index cd334774930596a9e2ad7d8cbcd8430a8b3a7c98..c63834d6443ac028105d5bf23bf16d300bb17142 100644
--- a/Code/Mantid/MantidPlot/src/ExpDecayDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/ExpDecayDialog.cpp
@@ -41,8 +41,11 @@
 #include <QLineEdit>
 #include <QComboBox>
 
-	ExpDecayDialog::ExpDecayDialog(int type, QWidget* parent, Qt::WFlags fl )
-: QDialog( parent, fl )
+ExpDecayDialog::ExpDecayDialog(int type, QWidget* parent, Qt::WFlags fl )
+  : QDialog( parent, fl ), fitter(NULL), graph(NULL),
+    buttonFit(NULL), buttonCancel(NULL), boxName(NULL), boxAmplitude(NULL),
+    boxFirst(NULL), boxSecond(NULL), boxThird(NULL), boxStart(NULL), boxYOffset(NULL),
+    thirdLabel(NULL), dampingLabel(NULL), boxColor(NULL)
 {
     setName( "ExpDecayDialog" );
 
diff --git a/Code/Mantid/MantidPlot/src/ExportDialog.cpp b/Code/Mantid/MantidPlot/src/ExportDialog.cpp
index 76c99f7df80dd4cae11733f176730619c8ab67cd..efa532d3a4757872af0deacc7322027007393b00 100644
--- a/Code/Mantid/MantidPlot/src/ExportDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/ExportDialog.cpp
@@ -42,7 +42,10 @@ ExportDialog::ExportDialog(const QString& tableName, QWidget* parent, Qt::WFlags
 	setWindowTitle( tr( "MantidPlot - Export ASCII" ) );
 	setSizeGripEnabled( true );
 
-	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent);
+  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent);
+  if (!app) {
+    throw std::logic_error("Parent of FFTDialog is not ApplicationWindow as expected.");
+  }
 
 	QGridLayout *gl1 = new QGridLayout();
   gl1->addWidget(new QLabel(tr("Export From")), 0, 0);
diff --git a/Code/Mantid/MantidPlot/src/FFT.cpp b/Code/Mantid/MantidPlot/src/FFT.cpp
index 2a09819df05de8d149ef5835abe9990c5e3f8130..369889b2b002078ccdda17e49de0496884c4a5f8 100644
--- a/Code/Mantid/MantidPlot/src/FFT.cpp
+++ b/Code/Mantid/MantidPlot/src/FFT.cpp
@@ -72,12 +72,12 @@ void FFT::init ()
 
 QString FFT::fftCurve()
 {
-    int i, i2;
+  int i, i2;
 	int n2 = d_n/2;
-	double *amp = new double[d_n];
-	double *result = new double[2*d_n];
+	std::vector<double> amp(d_n);
+	std::vector<double> result(2*d_n);
 
-	if(!amp || !result){
+	if(amp.empty() || result.empty()){
     QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
                         tr("Could not allocate memory, operation aborted!"));
         d_init_err = true;
@@ -98,14 +98,11 @@ QString FFT::fftCurve()
 			QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
                         tr("Could not allocate memory, operation aborted!"));
             d_init_err = true;
-            // Cleanup variables before returning
-            delete [] amp;
-            delete [] result;
 			return "";
 		}
 
 		gsl_fft_real_transform(d_y, 1, d_n, real,work);
-		gsl_fft_halfcomplex_unpack (d_y, result, 1, d_n);
+    gsl_fft_halfcomplex_unpack (d_y, result.data(), 1, d_n);
 
 		gsl_fft_real_wavetable_free(real);
 		gsl_fft_real_workspace_free(work);
@@ -113,7 +110,7 @@ QString FFT::fftCurve()
         d_explanation = tr("Inverse") + " " + tr("FFT") + " " + tr("of") + " " + d_curve->title().text();
 		text = tr("Time");
 
-		gsl_fft_real_unpack (d_y, result, 1, d_n);
+    gsl_fft_real_unpack (d_y, result.data(), 1, d_n);
 		gsl_fft_complex_wavetable *wavetable = gsl_fft_complex_wavetable_alloc (d_n);
 		gsl_fft_complex_workspace *workspace = gsl_fft_complex_workspace_alloc (d_n);
 
@@ -121,13 +118,10 @@ QString FFT::fftCurve()
 			QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
                         tr("Could not allocate memory, operation aborted!"));
             d_init_err = true;
-            // Cleanup local variables before returning
-            delete [] amp;
-            delete [] result;
 			return "";
 		}
 
-		gsl_fft_complex_inverse (result, 1, d_n, wavetable, workspace);
+		gsl_fft_complex_inverse (result.data(), 1, d_n, wavetable, workspace);
 		gsl_fft_complex_wavetable_free (wavetable);
 		gsl_fft_complex_workspace_free (workspace);
 	}
@@ -155,7 +149,11 @@ QString FFT::fftCurve()
 			aMax = a;
 	}
 
-	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
+  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
+  if (!app) {
+    throw std::logic_error("Parent of FFTDialog is not ApplicationWindow as expected.");
+  }
+
 	QLocale locale = app->locale();
 	int prec = app->d_decimal_digits;
 
@@ -171,9 +169,7 @@ QString FFT::fftCurve()
 			text += locale.toString(amp[i], 'g', prec)+"\t";
 		text += locale.toString(atan(result[i2+1]/result[i2]), 'g', prec)+"\n";
 	}
-	delete[] amp;
-	delete[] result;
-    return text;
+  return text;
 }
 
 QString FFT::fftTable()
@@ -234,6 +230,9 @@ QString FFT::fftTable()
 	}
 
     ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
+    if (!app) {
+      throw std::logic_error("Parent of FFTDialog is not ApplicationWindow as expected.");
+    }
     QLocale locale = app->locale();
 	int prec = app->d_decimal_digits;
 
@@ -268,6 +267,9 @@ void FFT::output()
 void FFT::output(const QString &text)
 {
     ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
+    if (!app) {
+      throw std::logic_error("Parent of FFT is not ApplicationWindow as expected.");
+    }
     QString tableName = app->generateUniqueName(QString(objectName()));
     d_result_table = app->newHiddenTable(tableName, d_explanation, d_n, 5, text);
 
diff --git a/Code/Mantid/MantidPlot/src/FFTDialog.cpp b/Code/Mantid/MantidPlot/src/FFTDialog.cpp
index e6453e17b295abed8ce016b5b28113ba64a95f78..7a6193e7d78ba8d5695719b5d2fa26fa5c97e335 100644
--- a/Code/Mantid/MantidPlot/src/FFTDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/FFTDialog.cpp
@@ -49,67 +49,70 @@
 #include <QApplication>
 
 FFTDialog::FFTDialog(int type, QWidget* parent, Qt::WFlags fl )
-: QDialog( parent, fl )
+  : QDialog( parent, fl ),
+    buttonOK(NULL), buttonCancel(NULL), forwardBtn(NULL), backwardBtn(NULL),
+    boxName(NULL), boxReal(NULL), boxImaginary(NULL),
+    boxSampling(NULL), boxNormalize(NULL), boxOrder(NULL)
 {
-	setWindowTitle(tr("MantidPlot - FFT Options"));
+    setWindowTitle(tr("MantidPlot - FFT Options"));
 
     d_matrix = 0;
-	d_table = 0;
-	graph = 0;
-	d_type = type;
+    d_table = 0;
+    graph = 0;
+    d_type = type;
 
-	forwardBtn = new QRadioButton(tr("&Forward"));
-	forwardBtn->setChecked( true );
-	backwardBtn = new QRadioButton(tr("&Inverse"));
+    forwardBtn = new QRadioButton(tr("&Forward"));
+    forwardBtn->setChecked( true );
+    backwardBtn = new QRadioButton(tr("&Inverse"));
 
-	QHBoxLayout *hbox1 = new QHBoxLayout();
+    QHBoxLayout *hbox1 = new QHBoxLayout();
     hbox1->addWidget(forwardBtn);
     hbox1->addWidget(backwardBtn);
 
-	QGroupBox *gb1 = new QGroupBox();
+    QGroupBox *gb1 = new QGroupBox();
     gb1->setLayout(hbox1);
 
-	QGridLayout *gl1 = new QGridLayout();
-	if (d_type == onGraph)
-	    gl1->addWidget(new QLabel(tr("Curve")), 0, 0);
-	else if (d_type == onTable)
-		gl1->addWidget(new QLabel(tr("Sampling")), 0, 0);
+    QGridLayout *gl1 = new QGridLayout();
+    if (d_type == onGraph)
+      gl1->addWidget(new QLabel(tr("Curve")), 0, 0);
+    else if (d_type == onTable)
+      gl1->addWidget(new QLabel(tr("Sampling")), 0, 0);
 
     if (d_type != onMatrix){
-        boxName = new QComboBox();
-        connect( boxName, SIGNAL( activated(const QString&) ), this, SLOT( activateCurve(const QString&) ) );
-        gl1->addWidget(boxName, 0, 1);
-        setFocusProxy(boxName);
+      boxName = new QComboBox();
+      connect( boxName, SIGNAL( activated(const QString&) ), this, SLOT( activateCurve(const QString&) ) );
+      gl1->addWidget(boxName, 0, 1);
+      setFocusProxy(boxName);
     }
 
     boxSampling = new QLineEdit();
-	if (d_type == onTable || d_type == onMatrix){
-		gl1->addWidget(new QLabel(tr("Real")), 1, 0);
-		boxReal = new QComboBox();
-		gl1->addWidget(boxReal, 1, 1);
-
-		gl1->addWidget(new QLabel(tr("Imaginary")), 2, 0);
-		boxImaginary = new QComboBox();
-		gl1->addWidget(boxImaginary, 2, 1);
-
-        if (d_type == onTable){
-            gl1->addWidget(new QLabel(tr("Sampling Interval")), 3, 0);
-            gl1->addWidget(boxSampling, 3, 1);
-        }
+    if (d_type == onTable || d_type == onMatrix){
+      gl1->addWidget(new QLabel(tr("Real")), 1, 0);
+      boxReal = new QComboBox();
+      gl1->addWidget(boxReal, 1, 1);
+
+      gl1->addWidget(new QLabel(tr("Imaginary")), 2, 0);
+      boxImaginary = new QComboBox();
+      gl1->addWidget(boxImaginary, 2, 1);
+
+      if (d_type == onTable){
+        gl1->addWidget(new QLabel(tr("Sampling Interval")), 3, 0);
+        gl1->addWidget(boxSampling, 3, 1);
+      }
     } else if (d_type == onGraph){
-        gl1->addWidget(new QLabel(tr("Sampling Interval")), 1, 0);
-		gl1->addWidget(boxSampling, 1, 1);
+      gl1->addWidget(new QLabel(tr("Sampling Interval")), 1, 0);
+      gl1->addWidget(boxSampling, 1, 1);
     }
 
- 	QGroupBox *gb2 = new QGroupBox();
+    QGroupBox *gb2 = new QGroupBox();
     gb2->setLayout(gl1);
 
-	boxNormalize = new QCheckBox(tr( "&Normalize Amplitude" ));
-	boxNormalize->setChecked(true);
+    boxNormalize = new QCheckBox(tr( "&Normalize Amplitude" ));
+    boxNormalize->setChecked(true);
 
     if (d_type != onMatrix){
-        boxOrder = new QCheckBox(tr( "&Shift Results" ));
-        boxOrder->setChecked(true);
+      boxOrder = new QCheckBox(tr( "&Shift Results" ));
+      boxOrder->setChecked(true);
     }
 
     QVBoxLayout *vbox1 = new QVBoxLayout();
@@ -117,14 +120,14 @@ FFTDialog::FFTDialog(int type, QWidget* parent, Qt::WFlags fl )
     vbox1->addWidget(gb2);
     vbox1->addWidget(boxNormalize);
     if (d_type != onMatrix)
-        vbox1->addWidget(boxOrder);
-	vbox1->addStretch();
+      vbox1->addWidget(boxOrder);
+    vbox1->addStretch();
 
     buttonOK = new QPushButton(tr("&OK"));
-	buttonOK->setDefault( true );
-	buttonCancel = new QPushButton(tr("&Close"));
+    buttonOK->setDefault( true );
+    buttonCancel = new QPushButton(tr("&Close"));
 
-	QVBoxLayout *vbox2 = new QVBoxLayout();
+    QVBoxLayout *vbox2 = new QVBoxLayout();
     vbox2->addWidget(buttonOK);
     vbox2->addWidget(buttonCancel);
     vbox2->addStretch();
@@ -133,9 +136,9 @@ FFTDialog::FFTDialog(int type, QWidget* parent, Qt::WFlags fl )
     hbox2->addLayout(vbox1);
     hbox2->addLayout(vbox2);
 
-	// signals and slots connections
-	connect( buttonOK, SIGNAL( clicked() ), this, SLOT( accept() ) );
-	connect( buttonCancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
+    // signals and slots connections
+    connect( buttonOK, SIGNAL( clicked() ), this, SLOT( accept() ) );
+    connect( buttonCancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
 }
 
 void FFTDialog::accept()
@@ -161,7 +164,10 @@ void FFTDialog::accept()
 	}
 
   ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
-    FFT *fft = NULL;
+  if (!app) {
+    throw std::logic_error("Parent of FFTDialog is not ApplicationWindow as expected.");
+  }
+  FFT *fft = NULL;
 	if (graph)
         fft = new FFT(app, graph, boxName->currentText());
 	else if (d_table){
@@ -170,14 +176,17 @@ void FFTDialog::accept()
 			boxReal->setFocus();
 			return;
 		}
-        fft = new FFT(app, d_table, boxReal->currentText(), boxImaginary->currentText());
+    fft = new FFT(app, d_table, boxReal->currentText(), boxImaginary->currentText());
 	}
+
+  if (fft) {
     fft->setInverseFFT(backwardBtn->isChecked());
     fft->setSampling(sampling);
     fft->normalizeAmplitudes(boxNormalize->isChecked());
     fft->shiftFrequencies(boxOrder->isChecked());
     fft->run();
     delete fft;
+  }
 	close();
 }
 
@@ -238,6 +247,9 @@ void FFTDialog::setTable(Table *t)
 void FFTDialog::setMatrix(Matrix *m)
 {
     ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
+    if (!app) {
+      throw std::logic_error("Parent of FFTDialog is not ApplicationWindow as expected.");
+    }
     QStringList lst = app->matrixNames();
     boxReal->addItems(lst);
     if (m){
@@ -251,6 +263,9 @@ void FFTDialog::setMatrix(Matrix *m)
 void FFTDialog::fftMatrix()
 {
     ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
+    if (!app) {
+      throw std::logic_error("Parent of FFTDialog is not ApplicationWindow as expected.");
+    }
     Matrix *mReal = app->matrix(boxReal->currentText());
     if (!mReal)
         return;
diff --git a/Code/Mantid/MantidPlot/src/Filter.cpp b/Code/Mantid/MantidPlot/src/Filter.cpp
index 56e6165a89814fdd5b324c2a8bf9e36e10d0c3a8..16d5c7c92f6d9bdb8cf9a52f8e9c98bb8b6fe475 100644
--- a/Code/Mantid/MantidPlot/src/Filter.cpp
+++ b/Code/Mantid/MantidPlot/src/Filter.cpp
@@ -59,13 +59,17 @@ Filter::Filter( ApplicationWindow *parent, Table *t, const QString& name)
 
 void Filter::init()
 {
+	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (!app) {
+    throw std::logic_error("Parent of qtiplot's Filter is not ApplicationWindow as expected.");
+  }
 	d_n = 0;
 	d_curveColorIndex = 1;
 	d_tolerance = 1e-4;
 	d_points = 100;
 	d_max_iterations = 1000;
 	d_curve = 0;
-	d_prec = dynamic_cast<ApplicationWindow *>(parent())->fit_output_precision;
+	d_prec = app->fit_output_precision;
 	d_init_err = false;
     d_sort_data = true;
     d_min_points = 2;
@@ -200,7 +204,11 @@ bool Filter::run()
 		return false;
 
 	if (d_n < 0){
-		QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
+	  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+    if (!app) {
+      throw std::logic_error("Parent of Filter is not ApplicationWindow as expected.");
+    }
+		QMessageBox::critical(app, tr("MantidPlot") + " - " + tr("Error"),
 				tr("You didn't specify a valid data set for this operation!"));
 		return false;
 	}
@@ -208,7 +216,11 @@ bool Filter::run()
 	QApplication::setOverrideCursor(Qt::WaitCursor);
 
     output();//data analysis and output
-    dynamic_cast<ApplicationWindow *>(parent())->updateLog(logInfo());
+	  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+    if (!app) {
+      throw std::logic_error("Parent of Filter is not ApplicationWindow as expected.");
+    }
+    app->updateLog(logInfo());
 
 	QApplication::restoreOverrideCursor();
     return true;
@@ -315,7 +327,10 @@ int Filter::curveRange(QwtPlotCurve *c, double start, double end, int *iStart, i
 
 QwtPlotCurve* Filter::addResultCurve(double *x, double *y)
 {
-    ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
+	  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+    if (!app) {
+      throw std::logic_error("Parent of Filter is not ApplicationWindow as expected.");
+    }
     QLocale locale = app->locale();
     const QString tableName = app->generateUniqueName(QString(objectName()));
 	QString dataSet;
@@ -358,7 +373,11 @@ void Filter::enableGraphicsDisplay(bool on, Graph *g)
 
 MultiLayer * Filter::createOutputGraph()
 {
-  MultiLayer *ml = dynamic_cast<ApplicationWindow *>(parent())->newGraph(objectName() + tr("Plot"));
+	  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+    if (!app) {
+      throw std::logic_error("Parent of Filter is not ApplicationWindow as expected.");
+    }
+    MultiLayer *ml = app->newGraph(objectName() + tr("Plot"));
    	d_output_graph = ml->activeGraph();
 	return ml;
 }
@@ -404,7 +423,11 @@ bool Filter::setDataFromTable(Table *t, const QString& xColName, const QString&
 	}
 
 	if (size < d_min_points){
-		QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
+	  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+    if (!app) {
+      throw std::logic_error("Parent of Filter is not ApplicationWindow as expected.");
+    }
+		QMessageBox::critical(app, tr("MantidPlot") + " - " + tr("Error"),
 				tr("You need at least %1 points in order to perform this operation!").arg(d_min_points));
         return false;
 	}
diff --git a/Code/Mantid/MantidPlot/src/FilterDialog.cpp b/Code/Mantid/MantidPlot/src/FilterDialog.cpp
index 1e16d247b5955fec9a51f950f9157c9d562713b1..0698f42d379b74989de70c8086ea95b7b3e0a216 100644
--- a/Code/Mantid/MantidPlot/src/FilterDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/FilterDialog.cpp
@@ -42,72 +42,73 @@
 #include <QComboBox>
 
 FilterDialog::FilterDialog(int type, QWidget* parent, Qt::WFlags fl )
-    : QDialog( parent, fl )
+  : QDialog( parent, fl ), graph(NULL), buttonFilter(NULL), buttonCancel(NULL),
+    boxName(NULL), boxOffset(NULL), boxStart(NULL), boxEnd(NULL), boxColor(NULL)
 {
-	setWindowTitle(tr("MantidPlot - Filter options"));
+    setWindowTitle(tr("MantidPlot - Filter options"));
     filter_type = type;
 
     setName( "FilterDialog" );
 
     QGroupBox *gb1 = new QGroupBox();
     QGridLayout *gl1 = new QGridLayout(gb1);
-	gl1->addWidget(new QLabel(tr("Filter curve: ")), 0, 0);
+    gl1->addWidget(new QLabel(tr("Filter curve: ")), 0, 0);
 
-	boxName = new QComboBox();
-	gl1->addWidget(boxName, 0, 1);
+    boxName = new QComboBox();
+    gl1->addWidget(boxName, 0, 1);
 
-	if (type <= FFTFilter::HighPass)
-		gl1->addWidget(new QLabel(tr("Frequency cutoff (Hz)")), 1, 0);
-	else
-		gl1->addWidget(new QLabel(tr("Low Frequency (Hz)")), 1, 0);
+    if (type <= FFTFilter::HighPass)
+      gl1->addWidget(new QLabel(tr("Frequency cutoff (Hz)")), 1, 0);
+    else
+      gl1->addWidget(new QLabel(tr("Low Frequency (Hz)")), 1, 0);
 
-	boxStart = new QLineEdit();
-	boxStart->setText(tr("0"));
-	gl1->addWidget(boxStart, 1, 1);
+    boxStart = new QLineEdit();
+    boxStart->setText(tr("0"));
+    gl1->addWidget(boxStart, 1, 1);
 
-	boxColor = new ColorBox();
-	boxColor->setColor(QColor(Qt::red));
-	if (type >= FFTFilter::BandPass)
-		{
-	    gl1->addWidget(new QLabel(tr("High Frequency (Hz)")), 2, 0);
+    boxColor = new ColorBox();
+    boxColor->setColor(QColor(Qt::red));
+    if (type >= FFTFilter::BandPass)
+    {
+        gl1->addWidget(new QLabel(tr("High Frequency (Hz)")), 2, 0);
 
-		boxEnd = new QLineEdit();
-		boxEnd->setText(tr("0"));
+        boxEnd = new QLineEdit();
+        boxEnd->setText(tr("0"));
         gl1->addWidget(boxEnd, 2, 1);
 
-		if (type == FFTFilter::BandPass)
-		    gl1->addWidget(new QLabel(tr("Add DC Offset")), 3, 0);
-		else
-		    gl1->addWidget(new QLabel(tr("Substract DC Offset")), 3, 0);
+        if (type == FFTFilter::BandPass)
+          gl1->addWidget(new QLabel(tr("Add DC Offset")), 3, 0);
+        else
+          gl1->addWidget(new QLabel(tr("Substract DC Offset")), 3, 0);
 
-		boxOffset = new QCheckBox();
-		gl1->addWidget(boxOffset, 3, 1);
+        boxOffset = new QCheckBox();
+        gl1->addWidget(boxOffset, 3, 1);
 
-		gl1->addWidget(new QLabel(tr("Color")), 4, 0);
-		gl1->addWidget(boxColor, 4, 1);
+        gl1->addWidget(new QLabel(tr("Color")), 4, 0);
+        gl1->addWidget(boxColor, 4, 1);
         gl1->setRowStretch(5, 1);
-		}
+    }
     else
-        {
+    {
         gl1->addWidget(new QLabel(tr("Color")), 2, 0);
-		gl1->addWidget(boxColor, 2, 1);
+        gl1->addWidget(boxColor, 2, 1);
         gl1->setRowStretch(3, 1);
-        }
+    }
 
-	buttonFilter = new QPushButton(tr( "&Filter" ));
+    buttonFilter = new QPushButton(tr( "&Filter" ));
     buttonFilter->setDefault( true );
     buttonCancel = new QPushButton(tr( "&Close" ));
 
     QVBoxLayout *vl = new QVBoxLayout();
- 	vl->addWidget(buttonFilter);
-	vl->addWidget(buttonCancel);
+    vl->addWidget(buttonFilter);
+    vl->addWidget(buttonCancel);
     vl->addStretch();
 
     QHBoxLayout *hb = new QHBoxLayout(this);
     hb->addWidget(gb1);
     hb->addLayout(vl);
 
-	connect( buttonFilter, SIGNAL( clicked() ), this, SLOT( filter() ) );
+    connect( buttonFilter, SIGNAL( clicked() ), this, SLOT( filter() ) );
     connect( buttonCancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
 }
 
diff --git a/Code/Mantid/MantidPlot/src/FindDialog.cpp b/Code/Mantid/MantidPlot/src/FindDialog.cpp
index 5132e9f6ef0a183ef16292152659f2a1d4ee930b..154f1cd14e6ecc88c266e9ec393add7d9a9761c2 100644
--- a/Code/Mantid/MantidPlot/src/FindDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/FindDialog.cpp
@@ -119,13 +119,19 @@ FindDialog::FindDialog( QWidget* parent, Qt::WFlags fl )
 
 void FindDialog::setStartPath()
 {
-	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
+	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (!app) {
+    throw std::logic_error("Parent of FindDialog is not ApplicationWindow as expected.");
+  }
 	labelStart->setText(app->currentFolder()->path());
 }
 
 void FindDialog::accept()
 {
-	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
+	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (!app) {
+    throw std::logic_error("Parent of FindDialog is not ApplicationWindow as expected.");
+  }
 	app->find(boxFind->currentText(), boxWindowNames->isChecked(), boxWindowLabels->isChecked(),
 			boxFolderNames->isChecked(), boxCaseSensitive->isChecked(), boxPartialMatch->isChecked(),
 			boxSubfolders->isChecked());
diff --git a/Code/Mantid/MantidPlot/src/Fit.cpp b/Code/Mantid/MantidPlot/src/Fit.cpp
index 1319d10708d38986fcb78dc88c31a4b21e4d6b67..838a53549418f3558603c0995a49de273629859e 100644
--- a/Code/Mantid/MantidPlot/src/Fit.cpp
+++ b/Code/Mantid/MantidPlot/src/Fit.cpp
@@ -60,6 +60,10 @@ Fit::Fit( ApplicationWindow *parent, Table *t, const QString& name)
 
 void Fit::init()
 {
+	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (!app) {
+    throw std::logic_error("Parent of qtiplot's Fit is not ApplicationWindow as expected.");
+  }
 	d_p = 0;
 	d_n = 0;
 	d_x = 0;
@@ -83,7 +87,7 @@ void Fit::init()
 	chi_2 = -1;
 	d_scale_errors = false;
 	d_sort_data = false;
-	d_prec = (dynamic_cast<ApplicationWindow *>(parent())->fit_output_precision);
+	d_prec = app->fit_output_precision;
 	d_param_table = 0;
 	d_cov_matrix = 0;
 	covar = 0;
@@ -213,6 +217,8 @@ bool Fit::setDataFromTable(Table *t, const QString& xColName, const QString& yCo
 
 void Fit::setDataCurve(int curve, double start, double end)
 {
+    if (!d_graph) return;
+
     if (d_n > 0)
 		delete[] d_w;
 
@@ -222,12 +228,12 @@ void Fit::setDataCurve(int curve, double start, double end)
     PlotCurve *plotCurve = dynamic_cast<PlotCurve *>(d_curve);
     DataCurve *dataCurve = dynamic_cast<DataCurve *>(d_curve);
     // if it is a DataCurve (coming from a Table)
-    if (d_graph && plotCurve && dataCurve && plotCurve->type() != Graph::Function)
+    if (plotCurve && dataCurve && plotCurve->type() != Graph::Function)
     {
-        QList<DataCurve *> lst = (dynamic_cast<DataCurve *>(d_curve))->errorBarsList();
+        QList<DataCurve *> lst = dataCurve->errorBarsList();
         foreach (DataCurve *c, lst){
             QwtErrorPlotCurve *er = dynamic_cast<QwtErrorPlotCurve *>(c);
-            if (!er->xErrors()){
+            if (er && !er->xErrors()){
                 d_weighting = Instrumental;
                 for (int i=0; i<d_n; i++)
                     d_w[i] = er->errorValue(i); //d_w are equal to the error bar values
@@ -381,6 +387,11 @@ QString Fit::legendInfo()
 
 bool Fit::setWeightingData(WeightingMethod w, const QString& colName)
 {
+	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (!app) {
+    throw std::logic_error("Parent of qtiplot's Fit is not ApplicationWindow as expected.");
+  }
+  auto dataCurve = dynamic_cast<DataCurve *>(d_curve);
   switch (w)
   {
   case NoWeighting: // No Weighting
@@ -416,15 +427,15 @@ bool Fit::setWeightingData(WeightingMethod w, const QString& colName)
       }
       // or if it's a Table curve
       if (!d_graph && d_table){
-        QMessageBox::critical(dynamic_cast<ApplicationWindow *>(this->parent()), tr("MantidPlot - Error"),
+        QMessageBox::critical(app, tr("MantidPlot - Error"),
           tr("You cannot use the instrumental weighting method."));
         return false;
       }
 
       bool error = true;
       QwtErrorPlotCurve *er = 0;
-      if ((dynamic_cast<PlotCurve *>(d_curve))->type() != Graph::Function){
-        QList<DataCurve *> lst = (dynamic_cast<DataCurve *>(d_curve))->errorBarsList();
+      if (dataCurve && dataCurve->type() != Graph::Function){
+        QList<DataCurve *> lst = dataCurve->errorBarsList();
         foreach (DataCurve *c, lst){
           er = dynamic_cast<QwtErrorPlotCurve *>(c);
           if (!er->xErrors()){
@@ -435,7 +446,7 @@ bool Fit::setWeightingData(WeightingMethod w, const QString& colName)
         }
       }
       if (error){
-        QMessageBox::critical(dynamic_cast<ApplicationWindow *>(this->parent()), tr("MantidPlot - Error"),
+        QMessageBox::critical(app, tr("MantidPlot - Error"),
           tr("The curve %1 has no associated Y error bars. You cannot use instrumental weighting method.").arg(d_curve->title().text()));
         return false;
       }
@@ -461,12 +472,12 @@ bool Fit::setWeightingData(WeightingMethod w, const QString& colName)
       if (colName.isEmpty())
         return false;
 
-      Table* t = (dynamic_cast<ApplicationWindow *>(this->parent()))->table(colName);
+      Table* t = app->table(colName);
       if (!t)
         return false;
 
       if (t->numRows() < d_n){
-        QMessageBox::critical(dynamic_cast<ApplicationWindow *>(this->parent()), tr("MantidPlot - Error"),
+        QMessageBox::critical(app, tr("MantidPlot - Error"),
           tr("The column %1 has less points than the fitted data set. Please choose another column!.").arg(colName));
         return false;
       }
@@ -487,6 +498,9 @@ bool Fit::setWeightingData(WeightingMethod w, const QString& colName)
 Table* Fit::parametersTable(const QString& tableName)
 {
 	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (!app) {
+    throw std::logic_error("Parent of qtiplot's Fit is not ApplicationWindow as expected.");
+  }
 	d_param_table = app->table(tableName);
 	if (!d_param_table || d_param_table->objectName() != tableName){
 		d_param_table = app->newTable(app->generateUniqueName(tableName, false), d_p, 3);
@@ -517,6 +531,9 @@ void Fit::writeParametersToTable(Table *t, bool append)
 	}
 
 	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (!app) {
+    throw std::logic_error("Parent of qtiplot's Fit is not ApplicationWindow as expected.");
+  }
 	QLocale locale = app->locale();
 
 	for (int i=0; i<d_p; i++){
@@ -533,6 +550,9 @@ void Fit::writeParametersToTable(Table *t, bool append)
 Matrix* Fit::covarianceMatrix(const QString& matrixName)
 {
 	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (!app) {
+    throw std::logic_error("Parent of qtiplot's Fit is not ApplicationWindow as expected.");
+  }
 	d_cov_matrix = app->matrix(matrixName);
 	if (!d_cov_matrix || d_cov_matrix->objectName() != matrixName)
 		d_cov_matrix = app->newMatrix(app->generateUniqueName(matrixName, false), d_p, d_p);
@@ -567,23 +587,28 @@ void Fit::fit()
 	if (!(d_graph || d_table) || d_init_err)
 		return;
 
+  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (!app) {
+    throw std::logic_error("Parent of qtiplot's Fit is not ApplicationWindow as expected.");
+  }
+
 	if (!d_n){
-		QMessageBox::critical(dynamic_cast<ApplicationWindow *>(this->parent()), tr("MantidPlot - Fit Error"),
+		QMessageBox::critical(app, tr("MantidPlot - Fit Error"),
 				tr("You didn't specify a valid data set for this fit operation. Operation aborted!"));
 		return;
 	}
 	if (!d_p){
-		QMessageBox::critical(dynamic_cast<ApplicationWindow *>(this->parent()), tr("MantidPlot - Fit Error"),
+		QMessageBox::critical(app, tr("MantidPlot - Fit Error"),
 				tr("There are no parameters specified for this fit operation. Operation aborted!"));
 		return;
 	}
 	if (d_p > d_n){
-			QMessageBox::critical(dynamic_cast<ApplicationWindow *>(this->parent()), tr("MantidPlot - Fit Error"),
+			QMessageBox::critical(app, tr("MantidPlot - Fit Error"),
   	    tr("You need at least %1 data points for this fit operation. Operation aborted!").arg(d_p));
   	    return;
   	}
 	if (d_formula.isEmpty()){
-		QMessageBox::critical(dynamic_cast<ApplicationWindow *>(this->parent()), tr("MantidPlot - Fit Error"),
+		QMessageBox::critical(app, tr("MantidPlot - Fit Error"),
 				tr("You must specify a valid fit function first. Operation aborted!"));
 		return;
 	}
@@ -630,7 +655,6 @@ void Fit::fit()
 
 	generateFitCurve();
 
-	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
 	if (app->writeFitResultsToLog)
 		app->updateLog(logFitInfo(iterations, status));
 
diff --git a/Code/Mantid/MantidPlot/src/FitDialog.cpp b/Code/Mantid/MantidPlot/src/FitDialog.cpp
index 701adfc599bcca9af0f282023c6a4f1078d60d6d..b2030f5eefa12517dea42829d8312c7053d86221 100644
--- a/Code/Mantid/MantidPlot/src/FitDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/FitDialog.cpp
@@ -100,6 +100,9 @@ FitDialog::FitDialog(Graph *g, QWidget* parent, Qt::WFlags fl )
 void FitDialog::initFitPage()
 {
     ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+    if (!app) {
+      throw std::logic_error("Parent of FitDialog is not ApplicationWindow as expected.");
+    }
 
     QGridLayout *gl1 = new QGridLayout();
     gl1->addWidget(new QLabel(tr("Curve")), 0, 0);
@@ -366,6 +369,9 @@ void FitDialog::initEditPage()
 void FitDialog::initAdvancedPage()
 {
 	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (!app) {
+    throw std::logic_error("Parent of FitDialog is not ApplicationWindow as expected.");
+  }
 
 	generatePointsBtn = new QRadioButton (tr("&Uniform X Function"));
 	generatePointsBtn->setChecked(app->generateUniformFitPoints);
@@ -471,15 +477,19 @@ void FitDialog::initAdvancedPage()
 void FitDialog::applyChanges()
 {
 	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (!app) {
+    throw std::logic_error("Parent of FitDialog is not ApplicationWindow as expected.");
+  }
 	int prec = boxPrecision->value();
 	app->fit_output_precision = prec;
-	if (d_current_fit)
-		d_current_fit->setOutputPrecision(prec);
+  if (!d_current_fit) return;
+
+	d_current_fit->setOutputPrecision(prec);
 	for (int i=0; i<boxParams->rowCount(); i++){
-    (dynamic_cast<DoubleSpinBox*>(boxParams->cellWidget(i, 2)))->setDecimals(prec);
+    boxParams_cellWidget<DoubleSpinBox>(i, 2)->setDecimals(prec);
 		if (d_current_fit->type() != Fit::BuiltIn){
-      (dynamic_cast<RangeLimitBox*>(boxParams->cellWidget(i, 1)))->setDecimals(prec);
-      (dynamic_cast<RangeLimitBox*>(boxParams->cellWidget(i, 3)))->setDecimals(prec);
+      boxParams_cellWidget<RangeLimitBox>(i, 1)->setDecimals(prec);
+      boxParams_cellWidget<RangeLimitBox>(i, 3)->setDecimals(prec);
 		}
 	}
 
@@ -614,14 +624,19 @@ void FitDialog::saveUserFunction()
 	if (lst.contains(name)){
 		int index = lst.findIndex(name);
     d_current_fit = dynamic_cast<NonLinearFit *>(d_user_functions[index]);
-		d_current_fit->setParametersList(boxParam->text().split(QRegExp("[,;]+[\\s]*"), QString::SkipEmptyParts));
-        d_current_fit->setFormula(formula);
-        d_current_fit->save(d_current_fit->fileName());
+    if (d_current_fit) {
+		  d_current_fit->setParametersList(boxParam->text().split(QRegExp("[,;]+[\\s]*"), QString::SkipEmptyParts));
+      d_current_fit->setFormula(formula);
+      d_current_fit->save(d_current_fit->fileName());
 
-		if (funcBox->currentItem()->text() == name)
-			showExpression(index);
+		  if (funcBox->currentItem()->text() == name)
+			  showExpression(index);
+    }
 	} else {
-			ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+		ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+    if (!app) {
+      throw std::logic_error("Parent of FitDialog is not ApplicationWindow as expected.");
+    }
 		QString filter = tr("MantidPlot fit model")+" (*.fit);;";
 		filter += tr("All files")+" (*.*)";
 		QString fn = MantidQt::API::FileDialogHandler::getSaveFileName(app, tr("MantidPlot") + " - " + tr("Save Fit Model As"),
@@ -917,6 +932,9 @@ void FitDialog::loadPlugins()
     //typedef char* (*fitFunc)();
 
 	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (!app) {
+    throw std::logic_error("Parent of FitDialog is not ApplicationWindow as expected.");
+  }
 	QString path = app->fitPluginsPath + "/";
 	QString modelsDirPath = app->fitModelsPath + "/";
 	QDir dir(path);
@@ -1015,6 +1033,9 @@ void FitDialog::addFunctionName()
 void FitDialog::accept()
 {
 	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (!app) {
+    throw std::logic_error("Parent of FitDialog is not ApplicationWindow as expected.");
+  }
 
 	QString curve = boxCurve->currentText();
 	QStringList curvesList = d_graph->curvesList();
@@ -1040,7 +1061,7 @@ void FitDialog::accept()
 	int n = 0, rows = boxParams->rowCount();
 	if (!boxParams->isColumnHidden(4)){
 		for (int i=0; i<rows; i++){//count the non-constant parameters
-            QCheckBox *cb = dynamic_cast<QCheckBox*>(boxParams->cellWidget(i, 4));
+      QCheckBox *cb = boxParams_cellWidget<QCheckBox>(i, 4);
 			if (!cb->isChecked())
 				n++;
 		}
@@ -1056,32 +1077,32 @@ void FitDialog::accept()
 		if (!boxParams->isColumnHidden(4)){
 			int j = 0;
 			for (int i=0; i<rows; i++){
-                QCheckBox *cb = dynamic_cast<QCheckBox*>(boxParams->cellWidget(i, 4));
+        QCheckBox *cb = boxParams_cellWidget<QCheckBox>(i, 4);
 				if (!cb->isChecked()){
-          paramsInit[j] = (dynamic_cast<DoubleSpinBox*>(boxParams->cellWidget(i, 2)))->value();
+          paramsInit[j] = boxParams_cellWidget<DoubleSpinBox>(i, 2)->value();
 					parser.DefineVar(boxParams->item(i, 0)->text().ascii(), &paramsInit[j]);
 					parameters << boxParams->item(i, 0)->text();
 
 					if (d_current_fit->type() != Fit::BuiltIn){
-            double left = (dynamic_cast<RangeLimitBox*>(boxParams->cellWidget(j, 1)))->value();
-            double right = (dynamic_cast<RangeLimitBox*>(boxParams->cellWidget(j, 3)))->value();
+            double left = boxParams_cellWidget<RangeLimitBox>(j, 1)->value();
+            double right = boxParams_cellWidget<RangeLimitBox>(j, 3)->value();
 						d_current_fit->setParameterRange(j, left, right);
 					}
 					j++;
 				} else {
-          double val = (dynamic_cast<DoubleSpinBox*>(boxParams->cellWidget(i, 2)))->value();
+          double val = boxParams_cellWidget<DoubleSpinBox>(i, 2)->value();
 					formula.replace(boxParams->item(i, 0)->text(), QString::number(val, 'e', app->fit_output_precision));
 				}
 			}
 		} else {
 			for (int i=0; i<n; i++) {
-        paramsInit[i] = (dynamic_cast<DoubleSpinBox*>(boxParams->cellWidget(i, 2)))->value();
+        paramsInit[i] = boxParams_cellWidget<DoubleSpinBox>(i, 2)->value();
 				parser.DefineVar(boxParams->item(i, 0)->text().ascii(), &paramsInit[i]);
 				parameters << boxParams->item(i, 0)->text();
 
 				if (d_current_fit->type() != Fit::BuiltIn){
-          double left = (dynamic_cast<RangeLimitBox*>(boxParams->cellWidget(i, 1)))->value();
-          double right = (dynamic_cast<RangeLimitBox*>(boxParams->cellWidget(i, 3)))->value();
+          double left = boxParams_cellWidget<RangeLimitBox>(i, 1)->value();
+          double right = boxParams_cellWidget<RangeLimitBox>(i, 3)->value();
 					d_current_fit->setParameterRange(i, left, right);
 				}
 			}
@@ -1127,13 +1148,13 @@ void FitDialog::accept()
 		if (!boxParams->isColumnHidden(4)){
 			int j = 0;
 			for (int i=0; i<rows; i++){
-                QCheckBox *cb = dynamic_cast<QCheckBox*>(boxParams->cellWidget(i, 4));
+                QCheckBox *cb = boxParams_cellWidget<QCheckBox>(i, 4);
 				if (!cb->isChecked())
-          (dynamic_cast<DoubleSpinBox*>(boxParams->cellWidget(i, 2)))->setValue(res[j++]);
+          boxParams_cellWidget<DoubleSpinBox>(i, 2)->setValue(res[j++]);
 			}
 		} else {
 			for (int i=0; i<rows; i++)
-        (dynamic_cast<DoubleSpinBox*>(boxParams->cellWidget(i, 2)))->setValue(res[i]);
+        boxParams_cellWidget<DoubleSpinBox>(i, 2)->setValue(res[i]);
 		}
 
 		if (globalParamTableBox->isChecked() && d_param_table)
@@ -1244,6 +1265,9 @@ void FitDialog::resetFunction()
 void FitDialog::initBuiltInFunctions()
 {
 	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (!app) {
+    throw std::logic_error("Parent of FitDialog is not ApplicationWindow as expected.");
+  }
 
 	d_built_in_functions << new SigmoidalFit(app, d_graph);
 	d_built_in_functions << new ExponentialFit(app, d_graph);
@@ -1276,10 +1300,13 @@ void FitDialog::initBuiltInFunctions()
 void FitDialog::setNumPeaks(int peaks)
 {
 	if (d_current_fit->objectName() == tr("Gauss") ||
-		d_current_fit->objectName() == tr("Lorentz"))
-    (dynamic_cast<MultiPeakFit *>(d_current_fit))->setNumPeaks(peaks);
-	else if (d_current_fit->objectName() == tr("Polynomial"))
-    (dynamic_cast<PolynomialFit *>(d_current_fit))->setOrder(peaks);
+		d_current_fit->objectName() == tr("Lorentz")) {
+    if (auto fit = dynamic_cast<MultiPeakFit *>(d_current_fit))
+      fit->setNumPeaks(peaks);
+  } else if (d_current_fit->objectName() == tr("Polynomial")) {
+    if (auto fit = dynamic_cast<PolynomialFit *>(d_current_fit))
+      fit->setOrder(peaks);
+  }
 
 	int index = funcBox->currentRow();
 	d_built_in_functions[index] = d_current_fit;
@@ -1298,6 +1325,9 @@ void FitDialog::loadUserFunctions()
 {
     d_user_functions.clear();
   ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (!app) {
+    throw std::logic_error("Parent of FitDialog is not ApplicationWindow as expected.");
+  }
 	QString path = app->fitModelsPath + "/";
 	QDir dir(path);
 	QStringList lst = dir.entryList(QDir::Files|QDir::NoSymLinks, QDir::Name);
@@ -1353,13 +1383,16 @@ void FitDialog::saveInitialGuesses()
 
 	int rows = boxParams->rowCount();
     for (int i=0; i<rows; i++)
-        d_current_fit->setInitialGuess(i, (dynamic_cast<DoubleSpinBox*>(boxParams->cellWidget(i, 2)))->value());
+        d_current_fit->setInitialGuess(i, boxParams_cellWidget<DoubleSpinBox>(i, 2)->value());
 
     QString fileName = d_current_fit->fileName();
     if (!fileName.isEmpty())
         d_current_fit->save(fileName);
     else {
-      ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+    ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+    if (!app) {
+      throw std::logic_error("Parent of FitDialog is not ApplicationWindow as expected.");
+    }
 		QString filter = tr("MantidPlot fit model") + " (*.fit);;";
 		filter += tr("All files") + " (*.*)";
 		QString fn = MantidQt::API::FileDialogHandler::getSaveFileName(app, tr("MantidPlot") + " - " + tr("Save Fit Model As"),
@@ -1408,7 +1441,7 @@ void FitDialog::updatePreview()
     int p = boxParams->rowCount();
     QVarLengthArray<double> parameters(p);//double parameters[p];
     for (int i=0; i<p; i++)
-        parameters[i] = (dynamic_cast<DoubleSpinBox*>(boxParams->cellWidget(i, 2)))->value();
+        parameters[i] = boxParams_cellWidget<DoubleSpinBox>(i, 2)->value();
     if (d_current_fit->type() == Fit::BuiltIn)
         modifyGuesses(parameters.data());//modifyGuesses(parameters);
 
@@ -1461,3 +1494,13 @@ QString FitDialog::parseFormula(const QString& s)
 	}
 	return formula;
 }
+
+template<class Widget>
+Widget* FitDialog::boxParams_cellWidget(int i, int j) const {
+  Widget *w = dynamic_cast<Widget*>(boxParams->cellWidget(i, j));
+  if (!w) {
+    throw std::logic_error("Unexpected widget type in FitDialog.");
+  }
+  return w;
+}
+
diff --git a/Code/Mantid/MantidPlot/src/FitDialog.h b/Code/Mantid/MantidPlot/src/FitDialog.h
index d8d3838e1bfc14f7a653dfba2fe826cadd4fe062..813af36d155a71038aa3e30d36cdd4520563556b 100644
--- a/Code/Mantid/MantidPlot/src/FitDialog.h
+++ b/Code/Mantid/MantidPlot/src/FitDialog.h
@@ -115,6 +115,8 @@ private:
 	QStringList userFunctionNames();
 	QStringList plugInNames();
 	QString parseFormula(const QString& s);
+  template<class Widget>
+  Widget* boxParams_cellWidget(int i, int j) const ;
 
     Fit *d_current_fit;
 	Graph *d_graph;
diff --git a/Code/Mantid/MantidPlot/src/FunctionDialog.h b/Code/Mantid/MantidPlot/src/FunctionDialog.h
index 044a77a85e2b4674338f3729ae534ea08442adfb..bbc127c6d18dba0eaabdbba5bb7d220b5323f544 100644
--- a/Code/Mantid/MantidPlot/src/FunctionDialog.h
+++ b/Code/Mantid/MantidPlot/src/FunctionDialog.h
@@ -55,7 +55,6 @@ protected:
     QComboBox* boxPolarRadius;
     QComboBox* boxPolarTheta;
     QComboBox* boxType;
-    QLabel* textFunction;
     QLineEdit* boxFrom;
     QLineEdit* boxTo;
 	QLineEdit* boxParameter;
diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp
index bc2f85db81f72a10036fb8b91c2c24966108e8ad..685d07e5f7236f808192e6e309a5708a3421c0cc 100644
--- a/Code/Mantid/MantidPlot/src/Graph.cpp
+++ b/Code/Mantid/MantidPlot/src/Graph.cpp
@@ -985,8 +985,9 @@ void Graph::updateSecondaryAxis(int axis)
 
   ScaleEngine *sc_engine = dynamic_cast<ScaleEngine *>(d_plot->axisScaleEngine(axis));
   if (sc_engine) {
-    ScaleEngine *a_engine = dynamic_cast<ScaleEngine *>(d_plot->axisScaleEngine(a));
-    sc_engine->clone(a_engine);
+    if (ScaleEngine *a_engine = dynamic_cast<ScaleEngine *>(d_plot->axisScaleEngine(a))) {
+      sc_engine->clone(a_engine);
+    }
   }
 
   /*QwtScaleEngine *qwtsc_engine = d_plot->axisScaleEngine(axis);
@@ -1153,17 +1154,18 @@ void Graph::setScale(int axis, double start, double end, double step,
     double stepBeforeBreak, double stepAfterBreak, int minTicksBeforeBreak,
     int minTicksAfterBreak, bool log10AfterBreak, int breakWidth, bool breakDecoration)
 {
-  ScaleEngine* se = dynamic_cast<ScaleEngine *>(d_plot->axisScaleEngine(axis));
-  se->setBreakRegion(left_break, right_break);
-  se->setBreakPosition(breakPos);
-  se->setBreakWidth(breakWidth);
-  se->drawBreakDecoration(breakDecoration);
-  se->setStepBeforeBreak(stepBeforeBreak);
-  se->setStepAfterBreak(stepAfterBreak);
-  se->setMinTicksBeforeBreak(minTicksBeforeBreak);
-  se->setMinTicksAfterBreak(minTicksAfterBreak);
-  se->setLog10ScaleAfterBreak(log10AfterBreak);
-  se->setAttribute(QwtScaleEngine::Inverted, inverted);
+  if (ScaleEngine* se = dynamic_cast<ScaleEngine *>(d_plot->axisScaleEngine(axis))){
+    se->setBreakRegion(left_break, right_break);
+    se->setBreakPosition(breakPos);
+    se->setBreakWidth(breakWidth);
+    se->drawBreakDecoration(breakDecoration);
+    se->setStepBeforeBreak(stepBeforeBreak);
+    se->setStepAfterBreak(stepAfterBreak);
+    se->setMinTicksBeforeBreak(minTicksBeforeBreak);
+    se->setMinTicksAfterBreak(minTicksAfterBreak);
+    se->setLog10ScaleAfterBreak(log10AfterBreak);
+    se->setAttribute(QwtScaleEngine::Inverted, inverted);
+  }
 
   setAxisScale(axis, start, end, type, step, majorTicks, minorTicks);
 
@@ -4214,7 +4216,7 @@ void Graph::copy(Graph* g)
         c_keys[i] = d_plot->insertCurve(c);
 
         QwtHistogram *cQH = dynamic_cast<QwtHistogram*>(c);
-        if (cQH)
+        if (cQH && h)
           cQH->copy(h);
       } else if (style == VectXYXY || style == VectXYAM) {
         VectorCurve::VectorStyle vs = VectorCurve::XYXY;
diff --git a/Code/Mantid/MantidPlot/src/ImageDialog.cpp b/Code/Mantid/MantidPlot/src/ImageDialog.cpp
index d13603b5127940a21884d2a11f56b2dae42f3b64..f15fd300e3eb90f2760e65c45ecc55187c64a127 100644
--- a/Code/Mantid/MantidPlot/src/ImageDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/ImageDialog.cpp
@@ -33,7 +33,7 @@
 #include <QLabel>
 
 ImageDialog::ImageDialog( QWidget* parent, Qt::WFlags fl )
-    : QDialog( parent, fl )
+  : QDialog( parent, fl ), aspect_ratio(1.)
 {
 	setName( "ImageDialog" );
 	setWindowTitle( tr( "MantidPlot - Image Geometry" ) );
diff --git a/Code/Mantid/MantidPlot/src/ImageExportDialog.cpp b/Code/Mantid/MantidPlot/src/ImageExportDialog.cpp
index 5eb48205d71573eab2e1afd6fdad0578117b3e53..6953951351e004c9b0aa6f0637f3c5cebdd40ff6 100644
--- a/Code/Mantid/MantidPlot/src/ImageExportDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/ImageExportDialog.cpp
@@ -85,7 +85,10 @@ ImageExportDialog::ImageExportDialog(QWidget * parent, bool vector_options, bool
 
 void ImageExportDialog::initAdvancedOptions()
 {
-		ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (!app) {
+    throw std::logic_error("Parent of ImageExportDialog is not ApplicationWindow as expected.");
+  }
 	d_advanced_options = new QStackedWidget();
 
 	d_vector_options = new QGroupBox();
diff --git a/Code/Mantid/MantidPlot/src/ImportASCIIDialog.cpp b/Code/Mantid/MantidPlot/src/ImportASCIIDialog.cpp
index 1b72808a944af82a812eaa64ac61a098d42132d5..c93828a254594e8a1b6f68ab3d0b7fd17e373427 100644
--- a/Code/Mantid/MantidPlot/src/ImportASCIIDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/ImportASCIIDialog.cpp
@@ -70,6 +70,9 @@ ImportASCIIDialog::ImportASCIIDialog(bool new_windows_only, QWidget * parent, bo
 
 	// get rembered option values
 	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (!app) {
+    throw std::logic_error("Parent of ImportASCIIDialog is not ApplicationWindow as expected.");
+  }
 	setLocale(app->locale());
 
 	d_strip_spaces->setChecked(app->strip_spaces);
diff --git a/Code/Mantid/MantidPlot/src/Integration.cpp b/Code/Mantid/MantidPlot/src/Integration.cpp
index a7caa0cb1fca2d7eadf621be73f83fe7d917fa1d..1ae944321332169ced146f0b0497a0fe13913ae4 100644
--- a/Code/Mantid/MantidPlot/src/Integration.cpp
+++ b/Code/Mantid/MantidPlot/src/Integration.cpp
@@ -174,6 +174,7 @@ int Integration::romberg()
 QString Integration::logInfo()
 {
   ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (!app) return "";
     QLocale locale = app->locale();
     int prec = app->d_decimal_digits;
 
diff --git a/Code/Mantid/MantidPlot/src/InterpolationDialog.cpp b/Code/Mantid/MantidPlot/src/InterpolationDialog.cpp
index efc62a720287db9a0bf84597b542da0dbd6d2852..d42d9224898f6b94cd173da0c8e2f7ac8c3b659c 100644
--- a/Code/Mantid/MantidPlot/src/InterpolationDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/InterpolationDialog.cpp
@@ -42,63 +42,63 @@
 #include <QLayout>
 
 InterpolationDialog::InterpolationDialog( QWidget* parent, Qt::WFlags fl )
-    : QDialog( parent, fl )
+  : QDialog( parent, fl ), graph(NULL)
 {
     setName( "InterpolationDialog" );
-	setWindowTitle(tr("MantidPlot - Interpolation Options"));
+    setWindowTitle(tr("MantidPlot - Interpolation Options"));
 
     QGroupBox *gb1 = new QGroupBox();
-	QGridLayout *gl1 = new QGridLayout(gb1);
-	gl1->addWidget(new QLabel(tr("Make curve from")), 0, 0);
+    QGridLayout *gl1 = new QGridLayout(gb1);
+    gl1->addWidget(new QLabel(tr("Make curve from")), 0, 0);
 
-	boxName = new QComboBox();
-	gl1->addWidget(boxName, 0, 1);
+    boxName = new QComboBox();
+    gl1->addWidget(boxName, 0, 1);
 
-	gl1->addWidget(new QLabel(tr("Spline")), 1, 0);
-	boxMethod = new QComboBox();
-	boxMethod->insertItem(tr("Linear"));
+    gl1->addWidget(new QLabel(tr("Spline")), 1, 0);
+    boxMethod = new QComboBox();
+    boxMethod->insertItem(tr("Linear"));
     boxMethod->insertItem(tr("Cubic"));
     boxMethod->insertItem(tr("Non-rounded Akima"));
-	gl1->addWidget(boxMethod, 1, 1);
+    gl1->addWidget(boxMethod, 1, 1);
 
-	gl1->addWidget(new QLabel(tr("Points")), 2, 0);
-	boxPoints = new QSpinBox();
-	boxPoints->setRange(3,100000);
-	boxPoints->setSingleStep(10);
-	boxPoints->setValue(1000);
-	gl1->addWidget(boxPoints, 2, 1);
+    gl1->addWidget(new QLabel(tr("Points")), 2, 0);
+    boxPoints = new QSpinBox();
+    boxPoints->setRange(3,100000);
+    boxPoints->setSingleStep(10);
+    boxPoints->setValue(1000);
+    gl1->addWidget(boxPoints, 2, 1);
 
-	gl1->addWidget(new QLabel(tr("From Xmin")), 3, 0);
-	boxStart = new QLineEdit();
-	boxStart->setText(tr("0"));
-	gl1->addWidget(boxStart, 3, 1);
+    gl1->addWidget(new QLabel(tr("From Xmin")), 3, 0);
+    boxStart = new QLineEdit();
+    boxStart->setText(tr("0"));
+    gl1->addWidget(boxStart, 3, 1);
 
-	gl1->addWidget(new QLabel(tr("To Xmax")), 4, 0);
-	boxEnd = new QLineEdit();
-	gl1->addWidget(boxEnd, 4, 1);
+    gl1->addWidget(new QLabel(tr("To Xmax")), 4, 0);
+    boxEnd = new QLineEdit();
+    gl1->addWidget(boxEnd, 4, 1);
 
-	gl1->addWidget(new QLabel(tr("Color")), 5, 0);
+    gl1->addWidget(new QLabel(tr("Color")), 5, 0);
 
-	boxColor = new ColorBox();
-	boxColor->setColor(QColor(Qt::red));
-	gl1->addWidget(boxColor, 5, 1);
-	gl1->setRowStretch(6, 1);
+    boxColor = new ColorBox();
+    boxColor->setColor(QColor(Qt::red));
+    gl1->addWidget(boxColor, 5, 1);
+    gl1->setRowStretch(6, 1);
 
-	buttonFit = new QPushButton(tr( "&Make" ));
+    buttonFit = new QPushButton(tr( "&Make" ));
     buttonFit->setDefault( true );
     buttonCancel = new QPushButton(tr( "&Close" ));
 
-	QVBoxLayout *vl = new QVBoxLayout();
- 	vl->addWidget(buttonFit);
-	vl->addWidget(buttonCancel);
+    QVBoxLayout *vl = new QVBoxLayout();
+    vl->addWidget(buttonFit);
+    vl->addWidget(buttonCancel);
     vl->addStretch();
 
     QHBoxLayout *hb = new QHBoxLayout(this);
     hb->addWidget(gb1);
     hb->addLayout(vl);
 
-	connect( boxName, SIGNAL(activated(const QString&)), this, SLOT( activateCurve(const QString&)));
-	connect( buttonFit, SIGNAL( clicked() ), this, SLOT( interpolate() ) );
+    connect( boxName, SIGNAL(activated(const QString&)), this, SLOT( activateCurve(const QString&)));
+    connect( buttonFit, SIGNAL( clicked() ), this, SLOT( interpolate() ) );
     connect( buttonCancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
 }
 
diff --git a/Code/Mantid/MantidPlot/src/LayerDialog.cpp b/Code/Mantid/MantidPlot/src/LayerDialog.cpp
index 4d1112d13a9a0f06386fe2f8c855fa209cf58bc1..03823209aec75a7c84dfbd9133175b98cbc101af 100644
--- a/Code/Mantid/MantidPlot/src/LayerDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/LayerDialog.cpp
@@ -41,155 +41,155 @@
 #include <QMessageBox>
 
 LayerDialog::LayerDialog( QWidget* parent, Qt::WFlags fl )
-: QDialog( parent, fl )
+  : QDialog( parent, fl ), multi_layer(NULL)
 {
     setName("LayerDialog");
-	setWindowTitle(tr( "MantidPlot - Arrange Layers" ));
+    setWindowTitle(tr( "MantidPlot - Arrange Layers" ));
 
     QGroupBox *gb1 = new QGroupBox(tr("Layers"));
-	QGridLayout *gl1 = new QGridLayout(gb1);
-	gl1->addWidget(new QLabel(tr("Number")), 0, 0);
-	layersBox = new QSpinBox();
-	layersBox->setRange(0, 100);
-	gl1->addWidget(layersBox, 0, 1);
+    QGridLayout *gl1 = new QGridLayout(gb1);
+    gl1->addWidget(new QLabel(tr("Number")), 0, 0);
+    layersBox = new QSpinBox();
+    layersBox->setRange(0, 100);
+    gl1->addWidget(layersBox, 0, 1);
 
-	fitBox = new QCheckBox(tr("Automatic &layout"));
-	fitBox->setChecked(false);
-	gl1->addWidget(fitBox, 1, 1);
-	gl1->setRowStretch(2, 1);
+    fitBox = new QCheckBox(tr("Automatic &layout"));
+    fitBox->setChecked(false);
+    gl1->addWidget(fitBox, 1, 1);
+    gl1->setRowStretch(2, 1);
 
     QGroupBox *gb2 = new QGroupBox(tr("Alignment"));
-	QGridLayout *gl2 = new QGridLayout(gb2);
-	gl2->addWidget(new QLabel(tr("Horizontal")), 0, 0);
-
-	alignHorBox = new QComboBox( );
-	alignHorBox->insertItem( tr( "Center" ) );
-	alignHorBox->insertItem( tr( "Left" ) );
-	alignHorBox->insertItem( tr( "Right" ) );
-	gl2->addWidget(alignHorBox, 0, 1);
-
-	gl2->addWidget(new QLabel( tr( "Vertical" )), 1, 0 );
-	alignVertBox = new QComboBox();
-	alignVertBox->insertItem( tr( "Center" ) );
-	alignVertBox->insertItem( tr( "Top" ) );
-	alignVertBox->insertItem( tr( "Bottom" ) );
-	gl2->addWidget(alignVertBox, 1, 1);
-	gl2->setRowStretch(2, 1);
+    QGridLayout *gl2 = new QGridLayout(gb2);
+    gl2->addWidget(new QLabel(tr("Horizontal")), 0, 0);
+
+    alignHorBox = new QComboBox( );
+    alignHorBox->insertItem( tr( "Center" ) );
+    alignHorBox->insertItem( tr( "Left" ) );
+    alignHorBox->insertItem( tr( "Right" ) );
+    gl2->addWidget(alignHorBox, 0, 1);
+
+    gl2->addWidget(new QLabel( tr( "Vertical" )), 1, 0 );
+    alignVertBox = new QComboBox();
+    alignVertBox->insertItem( tr( "Center" ) );
+    alignVertBox->insertItem( tr( "Top" ) );
+    alignVertBox->insertItem( tr( "Bottom" ) );
+    gl2->addWidget(alignVertBox, 1, 1);
+    gl2->setRowStretch(2, 1);
 
     GroupGrid = new QGroupBox(tr("Grid"));
-	QGridLayout *gl3 = new QGridLayout(GroupGrid);
-	gl3->addWidget(new QLabel(tr("Columns")), 0, 0);
-	boxX = new QSpinBox();
-	boxX->setRange(1, 100);
-	gl3->addWidget(boxX, 0, 1);
-	gl3->addWidget(new QLabel( tr( "Rows" )), 1, 0);
-	boxY = new QSpinBox();
-	boxY->setRange(1, 100);
-	gl3->addWidget(boxY, 1, 1);
-
-	GroupCanvasSize = new QGroupBox(tr("&Layer Canvas Size"));
-	GroupCanvasSize->setCheckable(true);
-	GroupCanvasSize->setChecked(false);
-
-	QGridLayout *gl5 = new QGridLayout(GroupCanvasSize);
-	gl5->addWidget(new QLabel(tr("Width")), 0, 0);
-	boxCanvasWidth = new QSpinBox();
-	boxCanvasWidth->setRange(0, 10000);
-	boxCanvasWidth->setSingleStep(50);
-	boxCanvasWidth->setSuffix(tr(" pixels"));
-	gl5->addWidget(boxCanvasWidth, 0, 1);
-	gl5->addWidget(new QLabel( tr( "Height" )), 1, 0);
-	boxCanvasHeight = new QSpinBox();
-	boxCanvasHeight->setRange(0, 10000);
-	boxCanvasHeight->setSingleStep(50);
-	boxCanvasHeight->setSuffix(tr(" pixels"));
-	gl5->addWidget(boxCanvasHeight, 1, 1);
+    QGridLayout *gl3 = new QGridLayout(GroupGrid);
+    gl3->addWidget(new QLabel(tr("Columns")), 0, 0);
+    boxX = new QSpinBox();
+    boxX->setRange(1, 100);
+    gl3->addWidget(boxX, 0, 1);
+    gl3->addWidget(new QLabel( tr( "Rows" )), 1, 0);
+    boxY = new QSpinBox();
+    boxY->setRange(1, 100);
+    gl3->addWidget(boxY, 1, 1);
+
+    GroupCanvasSize = new QGroupBox(tr("&Layer Canvas Size"));
+    GroupCanvasSize->setCheckable(true);
+    GroupCanvasSize->setChecked(false);
+
+    QGridLayout *gl5 = new QGridLayout(GroupCanvasSize);
+    gl5->addWidget(new QLabel(tr("Width")), 0, 0);
+    boxCanvasWidth = new QSpinBox();
+    boxCanvasWidth->setRange(0, 10000);
+    boxCanvasWidth->setSingleStep(50);
+    boxCanvasWidth->setSuffix(tr(" pixels"));
+    gl5->addWidget(boxCanvasWidth, 0, 1);
+    gl5->addWidget(new QLabel( tr( "Height" )), 1, 0);
+    boxCanvasHeight = new QSpinBox();
+    boxCanvasHeight->setRange(0, 10000);
+    boxCanvasHeight->setSingleStep(50);
+    boxCanvasHeight->setSuffix(tr(" pixels"));
+    gl5->addWidget(boxCanvasHeight, 1, 1);
 
     QGroupBox *gb4 = new QGroupBox(tr("Spacing"));
-	QGridLayout *gl4 = new QGridLayout(gb4);
-	gl4->addWidget(new QLabel(tr("Columns gap")), 0, 0);
-	boxColsGap = new QSpinBox();
-	boxColsGap->setRange(0, 1000);
-	boxColsGap->setSingleStep(5);
-	boxColsGap->setSuffix(tr(" pixels"));
-	gl4->addWidget(boxColsGap, 0, 1);
-	gl4->addWidget(new QLabel( tr( "Rows gap" )), 1, 0);
-	boxRowsGap = new QSpinBox();
-	boxRowsGap->setRange(0, 1000);
-	boxRowsGap->setSingleStep(5);
-	boxRowsGap->setSuffix(tr(" pixels"));
-	gl4->addWidget(boxRowsGap, 1, 1);
-	gl4->addWidget(new QLabel( tr( "Left margin" )), 2, 0);
-	boxLeftSpace = new QSpinBox();
-	boxLeftSpace->setRange(0, 1000);
-	boxLeftSpace->setSingleStep(5);
-	boxLeftSpace->setSuffix(tr(" pixels"));
-	gl4->addWidget(boxLeftSpace, 2, 1);
-	gl4->addWidget(new QLabel( tr( "Right margin" )), 3, 0);
-	boxRightSpace = new QSpinBox();
-	boxRightSpace->setRange(0, 1000);
-	boxRightSpace->setSingleStep(5);
-	boxRightSpace->setSuffix(tr(" pixels"));
-	gl4->addWidget(boxRightSpace, 3, 1);
-	gl4->addWidget(new QLabel( tr( "Top margin" )), 4, 0);
-	boxTopSpace = new QSpinBox();
-	boxTopSpace->setRange(0, 1000);
-	boxTopSpace->setSingleStep(5);
-	boxTopSpace->setSuffix(tr(" pixels"));
-	gl4->addWidget(boxTopSpace, 4, 1);
-	gl4->addWidget(new QLabel( tr( "Bottom margin") ), 5, 0);
-	boxBottomSpace = new QSpinBox();
-	boxBottomSpace->setRange(0, 1000);
-	boxBottomSpace->setSingleStep(5);
-	boxBottomSpace->setSuffix(tr(" pixels"));
-	gl4->addWidget(boxBottomSpace, 5, 1);
-
-	QVBoxLayout *vbox1 = new QVBoxLayout();
-	vbox1->addWidget(GroupGrid);
-	vbox1->addWidget(GroupCanvasSize);
-
-	buttonApply = new QPushButton(tr( "&Apply" ));
-	buttonOk = new QPushButton(tr( "&OK" ));
-	buttonCancel = new QPushButton(tr( "&Cancel" ));
-
-	QHBoxLayout *hbox1 = new QHBoxLayout();
+    QGridLayout *gl4 = new QGridLayout(gb4);
+    gl4->addWidget(new QLabel(tr("Columns gap")), 0, 0);
+    boxColsGap = new QSpinBox();
+    boxColsGap->setRange(0, 1000);
+    boxColsGap->setSingleStep(5);
+    boxColsGap->setSuffix(tr(" pixels"));
+    gl4->addWidget(boxColsGap, 0, 1);
+    gl4->addWidget(new QLabel( tr( "Rows gap" )), 1, 0);
+    boxRowsGap = new QSpinBox();
+    boxRowsGap->setRange(0, 1000);
+    boxRowsGap->setSingleStep(5);
+    boxRowsGap->setSuffix(tr(" pixels"));
+    gl4->addWidget(boxRowsGap, 1, 1);
+    gl4->addWidget(new QLabel( tr( "Left margin" )), 2, 0);
+    boxLeftSpace = new QSpinBox();
+    boxLeftSpace->setRange(0, 1000);
+    boxLeftSpace->setSingleStep(5);
+    boxLeftSpace->setSuffix(tr(" pixels"));
+    gl4->addWidget(boxLeftSpace, 2, 1);
+    gl4->addWidget(new QLabel( tr( "Right margin" )), 3, 0);
+    boxRightSpace = new QSpinBox();
+    boxRightSpace->setRange(0, 1000);
+    boxRightSpace->setSingleStep(5);
+    boxRightSpace->setSuffix(tr(" pixels"));
+    gl4->addWidget(boxRightSpace, 3, 1);
+    gl4->addWidget(new QLabel( tr( "Top margin" )), 4, 0);
+    boxTopSpace = new QSpinBox();
+    boxTopSpace->setRange(0, 1000);
+    boxTopSpace->setSingleStep(5);
+    boxTopSpace->setSuffix(tr(" pixels"));
+    gl4->addWidget(boxTopSpace, 4, 1);
+    gl4->addWidget(new QLabel( tr( "Bottom margin") ), 5, 0);
+    boxBottomSpace = new QSpinBox();
+    boxBottomSpace->setRange(0, 1000);
+    boxBottomSpace->setSingleStep(5);
+    boxBottomSpace->setSuffix(tr(" pixels"));
+    gl4->addWidget(boxBottomSpace, 5, 1);
+
+    QVBoxLayout *vbox1 = new QVBoxLayout();
+    vbox1->addWidget(GroupGrid);
+    vbox1->addWidget(GroupCanvasSize);
+
+    buttonApply = new QPushButton(tr( "&Apply" ));
+    buttonOk = new QPushButton(tr( "&OK" ));
+    buttonCancel = new QPushButton(tr( "&Cancel" ));
+
+    QHBoxLayout *hbox1 = new QHBoxLayout();
     hbox1->addStretch();
-	hbox1->addWidget(buttonApply);
-	hbox1->addWidget(buttonOk);
-	hbox1->addWidget(buttonCancel);
-
-	QGroupBox *gb5 = new QGroupBox(tr("Swap Layers"));
-	QHBoxLayout *hbox2 = new QHBoxLayout(gb5);
-	hbox2->addWidget(new QLabel( tr( "Source Layer") ));
-
-	boxLayerSrc = new QSpinBox();
-	hbox2->addWidget(boxLayerSrc);
-
-	hbox2->addWidget(new QLabel( tr( "Destination Layer") ));
-	boxLayerDest = new QSpinBox();
-	hbox2->addWidget(boxLayerDest);
-
-	buttonSwapLayers = new QPushButton(tr( "&Swap" ));
-	hbox2->addWidget(buttonSwapLayers);
-
-	QGridLayout *gl6 = new QGridLayout();
-	gl6->addWidget(gb1, 0, 0);
-	gl6->addWidget(gb2, 0, 1);
-	gl6->addLayout(vbox1, 1, 0);
-	gl6->addWidget(gb4, 1, 1);
-	gl6->setRowStretch(2, 1);
-
-	QVBoxLayout *vbox2 = new QVBoxLayout(this);
-	vbox2->addLayout(gl6);
-	vbox2->addWidget(gb5);
-	vbox2->addStretch();
-	vbox2->addLayout(hbox1);
-
-	connect( buttonSwapLayers, SIGNAL( clicked() ), this, SLOT( swapLayers() ) );
-	connect( buttonOk, SIGNAL( clicked() ), this, SLOT( accept() ) );
-	connect( buttonApply, SIGNAL( clicked() ), this, SLOT(update() ) );
-	connect( buttonCancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
-	connect( fitBox, SIGNAL( toggled(bool) ), this, SLOT(enableLayoutOptions(bool) ) );
+    hbox1->addWidget(buttonApply);
+    hbox1->addWidget(buttonOk);
+    hbox1->addWidget(buttonCancel);
+
+    QGroupBox *gb5 = new QGroupBox(tr("Swap Layers"));
+    QHBoxLayout *hbox2 = new QHBoxLayout(gb5);
+    hbox2->addWidget(new QLabel( tr( "Source Layer") ));
+
+    boxLayerSrc = new QSpinBox();
+    hbox2->addWidget(boxLayerSrc);
+
+    hbox2->addWidget(new QLabel( tr( "Destination Layer") ));
+    boxLayerDest = new QSpinBox();
+    hbox2->addWidget(boxLayerDest);
+
+    buttonSwapLayers = new QPushButton(tr( "&Swap" ));
+    hbox2->addWidget(buttonSwapLayers);
+
+    QGridLayout *gl6 = new QGridLayout();
+    gl6->addWidget(gb1, 0, 0);
+    gl6->addWidget(gb2, 0, 1);
+    gl6->addLayout(vbox1, 1, 0);
+    gl6->addWidget(gb4, 1, 1);
+    gl6->setRowStretch(2, 1);
+
+    QVBoxLayout *vbox2 = new QVBoxLayout(this);
+    vbox2->addLayout(gl6);
+    vbox2->addWidget(gb5);
+    vbox2->addStretch();
+    vbox2->addLayout(hbox1);
+
+    connect( buttonSwapLayers, SIGNAL( clicked() ), this, SLOT( swapLayers() ) );
+    connect( buttonOk, SIGNAL( clicked() ), this, SLOT( accept() ) );
+    connect( buttonApply, SIGNAL( clicked() ), this, SLOT(update() ) );
+    connect( buttonCancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
+    connect( fitBox, SIGNAL( toggled(bool) ), this, SLOT(enableLayoutOptions(bool) ) );
 }
 
 void LayerDialog::enableLayoutOptions(bool ok)
@@ -239,6 +239,7 @@ void LayerDialog::update()
 		if (dn < 0)
 		{// Customize new layers with user default settings
       ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+      if (!app) return;
 			for (int i = old_graphs+1; i <= graphs; i++)
 				app->setPreferences(multi_layer->layer(i));
 		}
diff --git a/Code/Mantid/MantidPlot/src/LegendWidget.cpp b/Code/Mantid/MantidPlot/src/LegendWidget.cpp
index 724e08d362b22e971d1bec46788c5e7c2251bafc..d17de38685353e8b345e06f214dc8afb5d20038f 100644
--- a/Code/Mantid/MantidPlot/src/LegendWidget.cpp
+++ b/Code/Mantid/MantidPlot/src/LegendWidget.cpp
@@ -51,7 +51,8 @@ LegendWidget::LegendWidget(Plot *plot):QWidget(plot),
 	d_plot(plot),
 	d_frame (0),
 	d_angle(0),
-	d_fixed_coordinates(false)
+        d_x(0.), d_y(0.),
+        d_fixed_coordinates(false)
 {
 	setAttribute(Qt::WA_DeleteOnClose);
 
@@ -204,9 +205,14 @@ void LegendWidget::drawVector(PlotCurve *c, QPainter *p, int x, int y, int l)
 		return;
 
   VectorCurve *v = dynamic_cast<VectorCurve*>(c);
+  if (!v) return;
+
+  Graph* g = dynamic_cast<Graph *>(d_plot->parent());
+  if (!g) return;
+
 	p->save();
 
-  if ((dynamic_cast<Graph *>(d_plot->parent()))->antialiasing())
+  if (g->antialiasing())
 		p->setRenderHints(QPainter::Antialiasing);
 
 	QPen pen(v->color(), v->width(), Qt::SolidLine);
@@ -243,6 +249,7 @@ void LegendWidget::drawSymbol(PlotCurve *c, int point, QPainter *p, int x, int y
 
 	if (c->type() == Graph::Pie){
     QwtPieCurve *pie = dynamic_cast<QwtPieCurve *>(c);
+    if (!pie) return;
 		const QBrush br = QBrush(pie->color(point), pie->pattern());
 		QPen pen = pie->pen();
 		p->save();
@@ -281,8 +288,10 @@ void LegendWidget::drawText(QPainter *p, const QRect& rect,
 		QwtArray<int> height, int symbolLineLength)
 {
   p->save();
-  if ((dynamic_cast<Graph *>(d_plot->parent()))->antialiasing())
-    p->setRenderHints(QPainter::Antialiasing);
+  if (auto g = dynamic_cast<Graph *>(d_plot->parent())) {
+    if (g->antialiasing())
+      p->setRenderHints(QPainter::Antialiasing);
+  }
 
   // RJT (22/09/09): For remainder of method, copied in code from current 
   // QtiPlot (rev. 1373) to fix infinite loop if closing bracket missing
@@ -569,10 +578,12 @@ QString LegendWidget::parse(const QString& str)
 					if (lst.count() == 1)
 						s = s.replace(pos, pos2-pos+1, c->title().text());
 					else if (lst.count() == 3 && c->type() == Graph::Pie){
-            Table *t = (dynamic_cast<DataCurve *>(c))->table();
-						int col = t->colIndex(c->title().text());
-						int row = lst[2].toInt() - 1;
-						s = s.replace(pos, pos2-pos+1, t->text(row, col));
+            if (auto dc = dynamic_cast<DataCurve *>(c)) {
+              Table *t = dc->table();
+						  int col = t->colIndex(c->title().text());
+						  int row = lst[2].toInt() - 1;
+						  s = s.replace(pos, pos2-pos+1, t->text(row, col));
+            }
 					}
 				}
         	}
@@ -586,25 +597,25 @@ PlotCurve* LegendWidget::getCurve(const QString& s, int &point)
 {
 	point = -1;
 	PlotCurve *curve = 0;
-  Graph *g = dynamic_cast<Graph *>(d_plot->parent());
-
-	QStringList l = s.split(",");
-    if (l.count() == 2)
-		point = l[1].toInt() - 1;
-
-	if (!l.isEmpty()){
-		l = l[0].split(".");
-    	if (l.count() == 2){
-    		int cv = l[1].toInt() - 1;
-			Graph *layer = g->multiLayer()->layer(l[0].toInt());
-			if (layer && cv >= 0 && cv < layer->curves())
-        return dynamic_cast<PlotCurve*>(layer->curve(cv));
-		} else if (l.count() == 1){
-			int cv = l[0].toInt() - 1;
-			if (cv >= 0 || cv < g->curves())
-        return dynamic_cast<PlotCurve*>(g->curve(cv));
-		}
-	}
+  if (Graph *g = dynamic_cast<Graph *>(d_plot->parent())) {
+	  QStringList l = s.split(",");
+      if (l.count() == 2)
+		  point = l[1].toInt() - 1;
+
+	  if (!l.isEmpty()){
+		  l = l[0].split(".");
+    	  if (l.count() == 2){
+    		  int cv = l[1].toInt() - 1;
+			  Graph *layer = g->multiLayer()->layer(l[0].toInt());
+			  if (layer && cv >= 0 && cv < layer->curves())
+          return dynamic_cast<PlotCurve*>(layer->curve(cv));
+		  } else if (l.count() == 1){
+			  int cv = l[0].toInt() - 1;
+			  if (cv >= 0 || cv < g->curves())
+          return dynamic_cast<PlotCurve*>(g->curve(cv));
+		  }
+	  }
+  }
 	return curve;
 }
 
@@ -626,11 +637,11 @@ void LegendWidget::mousePressEvent (QMouseEvent * /*e*/)
   // You cannot use 'this', that mixes up the labels and the last legend added (tickets #8891, #8851).
   // Alternative way of guessing the widget being clicked (we have QMouseEvent* e here): 
   // qApp->widgetAt(e->globalX(),e->globalY()))
-  LegendWidget *clickedWidget = dynamic_cast<LegendWidget*>(qApp->widgetAt(QCursor::pos()));
-
-  d_selector = new SelectionMoveResizer(clickedWidget);
-  connect(d_selector, SIGNAL(targetsChanged()), dynamic_cast<Graph*>(d_plot->parent()), SIGNAL(modifiedGraph()));
-  (dynamic_cast<Graph *>(d_plot->parent()))->setSelectedText(clickedWidget);
+  if (LegendWidget *clickedWidget = dynamic_cast<LegendWidget*>(qApp->widgetAt(QCursor::pos()))) {
+    d_selector = new SelectionMoveResizer(clickedWidget);
+    connect(d_selector, SIGNAL(targetsChanged()), g, SIGNAL(modifiedGraph()));
+    g->setSelectedText(clickedWidget);
+  }
 }
 
 void LegendWidget::setSelected(bool on)
@@ -667,14 +678,11 @@ void LegendWidget::setSelected(bool on)
 
 void LegendWidget::showTextEditor()
 {
-  // RJT (22/09/09): The code below caused a warning from the QObject destructor, which can't be good
-  // The d_selector member is completely gone from the current version of this code
-  //if (d_selector){
-  //  delete d_selector;
-  //  d_selector = NULL;
-  //}
-
-    ApplicationWindow *app = (dynamic_cast<Graph *>(d_plot->parent()))->multiLayer()->applicationWindow();
+    Graph *g = (dynamic_cast<Graph*>(d_plot->parent()));
+    if (!g)
+      return;
+
+    ApplicationWindow *app = g->multiLayer()->applicationWindow();
     if (!app)
         return;
 
diff --git a/Code/Mantid/MantidPlot/src/Mantid/AlgorithmHistoryWindow.cpp b/Code/Mantid/MantidPlot/src/Mantid/AlgorithmHistoryWindow.cpp
index 456acf8444926367c265e8cc19e99915843f5804..3a3b77c8fd9c788f9f46b7b025966ebbf9909c42 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/AlgorithmHistoryWindow.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/AlgorithmHistoryWindow.cpp
@@ -588,8 +588,9 @@ void AlgHistoryTreeWidget::uncheckAllChildren(QTreeWidgetItem* item, int index)
 
 void AlgHistoryTreeWidget::treeSelectionChanged()
 {	
-  AlgHistoryItem* item = dynamic_cast<AlgHistoryItem*>(this->selectedItems()[0]);
-  emit updateAlgorithmHistoryWindow(item->getAlgorithmHistory());
+  if (AlgHistoryItem* item = dynamic_cast<AlgHistoryItem*>(this->selectedItems()[0])) {
+    emit updateAlgorithmHistoryWindow(item->getAlgorithmHistory());
+  }
 }
 
 void AlgHistoryTreeWidget::selectionChanged ( const QItemSelection & selected, const QItemSelection & deselected )
diff --git a/Code/Mantid/MantidPlot/src/Mantid/ImportWorkspaceDlg.cpp b/Code/Mantid/MantidPlot/src/Mantid/ImportWorkspaceDlg.cpp
index 3db84add16b79ddf9a05034a16e7952a98cddf24..e2698e7673713fc7c21a7a990e74289b74cb82a3 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/ImportWorkspaceDlg.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/ImportWorkspaceDlg.cpp
@@ -4,7 +4,8 @@
 
 #include "ImportWorkspaceDlg.h"
 
-ImportWorkspaceDlg::ImportWorkspaceDlg(QWidget *parent, size_t num) : QDialog(parent), numHists(num),minValue(0),maxValue(100.)
+ImportWorkspaceDlg::ImportWorkspaceDlg(QWidget *parent, size_t num) :
+  QDialog(parent), numHists(num), lowerLimit(0), upperLimit(0), filtered(false), minValue(0), maxValue(100.)
 {
 	label = new QLabel(tr("Set Histogram Range to Load (Max Number = " + QString::number(numHists) + "):"));
 	
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/ColorMapWidget.cpp b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/ColorMapWidget.cpp
index 85151ef5f4946ea4866eb08049dc51a97bdf8682..1d97af0ee8a8bd2b3a8d4ec916ec3a809c20f7a3 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/ColorMapWidget.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/ColorMapWidget.cpp
@@ -18,7 +18,7 @@
   * @param minPositiveValue A minimum positive value for the Log10 scale
   */
 ColorMapWidget::ColorMapWidget(int type,QWidget* parent,const double& minPositiveValue):
-QFrame(parent),m_minPositiveValue(minPositiveValue),m_dragging(false)
+  QFrame(parent), m_minPositiveValue(minPositiveValue), m_dragging(false), m_y(0), m_dtype()
 {
   m_scaleWidget = new QwtScaleWidget(QwtScaleDraw::RightScale);
   m_scaleWidget->setColorBarEnabled(true);
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/DetXMLFile.cpp b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/DetXMLFile.cpp
index 8032f3771d16df9f4b4767cc13ff1589835460c7..b6c08f40d1e0043e5f48f2283cf573e9f3c39250 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/DetXMLFile.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/DetXMLFile.cpp
@@ -39,6 +39,7 @@ DetXMLFile::DetXMLFile(const QList<int>& dets, Option opt, const QString& fname)
     if (dets.empty())
     {
       m_fileName = "";
+      m_delete = false;
       return;
     }
 
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentActor.cpp b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentActor.cpp
index 49fdc40cf47014a073af198c1858c34ac88018ff..4653fbd5a36321ed72509d5d76ab1ebeff2468d7 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentActor.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentActor.cpp
@@ -659,8 +659,10 @@ void InstrumentActor::resetColors()
   }
   if (m_scene.getNumberOfActors() > 0)
   {
-    dynamic_cast<CompAssemblyActor*>(m_scene.getActor(0))->setColors();
-    invalidateDisplayLists();
+    if (auto actor = dynamic_cast<CompAssemblyActor*>(m_scene.getActor(0))) {
+      actor->setColors();
+      invalidateDisplayLists();
+    }
   }
   emit colorMapChanged();
 }
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentTreeWidget.cpp b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentTreeWidget.cpp
index a2649437b34be4c7d7eff4d34b7b75be00ab5b4b..d725f60827949f724eee0152ddc0578c5e16a4cd 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentTreeWidget.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentTreeWidget.cpp
@@ -14,7 +14,7 @@
 #include <cfloat>
 #include <iostream>
 
-InstrumentTreeWidget::InstrumentTreeWidget(QWidget *w):QTreeView(w), m_treeModel(0) 
+InstrumentTreeWidget::InstrumentTreeWidget(QWidget *w):QTreeView(w), m_instrActor(NULL), m_treeModel(NULL)
 {
   connect(this,SIGNAL(clicked(const QModelIndex)),this,SLOT(sendComponentSelectedSignal(const QModelIndex)));
 }
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentWindowMaskTab.cpp b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentWindowMaskTab.cpp
index 143fdd02f79c9a37ac540f452cd917f3ef8db0b0..9820795267c684c7e3f2596a4d8ac966fa32494a 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentWindowMaskTab.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentWindowMaskTab.cpp
@@ -62,7 +62,12 @@ InstrumentWindowMaskTab::InstrumentWindowMaskTab(InstrumentWindow* instrWindow):
 InstrumentWindowTab(instrWindow),
 m_activity(Select),
 m_hasMaskToApply(false),
-m_userEditing(true)
+m_userEditing(true),
+m_groupManager(NULL),
+m_stringManager(NULL),
+m_doubleManager(NULL),
+m_browser(NULL),
+m_left(NULL), m_top(NULL), m_right(NULL), m_bottom(NULL)
 {
 
   // main layout
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/XIntegrationControl.cpp b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/XIntegrationControl.cpp
index 5d1fc52edc4fcb6e44c1c236fba7b1c638b66393..4e432ba9a9ea8f148fd5271512177ffd6a969398 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/XIntegrationControl.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/XIntegrationControl.cpp
@@ -24,6 +24,8 @@ m_resizingLeft(false),
 m_resizingRight(false),
 m_moving(false),
 m_changed(false),
+m_x(0),
+m_width(0),
 m_minimum(0.0),
 m_maximum(1.0)
 {
diff --git a/Code/Mantid/MantidPlot/src/Mantid/MantidDock.cpp b/Code/Mantid/MantidPlot/src/Mantid/MantidDock.cpp
index febf051100738ecf83ecd27520ed7863d9bf0fbd..cef8fd980a615f4e25fffe270d9753bda8e700e7 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/MantidDock.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/MantidDock.cpp
@@ -1505,6 +1505,7 @@ MantidTreeWidget::MantidTreeWidget(MantidDockWidget *w, MantidUI *mui)
 {
   setObjectName("WorkspaceTree");
   setSelectionMode(QAbstractItemView::ExtendedSelection);
+  setSortOrder(Qt::AscendingOrder);
   setAcceptDrops(true);
 }
 
diff --git a/Code/Mantid/MantidPlot/src/Mantid/MantidMDCurve.cpp b/Code/Mantid/MantidPlot/src/Mantid/MantidMDCurve.cpp
index 2a0c5502125c408a23be6acc5333ca39bd6eedaa..a666e3ab0980a2b4339a22c2b495b09dc01f9c95 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/MantidMDCurve.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/MantidMDCurve.cpp
@@ -78,7 +78,7 @@ void MantidMDCurve::init(Graph* g, bool distr, Graph::CurveType style)
 
   int lineWidth = 1;
   MultiLayer* ml = dynamic_cast<MultiLayer*>(g->parent()->parent()->parent());
-  if (style == Graph::Unspecified || (ml && ml->applicationWindow()->applyCurveStyleToMantid) )
+  if (ml && (style == Graph::Unspecified || ml->applicationWindow()->applyCurveStyleToMantid) )
   {
     //FIXME: Style HorizontalSteps does NOT seem to be applied
     applyStyleChoice(style, ml, lineWidth);
diff --git a/Code/Mantid/MantidPlot/src/Mantid/MantidMatrix.cpp b/Code/Mantid/MantidPlot/src/Mantid/MantidMatrix.cpp
index 6723f8b298991f3012e4ee9502d8b5ebb78b7db2..f536d323228cebabd7e7690ca8a4ca4c2dc1e976 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/MantidMatrix.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/MantidMatrix.cpp
@@ -1131,6 +1131,7 @@ void MantidMatrixModel::setup(const Mantid::API::MatrixWorkspace* ws,
   m_workspace = ws;
   m_rows = rows;
   m_cols = cols;
+  m_colNumCorr = 1;
   m_startRow = start >= 0? start : 0;
   m_mon_color = QColor(255,255,204);
   if (ws->blocksize() != 0)
diff --git a/Code/Mantid/MantidPlot/src/Mantid/MantidMatrix.h b/Code/Mantid/MantidPlot/src/Mantid/MantidMatrix.h
index c5c5336fc645878cc5910e26f4a996cd0c867a1a..2bf9628335162a12fd386c7f6fe3dc24e2a059b0 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/MantidMatrix.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/MantidMatrix.h
@@ -269,8 +269,6 @@ protected:
   //MantidMatrixFunction m_funct;
   int m_column_width;
 
-  QAction *m_actionShowX;
-
 private:
   //name of the underlying workspace
   std::string m_strName;
diff --git a/Code/Mantid/MantidPlot/src/Mantid/MantidMatrixCurve.cpp b/Code/Mantid/MantidPlot/src/Mantid/MantidMatrixCurve.cpp
index 168fac85eae2f390f5d9a1785f1025d46aa0bab2..92dc7a6f54e2f87b972aa40cebcfe6df8d7c048a 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/MantidMatrixCurve.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/MantidMatrixCurve.cpp
@@ -143,7 +143,7 @@ void MantidMatrixCurve::init(Graph* g,bool distr,Graph::CurveType style)
 
   int lineWidth = 1;
   MultiLayer* ml = dynamic_cast<MultiLayer*>(g->parent()->parent()->parent());
-  if (style == Graph::Unspecified || (ml && ml->applicationWindow()->applyCurveStyleToMantid) )
+  if (ml && (style == Graph::Unspecified || ml->applicationWindow()->applyCurveStyleToMantid) )
   {
     applyStyleChoice(style, ml, lineWidth);
   }
diff --git a/Code/Mantid/MantidPlot/src/Mantid/MantidSampleLogDialog.cpp b/Code/Mantid/MantidPlot/src/Mantid/MantidSampleLogDialog.cpp
index 343c6551c4120d45acc8e47449eabf88d1806a7b..75d103842c8439fd2fbb44d37adcfa4b29c259b0 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/MantidSampleLogDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/MantidSampleLogDialog.cpp
@@ -404,7 +404,7 @@ void MantidSampleLogDialog::init()
       }
       treeItem->setText(2, QString::fromStdString( msg.str()) );
     }
-    else if( dynamic_cast<Mantid::Kernel::TimeSeriesProperty<std::string> *>(*pItr) )
+    else if(auto strSeries = dynamic_cast<Mantid::Kernel::TimeSeriesProperty<std::string> *>(*pItr) )
     {
       treeItem->setText(1, "str. series");
       treeItem->setData(1, Qt::UserRole, static_cast<int>(stringTSeries));
@@ -413,7 +413,7 @@ void MantidSampleLogDialog::init()
       if ((*pItr)->size() == 1)
       {
         //Print out the only entry
-        (dynamic_cast<Mantid::Kernel::TimeSeriesProperty<std::string> *>(*pItr))->nthValue(1);
+        strSeries->nthValue(1);
       }
       else
       {
diff --git a/Code/Mantid/MantidPlot/src/Mantid/MantidUI.cpp b/Code/Mantid/MantidPlot/src/Mantid/MantidUI.cpp
index 5dd11e651811c3c146509769838d870c18003433..d3f10db319fc4f8d9d2822674b72d169c2704e36 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/MantidUI.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/MantidUI.cpp
@@ -942,9 +942,8 @@ Table* MantidUI::importTableWorkspace(const QString& wsName, bool, bool makeVisi
 
 void MantidUI::showContextMenu(QMenu& cm, MdiSubWindow* w)
 {
-  if (w->isA("MantidMatrix"))
+  if (MantidMatrix * mm = dynamic_cast<MantidMatrix*>(w))
   {
-    MantidMatrix * mm = dynamic_cast<MantidMatrix*>(w);
 
     bool areSpectraSelected = mm->setSelectedRows();
     bool areColumnsSelected = mm->setSelectedColumns();
diff --git a/Code/Mantid/MantidPlot/src/Matrix.cpp b/Code/Mantid/MantidPlot/src/Matrix.cpp
index 9b978c99db188044df080bf27cea505dc6bef074..d345ff9617af37b9f004ea3db27e95059c12685c 100644
--- a/Code/Mantid/MantidPlot/src/Matrix.cpp
+++ b/Code/Mantid/MantidPlot/src/Matrix.cpp
@@ -808,8 +808,11 @@ void Matrix::insertColumn()
 
 void Matrix::customEvent(QEvent *e)
 {
-  if (e->type() == SCRIPTING_CHANGE_EVENT)
-    scriptingChangeEvent(dynamic_cast<ScriptingChangeEvent*>(e));
+  if (e->type() == SCRIPTING_CHANGE_EVENT){
+    if (auto sce = dynamic_cast<ScriptingChangeEvent*>(e)) {
+      scriptingChangeEvent(sce);
+    }
+  }
 }
 
 void Matrix::exportRasterImage(const QString& fileName, int quality)
diff --git a/Code/Mantid/MantidPlot/src/MatrixValuesDialog.cpp b/Code/Mantid/MantidPlot/src/MatrixValuesDialog.cpp
index de80bc44467c0ee052c462a1c9f032a148594ffc..78ee5b135847ca1e345768fb042157aeab4c21b2 100644
--- a/Code/Mantid/MantidPlot/src/MatrixValuesDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/MatrixValuesDialog.cpp
@@ -47,91 +47,94 @@
 #endif
 
 MatrixValuesDialog::MatrixValuesDialog( ScriptingEnv *env, QWidget* parent, Qt::WFlags fl )
-: QDialog( parent, fl ), Scripted(env)
+  : QDialog( parent, fl ), Scripted(env), matrix(NULL)
 {
     setName( "MatrixValuesDialog" );
-	setWindowTitle( tr( "MantidPlot - Set Matrix Values" ) );
-	setSizeGripEnabled(true);
+    setWindowTitle( tr( "MantidPlot - Set Matrix Values" ) );
+    setSizeGripEnabled(true);
 
-	QGridLayout *gl1 = new QGridLayout();
+    QGridLayout *gl1 = new QGridLayout();
     gl1->addWidget(new QLabel(tr("For row (i)")), 0, 0);
-	startRow = new QSpinBox();
-	startRow->setRange(1, 1000000);
+    startRow = new QSpinBox();
+    startRow->setRange(1, 1000000);
     gl1->addWidget(startRow, 0, 1);
-	gl1->addWidget(new QLabel(tr("to")), 0, 2);
-	endRow =  new QSpinBox();
-	endRow->setRange(1, 1000000);
-	gl1->addWidget(endRow, 0, 3);
-	gl1->addWidget(new QLabel(tr("For col (j)")), 1, 0);
-	startCol = new QSpinBox();
-	startCol->setRange(1, 1000000);
-	gl1->addWidget(startCol, 1, 1);
-	gl1->addWidget(new QLabel(tr("to")), 1, 2);
-	endCol = new QSpinBox();
-	endCol->setRange(1, 1000000);
-	gl1->addWidget(endCol, 1, 3);
-
-	QVBoxLayout *vbox1 = new QVBoxLayout();
+    gl1->addWidget(new QLabel(tr("to")), 0, 2);
+    endRow =  new QSpinBox();
+    endRow->setRange(1, 1000000);
+    gl1->addWidget(endRow, 0, 3);
+    gl1->addWidget(new QLabel(tr("For col (j)")), 1, 0);
+    startCol = new QSpinBox();
+    startCol->setRange(1, 1000000);
+    gl1->addWidget(startCol, 1, 1);
+    gl1->addWidget(new QLabel(tr("to")), 1, 2);
+    endCol = new QSpinBox();
+    endCol->setRange(1, 1000000);
+    gl1->addWidget(endCol, 1, 3);
+
+    QVBoxLayout *vbox1 = new QVBoxLayout();
     vbox1->addLayout(gl1);
-	QGroupBox *gb = new QGroupBox();
+    QGroupBox *gb = new QGroupBox();
     gb->setLayout(vbox1);
     gb->setSizePolicy(QSizePolicy (QSizePolicy::Maximum, QSizePolicy::Preferred));
 
-	QHBoxLayout *hbox3 = new QHBoxLayout();
-	commands = new ScriptEditor(this, scriptingEnv()->createCodeLexer());
-	commands->setFocus();
-	hbox3->addWidget(commands);
+    QHBoxLayout *hbox3 = new QHBoxLayout();
+    commands = new ScriptEditor(this, scriptingEnv()->createCodeLexer());
+    commands->setFocus();
+    hbox3->addWidget(commands);
 
-	QVBoxLayout *vbox2 = new QVBoxLayout();
-	btnApply = new QPushButton(tr( "&Apply" ));
+    QVBoxLayout *vbox2 = new QVBoxLayout();
+    btnApply = new QPushButton(tr( "&Apply" ));
     vbox2->addWidget(btnApply);
-	btnCancel = new QPushButton(tr( "&Close" ));
+    btnCancel = new QPushButton(tr( "&Close" ));
     vbox2->addWidget(btnCancel);
     vbox2->addStretch();
 
-	QHBoxLayout *hbox2 = new QHBoxLayout();
-	hbox2->addWidget(gb);
-	hbox2->addLayout(vbox2);
+    QHBoxLayout *hbox2 = new QHBoxLayout();
+    hbox2->addWidget(gb);
+    hbox2->addLayout(vbox2);
 
-	QVBoxLayout* vbox3 = new QVBoxLayout(this);
-	vbox3->addLayout(hbox2);
-	vbox3->addWidget(new QLabel(tr( "Cell(i,j)=" )));
-	vbox3->addLayout(hbox3);
+    QVBoxLayout* vbox3 = new QVBoxLayout(this);
+    vbox3->addLayout(hbox2);
+    vbox3->addWidget(new QLabel(tr( "Cell(i,j)=" )));
+    vbox3->addLayout(hbox3);
 
-	connect(btnApply, SIGNAL(clicked()), this, SLOT(apply()));
-	connect(btnCancel, SIGNAL(clicked()), this, SLOT(close()));
+    connect(btnApply, SIGNAL(clicked()), this, SLOT(apply()));
+    connect(btnCancel, SIGNAL(clicked()), this, SLOT(close()));
 }
 
 QSize MatrixValuesDialog::sizeHint() const
 {
-	return QSize( 400, 190 );
+    return QSize( 400, 190 );
 }
 
 void MatrixValuesDialog::customEvent(QEvent *e)
 {
-	if (e->type() == SCRIPTING_CHANGE_EVENT)
-    scriptingChangeEvent(dynamic_cast<ScriptingChangeEvent*>(e));
+	if (e->type() == SCRIPTING_CHANGE_EVENT) {
+    if (auto sce = dynamic_cast<ScriptingChangeEvent*>(e)) {
+      scriptingChangeEvent(sce);
+    }
+  }
 }
 
 bool MatrixValuesDialog::apply()
 {
-	QString formula = commands->text();
-	QString oldFormula = matrix->formula();
+    QString formula = commands->text();
+    QString oldFormula = matrix->formula();
 
-	matrix->setFormula(formula);
+    matrix->setFormula(formula);
 	
-	bool useMuParser = true;
+    bool useMuParser = true;
 	
-	if (matrix->canCalculate(useMuParser)){
-		matrix->undoStack()->push(new MatrixSetFormulaCommand(matrix, oldFormula, formula,
+    if (matrix->canCalculate(useMuParser)){
+        matrix->undoStack()->push(new MatrixSetFormulaCommand(matrix, oldFormula, formula,
 							tr("Set New Formula") + " \"" + formula + "\""));
 
-		if (matrix->calculate(startRow->value()-1, endRow->value()-1, 
-			startCol->value()-1, endCol->value()-1, useMuParser))
-			return true;
+        if (matrix->calculate(startRow->value()-1, endRow->value()-1,
+                              startCol->value()-1, endCol->value()-1, useMuParser))
+            return true;
 	}
-	matrix->setFormula(oldFormula);
-	return false;
+    matrix->setFormula(oldFormula);
+    return false;
 }
 
 void MatrixValuesDialog::setMatrix(Matrix* m)
@@ -139,8 +142,8 @@ void MatrixValuesDialog::setMatrix(Matrix* m)
     if (!m)
         return;
 
-	matrix = m;
-	commands->setText(m->formula());
+    matrix = m;
+    commands->setText(m->formula());
 
     endCol->setValue(m->numCols());
     endRow->setValue(m->numRows());
diff --git a/Code/Mantid/MantidPlot/src/MultiLayer.cpp b/Code/Mantid/MantidPlot/src/MultiLayer.cpp
index 36bf692670f4f0f8e10b7bc219282d995f149a17..e52b132236945700422c4c1d5f95b71c8fb27645 100644
--- a/Code/Mantid/MantidPlot/src/MultiLayer.cpp
+++ b/Code/Mantid/MantidPlot/src/MultiLayer.cpp
@@ -121,6 +121,7 @@ MultiLayer::MultiLayer(ApplicationWindow* parent, int layers, int rows, int cols
                          vert_align(VCenter),
                          d_scale_on_print(true),
                          d_print_cropmarks(false),
+                         d_close_on_empty(false),
                          d_is_waterfall_plot(false),
                          d_waterfall_fill_color(/*Invalid color*/)
 {
@@ -1398,9 +1399,10 @@ void MultiLayer::dropOntoMatrixCurve(Graph *g, MantidMatrixCurve* originalCurve,
     for( ; setIt != it.value().end(); ++setIt)
     {
       try {
+        bool isDistribution = originalCurve ? originalCurve->isDistribution() : false;
         // If the current curve is plotted as a distribution then do so also here
         new MantidMatrixCurve(it.key(),g,(*setIt),MantidMatrixCurve::Spectrum, errorBars,
-                              originalCurve->isDistribution()); // The graph takes ownership
+                              isDistribution); // The graph takes ownership
       } catch (Mantid::Kernel::Exception::NotFoundError &) {
         // Get here if workspace name is invalid - shouldn't be possible, but just in case
       } catch (std::invalid_argument&) {
@@ -1705,8 +1707,9 @@ WaterfallFillDialog::WaterfallFillDialog(MultiLayer *parent, Graph *active_graph
   }
 
   // If sidelines previously enabled, check it.
-  PlotCurve *c = dynamic_cast<PlotCurve*>(active_graph->curve(0));
-  sideLinesBox->setChecked(c->sideLinesEnabled());
+  if (PlotCurve *c = dynamic_cast<PlotCurve*>(active_graph->curve(0))) {
+    sideLinesBox->setChecked(c->sideLinesEnabled());
+  }
 
   colourModeGroup->setEnabled(rSolidC->isChecked() && enableFillGroup->isChecked());
 
diff --git a/Code/Mantid/MantidPlot/src/MultiTabScriptInterpreter.cpp b/Code/Mantid/MantidPlot/src/MultiTabScriptInterpreter.cpp
index b10cbdcb51ca06a42560e3f1bbe31a1527f7adc2..9b6b40bcd96c5437e4a3ca2ac730f8e2d1561488 100644
--- a/Code/Mantid/MantidPlot/src/MultiTabScriptInterpreter.cpp
+++ b/Code/Mantid/MantidPlot/src/MultiTabScriptInterpreter.cpp
@@ -1,6 +1,9 @@
 //-----------------------------------------------------
 // Includes
 //-----------------------------------------------------
+// std
+#include <stdexcept>
+
 #include "ApplicationWindow.h"
 #include "ScriptFileInterpreter.h"
 
@@ -23,9 +26,6 @@
 #include <QSpinBox>
 #include <QFontDatabase>
 
-// std
-#include <stdexcept>
-
 //***************************************************************************
 //
 // MultiTabScriptInterpreter class
diff --git a/Code/Mantid/MantidPlot/src/MultiTabScriptInterpreter.h b/Code/Mantid/MantidPlot/src/MultiTabScriptInterpreter.h
index 7f2fb291464f3fe3ed87bb9f4949b8697e8e02d2..7b2f1cf58f9ae4d6dd541570a2505ee63011f8fe 100644
--- a/Code/Mantid/MantidPlot/src/MultiTabScriptInterpreter.h
+++ b/Code/Mantid/MantidPlot/src/MultiTabScriptInterpreter.h
@@ -228,8 +228,6 @@ private:
   enum { MaxRecentScripts = 5 };
   /// List of recent scripts, with most recent at the top
   QStringList m_recentScriptList;
-  /// Flag to indicate whether stdout should be redirected
-  bool m_capturePrint;
   /// A pointer to the Null object
   NullScriptFileInterpreter *m_nullScript;
   /// A pointer to the current interpreter
diff --git a/Code/Mantid/MantidPlot/src/PlotCurve.cpp b/Code/Mantid/MantidPlot/src/PlotCurve.cpp
index b49b9d1be64f1fe49459f8eeb2906503a7f67aa8..84b4ef9f7335e845b312923fdd94f1a6d0307503 100644
--- a/Code/Mantid/MantidPlot/src/PlotCurve.cpp
+++ b/Code/Mantid/MantidPlot/src/PlotCurve.cpp
@@ -280,10 +280,11 @@ void PlotCurve::computeWaterfallOffsets()
 
   if (g->isWaterfallPlot()){
     int index = g->curveIndex(this);
-    int curves = g->curves();//Count();
-    PlotCurve *c = dynamic_cast<PlotCurve*>(g->curve(0));
+    int curves = g->curves();
+    auto firstCurve = g->curve(0);
     // Get the minimum value of the first curve in this plot
-    double ymin = c->minYValue();
+    double ymin = firstCurve ? firstCurve->minYValue() : 0.0;
+    PlotCurve *c = dynamic_cast<PlotCurve*>(g->curve(0));
     if (index > 0 && c){
       d_x_offset = index*g->waterfallXOffset()*0.01*plot->canvas()->width()/(double)(curves - 1);
       d_y_offset = index*g->waterfallYOffset()*0.01*plot->canvas()->height()/(double)(curves - 1);
diff --git a/Code/Mantid/MantidPlot/src/PlotWizard.cpp b/Code/Mantid/MantidPlot/src/PlotWizard.cpp
index eb63b24f1483f0dd462573098b5809288b6db7a9..cc3f400806dec16c9f2ce327eaf15028c804faa6 100644
--- a/Code/Mantid/MantidPlot/src/PlotWizard.cpp
+++ b/Code/Mantid/MantidPlot/src/PlotWizard.cpp
@@ -44,7 +44,7 @@
 #include <QComboBox>
 
 PlotWizard::PlotWizard( QWidget* parent, Qt::WFlags fl )
-: QDialog( parent, fl )
+  : QDialog( parent, fl )
 {
 	setWindowTitle( tr("MantidPlot - Select Columns to Plot") );
 
diff --git a/Code/Mantid/MantidPlot/src/PlotWizard.h b/Code/Mantid/MantidPlot/src/PlotWizard.h
index a06457a08f73472eba4ca55b657b06b9db47a64e..82e10c86559879c1c59c27b091dfca900e2fd080 100644
--- a/Code/Mantid/MantidPlot/src/PlotWizard.h
+++ b/Code/Mantid/MantidPlot/src/PlotWizard.h
@@ -70,11 +70,7 @@ private:
 				//! Button "<->Z"
 				*buttonZ;
 				//! Button group defining the layout
-    QGroupBox*  groupBox1,
-				//! Button group defining the layout
-				*groupBox2,
-				//! Button group defining the layout
-				*groupBox3;
+    QGroupBox*  groupBox1;
 				//! Combo box to select the table
     QComboBox* boxTables;
 				//! List of the columns in the selected table
diff --git a/Code/Mantid/MantidPlot/src/PluginFit.cpp b/Code/Mantid/MantidPlot/src/PluginFit.cpp
index 7ca2fdbe6df82f93d1b97c2ba8e036374d4be53c..46e587ecb70e75fa2fdaaa304b51f36ad0bb084c 100644
--- a/Code/Mantid/MantidPlot/src/PluginFit.cpp
+++ b/Code/Mantid/MantidPlot/src/PluginFit.cpp
@@ -185,7 +185,8 @@ bool PluginFit::load(const QString& pluginName)
 
 void PluginFit::calculateFitCurveData(double *X, double *Y)
 {
-	if (d_gen_function && f_eval)
+  if (!f_eval) return;
+	if (d_gen_function)
 	{
 		double X0 = d_x[0];
 		double step = (d_x[d_n-1]-X0)/(d_points-1);
diff --git a/Code/Mantid/MantidPlot/src/PolynomFitDialog.cpp b/Code/Mantid/MantidPlot/src/PolynomFitDialog.cpp
index f1e19dc48096b0edbdc3adcb1ea3f9b4651a67fa..613b1c02dcf1a2b1df714cbc4fe85089af2340c8 100644
--- a/Code/Mantid/MantidPlot/src/PolynomFitDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/PolynomFitDialog.cpp
@@ -43,67 +43,67 @@
 #include <QComboBox>
 
 PolynomFitDialog::PolynomFitDialog( QWidget* parent, Qt::WFlags fl )
-: QDialog( parent, fl )
+  : QDialog( parent, fl ), graph(NULL)
 {
     setName( "PolynomFitDialog" );
-	setWindowTitle(tr("MantidPlot - Polynomial Fit Options"));
+    setWindowTitle(tr("MantidPlot - Polynomial Fit Options"));
     setSizeGripEnabled( true );
 
     QGroupBox *gb1 = new QGroupBox();
-	QGridLayout *gl1 = new QGridLayout(gb1);
-	gl1->addWidget(new QLabel(tr("Polynomial Fit of")), 0, 0);
+    QGridLayout *gl1 = new QGridLayout(gb1);
+    gl1->addWidget(new QLabel(tr("Polynomial Fit of")), 0, 0);
 
-	boxName = new QComboBox();
+    boxName = new QComboBox();
     gl1->addWidget(boxName, 0, 1);
 
     gl1->addWidget(new QLabel( tr("Order (1 - 9, 1 = linear)")), 1, 0);
-	boxOrder = new QSpinBox();
+    boxOrder = new QSpinBox();
     boxOrder->setRange(1, 9);
-	boxOrder->setValue(2);
+    boxOrder->setValue(2);
     gl1->addWidget(boxOrder, 1, 1);
 
     gl1->addWidget(new QLabel( tr("Fit curve # pts")), 2, 0);
-	boxPoints = new QSpinBox();
+    boxPoints = new QSpinBox();
     boxPoints->setRange(1, 1000);
     boxPoints->setSingleStep(50);
     boxPoints->setSpecialValueText(tr("Not enough points"));
     gl1->addWidget(boxPoints, 2, 1);
 
     gl1->addWidget(new QLabel( tr("Fit curve Xmin")), 3, 0);
-	boxStart = new QLineEdit(tr("0"));
+    boxStart = new QLineEdit(tr("0"));
     gl1->addWidget(boxStart, 3, 1);
 
-    gl1->addWidget(	new QLabel( tr("Fit curve Xmax")), 4, 0);
-	boxEnd = new QLineEdit();
+    gl1->addWidget(new QLabel( tr("Fit curve Xmax")), 4, 0);
+    boxEnd = new QLineEdit();
     gl1->addWidget(boxEnd, 4, 1);
 
     gl1->addWidget(new QLabel( tr("Color")), 5, 0);
-	boxColor = new ColorBox();
-	boxColor->setColor(QColor(Qt::red));
+    boxColor = new ColorBox();
+    boxColor->setColor(QColor(Qt::red));
     gl1->addWidget(boxColor, 5, 1);
 
-	boxShowFormula = new QCheckBox(tr( "Show Formula on Graph?" ));
-	boxShowFormula->setChecked( false );
+    boxShowFormula = new QCheckBox(tr( "Show Formula on Graph?" ));
+    boxShowFormula->setChecked( false );
     gl1->addWidget(boxShowFormula, 6, 1);
     gl1->setRowStretch(7, 1);
 
-	buttonFit = new QPushButton(tr( "&Fit" ));
-	buttonFit->setDefault( true );
+    buttonFit = new QPushButton(tr( "&Fit" ));
+    buttonFit->setDefault( true );
 
-	buttonCancel = new QPushButton(tr( "&Close" ));
+    buttonCancel = new QPushButton(tr( "&Close" ));
 
     QVBoxLayout* vl = new QVBoxLayout();
     vl->addWidget(buttonFit);
     vl->addWidget(buttonCancel);
     vl->addStretch();
 
-	QHBoxLayout* hlayout = new QHBoxLayout(this);
-	hlayout->addWidget(gb1);
-	hlayout->addLayout(vl);
+    QHBoxLayout* hlayout = new QHBoxLayout(this);
+    hlayout->addWidget(gb1);
+    hlayout->addLayout(vl);
 
-	connect( buttonFit, SIGNAL( clicked() ), this, SLOT( fit() ) );
-	connect( buttonCancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
-	connect( boxName, SIGNAL( activated(const QString&) ), this, SLOT(activateCurve(const QString&)));
+    connect( buttonFit, SIGNAL( clicked() ), this, SLOT( fit() ) );
+    connect( buttonCancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
+    connect( boxName, SIGNAL( activated(const QString&) ), this, SLOT(activateCurve(const QString&)));
 }
 
 void PolynomFitDialog::fit()
@@ -125,7 +125,7 @@ void PolynomFitDialog::fit()
     {
         fitter->setColor(boxColor->currentItem());
         fitter->setOutputPrecision(app->fit_output_precision);
-		fitter->generateFunction(app->generateUniformFitPoints, app->fitPoints);
+	fitter->generateFunction(app->generateUniformFitPoints, app->fitPoints);
         fitter->fit();
         delete fitter;
 	}
diff --git a/Code/Mantid/MantidPlot/src/QwtHistogram.cpp b/Code/Mantid/MantidPlot/src/QwtHistogram.cpp
index 95a803e7b8eef57f3dd24890af624dd2c9a4f6d9..f3e7373d1c5b501eb558df1d22acbb8649be46be 100644
--- a/Code/Mantid/MantidPlot/src/QwtHistogram.cpp
+++ b/Code/Mantid/MantidPlot/src/QwtHistogram.cpp
@@ -45,7 +45,7 @@ QwtHistogram::QwtHistogram(Table *t, const QString& xColName, const QString& nam
 
 QwtHistogram::QwtHistogram(Matrix *m)
   : QwtBarCurve(QwtBarCurve::Vertical, NULL, "matrix", (m != NULL ? m->objectName() : QString() ), 0, 0),
-    d_bin_size(0.0), d_begin(0.0), d_end(0.0),
+    d_matrix(NULL), d_autoBin(false), d_bin_size(0.0), d_begin(0.0), d_end(0.0),
     d_mean(0.0), d_standard_deviation(0.0), d_min(0.0), d_max(0.0)
 {
     if (m){
diff --git a/Code/Mantid/MantidPlot/src/RangeSelectorTool.cpp b/Code/Mantid/MantidPlot/src/RangeSelectorTool.cpp
index 96919116cda6b5243ce3842a8a66114ff6a2a3a8..1986a53a5984a9349f2c08976d10d09e6fb4d0b4 100644
--- a/Code/Mantid/MantidPlot/src/RangeSelectorTool.cpp
+++ b/Code/Mantid/MantidPlot/src/RangeSelectorTool.cpp
@@ -43,52 +43,53 @@
 
 RangeSelectorTool::RangeSelectorTool(Graph *graph, const QObject *status_target, const char *status_slot)
 	: QwtPlotPicker(graph->plotWidget()->canvas()),
-	PlotToolInterface(graph)
+          PlotToolInterface(graph), d_active_point(0), d_inactive_point(0), d_selected_curve(NULL),
+          d_enabled(false), d_visible(false)
 {
-	d_selected_curve = NULL;
-	for (int i=d_graph->curves(); i>=0; --i) {
-		d_selected_curve = d_graph->curve(i);
-		if (d_selected_curve && d_selected_curve->rtti() == QwtPlotItem::Rtti_PlotCurve
-				&& d_selected_curve->dataSize() > 0)
-			break;
-		d_selected_curve = NULL;
-	}
-	if (!d_selected_curve) {
-		QMessageBox::critical(d_graph, tr("MantidPlot - Warning"),
-				tr("All the curves on this plot are empty!"));
-		return;
-	}
-
-    d_enabled = true;
-	d_visible = true;
-	d_active_point = 0;
-	d_inactive_point = d_selected_curve->dataSize() - 1;
-	int marker_size = 20;
-
-	d_active_marker.setSymbol(QwtSymbol(QwtSymbol::Cross, QBrush(QColor(255,255,255,0)),//QBrush(QColor(255,255,0,128)),
-				QPen(Qt::red,2), QSize(marker_size,marker_size)));
-	d_active_marker.setLineStyle(QwtPlotMarker::VLine);
-	d_active_marker.setLinePen(QPen(Qt::red, 1, Qt::DashLine));
-	d_inactive_marker.setSymbol(QwtSymbol(QwtSymbol::Cross, QBrush(QColor(255,255,255,0)), //QBrush(QColor(255,255,0,128)),
-				QPen(Qt::black,2), QSize(marker_size,marker_size)));
-	d_inactive_marker.setLineStyle(QwtPlotMarker::VLine);
-	d_inactive_marker.setLinePen(QPen(Qt::black, 1, Qt::DashLine));
-	d_active_marker.setValue(d_selected_curve->x(d_active_point),
-			d_selected_curve->y(d_active_point));
-	d_inactive_marker.setValue(d_selected_curve->x(d_inactive_point),
-			d_selected_curve->y(d_inactive_point));
-	d_active_marker.attach(d_graph->plotWidget());
-	d_inactive_marker.attach(d_graph->plotWidget());
-
-	setTrackerMode(QwtPicker::AlwaysOn);
-	setSelectionFlags(QwtPicker::PointSelection | QwtPicker::ClickSelection);
-	d_graph->plotWidget()->canvas()->setCursor(QCursor(getQPixmap("vizor_xpm"), -1, -1));
-	d_graph->plotWidget()->canvas()->setFocus();
-	d_graph->plotWidget()->replot();
-
-	if (status_target)
-		connect(this, SIGNAL(statusText(const QString&)), status_target, status_slot);
-	emit statusText(tr("Click or use Ctrl+arrow key to select range (arrows select active cursor)!"));
+  d_selected_curve = NULL;
+  for (int i=d_graph->curves(); i>=0; --i) {
+    d_selected_curve = d_graph->curve(i);
+    if (d_selected_curve && d_selected_curve->rtti() == QwtPlotItem::Rtti_PlotCurve
+        && d_selected_curve->dataSize() > 0)
+      break;
+    d_selected_curve = NULL;
+  }
+  if (!d_selected_curve) {
+    QMessageBox::critical(d_graph, tr("MantidPlot - Warning"),
+                          tr("All the curves on this plot are empty!"));
+    return;
+  }
+
+  d_enabled = true;
+  d_visible = true;
+  d_active_point = 0;
+  d_inactive_point = d_selected_curve->dataSize() - 1;
+  int marker_size = 20;
+
+  d_active_marker.setSymbol(QwtSymbol(QwtSymbol::Cross, QBrush(QColor(255,255,255,0)),//QBrush(QColor(255,255,0,128)),
+                                      QPen(Qt::red,2), QSize(marker_size,marker_size)));
+  d_active_marker.setLineStyle(QwtPlotMarker::VLine);
+  d_active_marker.setLinePen(QPen(Qt::red, 1, Qt::DashLine));
+  d_inactive_marker.setSymbol(QwtSymbol(QwtSymbol::Cross, QBrush(QColor(255,255,255,0)), //QBrush(QColor(255,255,0,128)),
+                                        QPen(Qt::black,2), QSize(marker_size,marker_size)));
+  d_inactive_marker.setLineStyle(QwtPlotMarker::VLine);
+  d_inactive_marker.setLinePen(QPen(Qt::black, 1, Qt::DashLine));
+  d_active_marker.setValue(d_selected_curve->x(d_active_point),
+                           d_selected_curve->y(d_active_point));
+  d_inactive_marker.setValue(d_selected_curve->x(d_inactive_point),
+                             d_selected_curve->y(d_inactive_point));
+  d_active_marker.attach(d_graph->plotWidget());
+  d_inactive_marker.attach(d_graph->plotWidget());
+
+  setTrackerMode(QwtPicker::AlwaysOn);
+  setSelectionFlags(QwtPicker::PointSelection | QwtPicker::ClickSelection);
+  d_graph->plotWidget()->canvas()->setCursor(QCursor(getQPixmap("vizor_xpm"), -1, -1));
+  d_graph->plotWidget()->canvas()->setFocus();
+  d_graph->plotWidget()->replot();
+
+  if (status_target)
+    connect(this, SIGNAL(statusText(const QString&)), status_target, status_slot);
+  emit statusText(tr("Click or use Ctrl+arrow key to select range (arrows select active cursor)!"));
 }
 
 RangeSelectorTool::~RangeSelectorTool()
diff --git a/Code/Mantid/MantidPlot/src/RenameWindowDialog.cpp b/Code/Mantid/MantidPlot/src/RenameWindowDialog.cpp
index 4f70fe9fab23de924252ccc91fd37e816f3ed906..8a0361148bd7e4a476a7ddfe7031925a8542fb55 100644
--- a/Code/Mantid/MantidPlot/src/RenameWindowDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/RenameWindowDialog.cpp
@@ -44,52 +44,54 @@
 RenameWindowDialog::RenameWindowDialog(QWidget* parent, Qt::WFlags fl )
     : QDialog( parent, fl )
 {
-	setWindowTitle(tr("MantidPlot - Rename Window"));
-
-	QGridLayout * leftLayout = new QGridLayout();
-	QVBoxLayout * rightLayout = new QVBoxLayout();
-
-	groupBox1 = new QGroupBox(tr("Window Title"));
-	groupBox1->setLayout(leftLayout);
-
-	boxName = new QRadioButton(tr("&Name (single word)"));
-	leftLayout->addWidget(boxName, 0, 0);
-	boxNameLine = new QLineEdit();
-	leftLayout->addWidget(boxNameLine, 0, 1);
-	setFocusProxy(boxNameLine);
-
-	boxLabel = new QRadioButton(tr("&Label"));
-	leftLayout->addWidget(boxLabel, 2, 0);
-	boxLabelEdit = new QTextEdit();
-	leftLayout->addWidget(boxLabelEdit, 1, 1, 3, 1);
-	boxLabelEdit->setMaximumHeight(100);
-	boxLabelEdit->setMinimumHeight(100);
-
-	boxBoth = new QRadioButton(tr("&Both Name and Label"));
-	leftLayout->addWidget(boxBoth, 4, 0);
-
-	buttons = new QButtonGroup(this);
-	buttons->addButton(boxName);
-	buttons->addButton(boxLabel);
-	buttons->addButton(boxBoth);
-
-	buttonOk = new QPushButton(tr( "&OK" ));
-    buttonOk->setAutoDefault( true );
-    buttonOk->setDefault( true );
-	rightLayout->addWidget(buttonOk);
-
-    buttonCancel = new QPushButton(tr( "&Cancel" ));
-    buttonCancel->setAutoDefault( true );
-	rightLayout->addWidget(buttonCancel);
-	rightLayout->addStretch();
-
-	QHBoxLayout * mainLayout = new QHBoxLayout(this);
-    mainLayout->addWidget(groupBox1);
-	mainLayout->addLayout(rightLayout);
-
-    // signals and slots connections
-    connect( buttonOk, SIGNAL( clicked() ), this, SLOT( accept() ) );
-    connect( buttonCancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
+  setWindowTitle(tr("MantidPlot - Rename Window"));
+
+  QGridLayout * leftLayout = new QGridLayout();
+  QVBoxLayout * rightLayout = new QVBoxLayout();
+
+  groupBox1 = new QGroupBox(tr("Window Title"));
+  groupBox1->setLayout(leftLayout);
+
+  boxName = new QRadioButton(tr("&Name (single word)"));
+  leftLayout->addWidget(boxName, 0, 0);
+  boxNameLine = new QLineEdit();
+  leftLayout->addWidget(boxNameLine, 0, 1);
+  setFocusProxy(boxNameLine);
+
+  boxLabel = new QRadioButton(tr("&Label"));
+  leftLayout->addWidget(boxLabel, 2, 0);
+  boxLabelEdit = new QTextEdit();
+  leftLayout->addWidget(boxLabelEdit, 1, 1, 3, 1);
+  boxLabelEdit->setMaximumHeight(100);
+  boxLabelEdit->setMinimumHeight(100);
+
+  boxBoth = new QRadioButton(tr("&Both Name and Label"));
+  leftLayout->addWidget(boxBoth, 4, 0);
+
+  buttons = new QButtonGroup(this);
+  buttons->addButton(boxName);
+  buttons->addButton(boxLabel);
+  buttons->addButton(boxBoth);
+
+  buttonOk = new QPushButton(tr( "&OK" ));
+  buttonOk->setAutoDefault( true );
+  buttonOk->setDefault( true );
+  rightLayout->addWidget(buttonOk);
+
+  buttonCancel = new QPushButton(tr( "&Cancel" ));
+  buttonCancel->setAutoDefault( true );
+  rightLayout->addWidget(buttonCancel);
+  rightLayout->addStretch();
+
+  QHBoxLayout * mainLayout = new QHBoxLayout(this);
+  mainLayout->addWidget(groupBox1);
+  mainLayout->addLayout(rightLayout);
+
+  window = NULL;
+
+  // signals and slots connections
+  connect( buttonOk, SIGNAL( clicked() ), this, SLOT( accept() ) );
+  connect( buttonCancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
 }
 
 void RenameWindowDialog::setWidget(MdiSubWindow *w)
diff --git a/Code/Mantid/MantidPlot/src/ScaleDetails.cpp b/Code/Mantid/MantidPlot/src/ScaleDetails.cpp
index 2cb2be79effc9143f448c404eee202895e0d759f..b8cccc31ba3f325b33a0ac633d2dbf914ddf0415 100644
--- a/Code/Mantid/MantidPlot/src/ScaleDetails.cpp
+++ b/Code/Mantid/MantidPlot/src/ScaleDetails.cpp
@@ -282,29 +282,30 @@ void ScaleDetails::initWidgets()
     }
     else if (type == ScaleDraw::Time)
     {
-      ScaleDraw *sclDraw = dynamic_cast<ScaleDraw *>(d_plot->axisScaleDraw(m_mappedaxis));
-      QTime origin = sclDraw->dateTimeOrigin().time();
-
-      m_dspnStart->hide();
-      m_dteStartDateTime->hide();
-      m_timStartTime->show();
-      m_timStartTime->setDisplayFormat(sclDraw->format());
-      m_timStartTime->setTime(origin.addMSecs((int) start));
-
-      m_dspnEnd->hide();
-      m_dteEndDateTime->hide();
-      m_timEndTime->show();
-      m_timEndTime->setDisplayFormat(sclDraw->format());
-      m_timEndTime->setTime(origin.addMSecs((int) end));
-
-      m_cmbUnit->show();
-      m_cmbUnit->insertItem(tr("millisec."));
-      m_cmbUnit->insertItem(tr("sec."));
-      m_cmbUnit->insertItem(tr("min."));
-      m_cmbUnit->insertItem(tr("hours"));
-      m_cmbUnit->setCurrentIndex(1);
-      m_dspnStep->setValue(m_graph->axisStep(m_mappedaxis) / 1e3);
-      m_dspnStep->setSingleStep(1000);
+      if (ScaleDraw *sclDraw = dynamic_cast<ScaleDraw *>(d_plot->axisScaleDraw(m_mappedaxis))) {
+        QTime origin = sclDraw->dateTimeOrigin().time();
+
+        m_dspnStart->hide();
+        m_dteStartDateTime->hide();
+        m_timStartTime->show();
+        m_timStartTime->setDisplayFormat(sclDraw->format());
+        m_timStartTime->setTime(origin.addMSecs((int) start));
+
+        m_dspnEnd->hide();
+        m_dteEndDateTime->hide();
+        m_timEndTime->show();
+        m_timEndTime->setDisplayFormat(sclDraw->format());
+        m_timEndTime->setTime(origin.addMSecs((int) end));
+
+        m_cmbUnit->show();
+        m_cmbUnit->insertItem(tr("millisec."));
+        m_cmbUnit->insertItem(tr("sec."));
+        m_cmbUnit->insertItem(tr("min."));
+        m_cmbUnit->insertItem(tr("hours"));
+        m_cmbUnit->setCurrentIndex(1);
+        m_dspnStep->setValue(m_graph->axisStep(m_mappedaxis) / 1e3);
+        m_dspnStep->setSingleStep(1000);
+      }
     }
     else
     {
diff --git a/Code/Mantid/MantidPlot/src/SmoothCurveDialog.cpp b/Code/Mantid/MantidPlot/src/SmoothCurveDialog.cpp
index dcd07cede7cfe10d419fff446321982f8d43cc32..0d4b6d6c1772896a778f8397e69b6ab2b13ee881 100644
--- a/Code/Mantid/MantidPlot/src/SmoothCurveDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/SmoothCurveDialog.cpp
@@ -42,78 +42,79 @@
 #include <QLayout>
 
 SmoothCurveDialog::SmoothCurveDialog(int method, QWidget* parent, Qt::WFlags fl )
-    : QDialog( parent, fl )
+  : QDialog( parent, fl ), graph(NULL), boxPointsLeft(NULL), boxPointsRight(NULL),
+    boxOrder(NULL)
 {
-	smooth_method = method;
-
-    setName( "SmoothCurveDialog" );
-	setWindowTitle(tr("MantidPlot - Smoothing Options"));
-
-    QGroupBox *gb1 = new QGroupBox();
-    QGridLayout *gl1 = new QGridLayout(gb1);
-	gl1->addWidget(new QLabel(tr("Curve")), 0, 0);
-
-    boxName = new QComboBox();
-	gl1->addWidget(boxName, 0, 1);
-
-	boxColor = new ColorBox();
-	boxColor->setColor(QColor(Qt::red));
-
-	if (method == SmoothFilter::SavitzkyGolay)
-		{
-        gl1->addWidget(new QLabel(tr("Polynomial Order")), 1, 0);
-		boxOrder = new QSpinBox();
-		boxOrder->setRange(0, 9);
-		boxOrder->setValue(2);
-		gl1->addWidget(boxOrder, 1, 1);
-
-		gl1->addWidget(new QLabel(tr("Points to the Left")), 2, 0);
-		boxPointsLeft = new QSpinBox();
-		boxPointsLeft->setRange(1, 25);
-		boxPointsLeft->setValue(2);
-		gl1->addWidget(boxPointsLeft, 2, 1);
-
-		gl1->addWidget(new QLabel(tr("Points to the Right")), 3, 0);
-		boxPointsRight = new QSpinBox();
-		boxPointsRight->setRange(1, 25);
-		boxPointsRight->setValue(2);
-		gl1->addWidget(boxPointsRight, 3, 1);
-
-		gl1->addWidget(new QLabel(tr("Color")), 4, 0);
-		gl1->addWidget(boxColor, 4, 1);
-        gl1->setRowStretch(5, 1);
-		}
-	else
-		{
-		gl1->addWidget(new QLabel(tr("Points")), 1, 0);
-		boxPointsLeft = new QSpinBox();
-		boxPointsLeft->setRange(1, 1000000);
-		boxPointsLeft->setSingleStep(10);
-		boxPointsLeft->setValue(5);
-		gl1->addWidget(boxPointsLeft, 1, 1);
-
-		gl1->addWidget(new QLabel(tr("Color")), 2, 0);
-		gl1->addWidget(boxColor, 2, 1);
-        gl1->setRowStretch(3, 1);
-		}
-    gl1->setColStretch(2, 1);
-
-	btnSmooth = new QPushButton(tr( "&Smooth" ));
-    btnSmooth->setDefault(true);
-    buttonCancel = new QPushButton(tr( "&Close" ));
-
-	QVBoxLayout *vl = new QVBoxLayout();
- 	vl->addWidget(btnSmooth);
-	vl->addWidget(buttonCancel);
-    vl->addStretch();
-
-    QHBoxLayout *hb = new QHBoxLayout(this);
-    hb->addWidget(gb1);
-    hb->addLayout(vl);
-
-	connect( btnSmooth, SIGNAL(clicked()), this, SLOT( smooth()));
-    connect( buttonCancel, SIGNAL(clicked()), this, SLOT( reject()));
-	connect( boxName, SIGNAL(activated(const QString&)), this, SLOT(activateCurve(const QString&)));
+  smooth_method = method;
+
+  setName( "SmoothCurveDialog" );
+  setWindowTitle(tr("MantidPlot - Smoothing Options"));
+
+  QGroupBox *gb1 = new QGroupBox();
+  QGridLayout *gl1 = new QGridLayout(gb1);
+  gl1->addWidget(new QLabel(tr("Curve")), 0, 0);
+
+  boxName = new QComboBox();
+  gl1->addWidget(boxName, 0, 1);
+
+  boxColor = new ColorBox();
+  boxColor->setColor(QColor(Qt::red));
+
+  if (method == SmoothFilter::SavitzkyGolay)
+  {
+      gl1->addWidget(new QLabel(tr("Polynomial Order")), 1, 0);
+      boxOrder = new QSpinBox();
+      boxOrder->setRange(0, 9);
+      boxOrder->setValue(2);
+      gl1->addWidget(boxOrder, 1, 1);
+
+      gl1->addWidget(new QLabel(tr("Points to the Left")), 2, 0);
+      boxPointsLeft = new QSpinBox();
+      boxPointsLeft->setRange(1, 25);
+      boxPointsLeft->setValue(2);
+      gl1->addWidget(boxPointsLeft, 2, 1);
+
+      gl1->addWidget(new QLabel(tr("Points to the Right")), 3, 0);
+      boxPointsRight = new QSpinBox();
+      boxPointsRight->setRange(1, 25);
+      boxPointsRight->setValue(2);
+      gl1->addWidget(boxPointsRight, 3, 1);
+
+      gl1->addWidget(new QLabel(tr("Color")), 4, 0);
+      gl1->addWidget(boxColor, 4, 1);
+      gl1->setRowStretch(5, 1);
+  }
+  else
+  {
+      gl1->addWidget(new QLabel(tr("Points")), 1, 0);
+      boxPointsLeft = new QSpinBox();
+      boxPointsLeft->setRange(1, 1000000);
+      boxPointsLeft->setSingleStep(10);
+      boxPointsLeft->setValue(5);
+      gl1->addWidget(boxPointsLeft, 1, 1);
+
+      gl1->addWidget(new QLabel(tr("Color")), 2, 0);
+      gl1->addWidget(boxColor, 2, 1);
+      gl1->setRowStretch(3, 1);
+  }
+  gl1->setColStretch(2, 1);
+
+  btnSmooth = new QPushButton(tr( "&Smooth" ));
+  btnSmooth->setDefault(true);
+  buttonCancel = new QPushButton(tr( "&Close" ));
+
+  QVBoxLayout *vl = new QVBoxLayout();
+  vl->addWidget(btnSmooth);
+  vl->addWidget(buttonCancel);
+  vl->addStretch();
+
+  QHBoxLayout *hb = new QHBoxLayout(this);
+  hb->addWidget(gb1);
+  hb->addLayout(vl);
+
+  connect( btnSmooth, SIGNAL(clicked()), this, SLOT( smooth()));
+  connect( buttonCancel, SIGNAL(clicked()), this, SLOT( reject()));
+  connect( boxName, SIGNAL(activated(const QString&)), this, SLOT(activateCurve(const QString&)));
 }
 
 void SmoothCurveDialog::smooth()
diff --git a/Code/Mantid/MantidPlot/src/SortDialog.h b/Code/Mantid/MantidPlot/src/SortDialog.h
index f689bd0731752c46965970b62315309ffdb4d245..029207cd77181ca88e872d654d401ddc3bfbcb37 100644
--- a/Code/Mantid/MantidPlot/src/SortDialog.h
+++ b/Code/Mantid/MantidPlot/src/SortDialog.h
@@ -53,7 +53,6 @@ signals:
 private:
   QPushButton* buttonOk;
   QPushButton* buttonCancel;
-  QPushButton* buttonHelp;
   QComboBox* boxType;
   QComboBox* boxOrder;
   QComboBox *columnsList;
diff --git a/Code/Mantid/MantidPlot/src/TextDialog.cpp b/Code/Mantid/MantidPlot/src/TextDialog.cpp
index a5e996dbfa0c06752e281ba994943bc1f648f165..892e50fdde1549a1099d29639b8a88c9b9e8cc5b 100644
--- a/Code/Mantid/MantidPlot/src/TextDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/TextDialog.cpp
@@ -48,7 +48,7 @@
 #include <qwt_scale_widget.h>
 
 TextDialog::TextDialog(TextType type, QWidget* parent, Qt::WFlags fl)
-	: QDialog( parent, fl)
+  : QDialog( parent, fl)
 {
 	setAttribute(Qt::WA_DeleteOnClose);
 	setWindowTitle( tr( "MantidPlot - Text options" ) );
@@ -82,6 +82,7 @@ TextDialog::TextDialog(TextType type, QWidget* parent, Qt::WFlags fl)
 	buttonApply->setDefault( true );
 	topLayout->addWidget( buttonApply, 1, 3 );
 
+        alignmentBox = NULL;
 	if (textType != TextDialog::TextMarker){
 		topLayout->addWidget(new QLabel(tr("Alignment")), 2, 0);
 		alignmentBox = new QComboBox();
diff --git a/Code/Mantid/MantidPlot/src/TextDialog.h b/Code/Mantid/MantidPlot/src/TextDialog.h
index 6d47dcd843d731f563b7168886931c1a581aca63..5d1fe4ca9440e6188691ab64b55801cf5e89e076 100644
--- a/Code/Mantid/MantidPlot/src/TextDialog.h
+++ b/Code/Mantid/MantidPlot/src/TextDialog.h
@@ -109,9 +109,8 @@ protected:
 	QPushButton *buttonCancel;
 	QPushButton *buttonApply;
 	QPushButton *buttonDefault;
-	QComboBox *rotateBox;
 	QTextEdit *textEditBox;
-	QGroupBox *groupBox1, *groupBox2;
+	QGroupBox *groupBox1;
 	QComboBox *alignmentBox;
 	TextFormatButtons *formatButtons;
 	QSpinBox *boxBackgroundTransparency;
diff --git a/Code/Mantid/MantidPlot/src/TextEditor.cpp b/Code/Mantid/MantidPlot/src/TextEditor.cpp
index 5d805941f1edad45166bd3b0f7cb03274bf60cee..255ca9be48dd437e097283ac14006a137db5c844 100644
--- a/Code/Mantid/MantidPlot/src/TextEditor.cpp
+++ b/Code/Mantid/MantidPlot/src/TextEditor.cpp
@@ -53,7 +53,8 @@ TextEditor::TextEditor(Graph *g): QTextEdit(g), d_target(NULL)
 	if (g->selectedText()){
 		d_target = g->selectedText();
 		setGeometry(d_target->geometry());
-		text = dynamic_cast<LegendWidget*>(d_target)->text();
+    auto legend = dynamic_cast<LegendWidget*>(d_target);
+		text = legend ? legend->text() : "";
 		d_target->hide();
 	} else if (g->titleSelected()){
 		d_target = g->plotWidget()->titleLabel();
@@ -104,38 +105,40 @@ void TextEditor::closeEvent(QCloseEvent *e)
   if(d_target != NULL)
   {
     Graph *g = dynamic_cast<Graph *>(parent());
-    QString s = QString();
-    if (d_target->isA("LegendWidget")){
-      s = text();
-      dynamic_cast<LegendWidget*>(d_target)->setText(s);
-      d_target->show();
-      g->setSelectedText(NULL);
-    } else if (d_target->isA("PieLabel")){
-      s = text();
-      dynamic_cast<PieLabel*>(d_target)->setCustomText(s);
-      d_target->show();
-      g->setSelectedText(NULL);
-    } else if (d_target->isA("QwtTextLabel")){
-      QwtText title = g->plotWidget()->title();
-      s = text();
-      if(s.isEmpty())
-        s = " ";
-      title.setText(s);			
-      g->plotWidget()->setTitle(title);
-    } else if (d_target->isA("QwtScaleWidget")){
-      QwtScaleWidget *scale = (QwtScaleWidget*)d_target;
-      QwtText title = scale->title();
-      s = text();
-      if(s.isEmpty())
-        s = " ";
-      title.setText(s);
-      scale->setTitle(title);
+    if (g) {
+      QString s = QString();
+      if (auto legend = dynamic_cast<LegendWidget*>(d_target)){
+        s = text();
+        legend->setText(s);
+        d_target->show();
+        g->setSelectedText(NULL);
+      } else if (auto pieLabel = dynamic_cast<PieLabel*>(d_target)){
+        s = text();
+        pieLabel->setCustomText(s);
+        d_target->show();
+        g->setSelectedText(NULL);
+      } else if (d_target->isA("QwtTextLabel")){
+        QwtText title = g->plotWidget()->title();
+        s = text();
+        if(s.isEmpty())
+          s = " ";
+        title.setText(s);			
+        g->plotWidget()->setTitle(title);
+      } else if (d_target->isA("QwtScaleWidget")){
+        QwtScaleWidget *scale = (QwtScaleWidget*)d_target;
+        QwtText title = scale->title();
+        s = text();
+        if(s.isEmpty())
+          s = " ";
+        title.setText(s);
+        scale->setTitle(title);
+      }
+
+      if (d_initial_text != s)
+        g->notifyChanges();
+
+      d_target->repaint();
     }
-
-    if (d_initial_text != s)
-      g->notifyChanges();
-
-    d_target->repaint();
   }
   e->accept();
 }
diff --git a/Code/Mantid/MantidPlot/src/TranslateCurveTool.cpp b/Code/Mantid/MantidPlot/src/TranslateCurveTool.cpp
index 03e984972fb189637b5e0bb93053135b6e78e358..c9607a648dfabb87983a65583aad273c93c73a6e 100644
--- a/Code/Mantid/MantidPlot/src/TranslateCurveTool.cpp
+++ b/Code/Mantid/MantidPlot/src/TranslateCurveTool.cpp
@@ -44,6 +44,9 @@
 TranslateCurveTool::TranslateCurveTool(Graph *graph, ApplicationWindow *app, Direction dir, const QObject *status_target, const char *status_slot)
 	: PlotToolInterface(graph),
 	d_dir(dir),
+        d_sub_tool(NULL),
+        d_selected_curve(NULL),
+        d_curve_point(),
 	d_app(app)
 {
 	if (status_target)
@@ -60,29 +63,37 @@ TranslateCurveTool::TranslateCurveTool(Graph *graph, ApplicationWindow *app, Dir
 
 void TranslateCurveTool::selectCurvePoint(QwtPlotCurve *curve, int point_index)
 {
-  if (!d_sub_tool) return;
-	if(dynamic_cast<PlotCurve *>(curve)->type() != Graph::Function){
-		DataCurve *c = dynamic_cast<DataCurve *>(curve);
-		Table *t = c->table();
-		if (!t)
-			return;
-		
-	    if (d_dir == Horizontal && t->isReadOnlyColumn(t->colIndex(c->xColumnName()))){
-            QMessageBox::warning(d_app, tr("MantidPlot - Warning"),
-            tr("The column '%1' is read-only! Operation aborted!").arg(c->xColumnName()));
-			delete d_sub_tool;
-			d_graph->setActiveTool(NULL);
-			return;
-        } else if (d_dir == Vertical && t->isReadOnlyColumn(t->colIndex(c->title().text()))){
-            QMessageBox::warning(d_app, tr("MantidPlot - Warning"),
-            tr("The column '%1' is read-only! Operation aborted!").arg(c->title().text()));
-			delete d_sub_tool;
-			d_graph->setActiveTool(NULL);
-			return;
-        } 
-	}
-		
-	d_selected_curve = curve;
+  if (!d_sub_tool)
+    return;
+  DataCurve *c = dynamic_cast<DataCurve *>(curve);
+  if (c && c->type() != Graph::Function) {
+    
+    Table *t = c->table();
+    if (!t)
+      return;
+
+    if (d_dir == Horizontal &&
+        t->isReadOnlyColumn(t->colIndex(c->xColumnName()))) {
+      QMessageBox::warning(
+          d_app, tr("MantidPlot - Warning"),
+          tr("The column '%1' is read-only! Operation aborted!")
+              .arg(c->xColumnName()));
+      delete d_sub_tool;
+      d_graph->setActiveTool(NULL);
+      return;
+    } else if (d_dir == Vertical &&
+               t->isReadOnlyColumn(t->colIndex(c->title().text()))) {
+      QMessageBox::warning(
+          d_app, tr("MantidPlot - Warning"),
+          tr("The column '%1' is read-only! Operation aborted!")
+              .arg(c->title().text()));
+      delete d_sub_tool;
+      d_graph->setActiveTool(NULL);
+      return;
+    }
+  }
+
+  d_selected_curve = curve;
 	d_curve_point = QwtDoublePoint(curve->x(point_index), curve->y(point_index));
 	delete d_sub_tool;
 
@@ -101,12 +112,12 @@ void TranslateCurveTool::selectDestination(const QwtDoublePoint &point)
 
 	// Phase 3: execute the translation
 
-	if(dynamic_cast<PlotCurve *>(d_selected_curve)->type() == Graph::Function){
+	if(auto c = dynamic_cast<PlotCurve *>(d_selected_curve)){
+    if (c->type() == Graph::Function) {
 	    if (d_dir == Horizontal){
             QMessageBox::warning(d_app, tr("MantidPlot - Warning"),
             tr("This operation cannot be performed on function curves."));
-        } else {
-            FunctionCurve *func = dynamic_cast<FunctionCurve *>(d_selected_curve);
+        } else if (FunctionCurve *func = dynamic_cast<FunctionCurve *>(d_selected_curve)) {
             if (func->functionType() == FunctionCurve::Normal){
                 QString formula = func->formulas().first();
                 double d = point.y() - d_curve_point.y();
@@ -119,9 +130,9 @@ void TranslateCurveTool::selectDestination(const QwtDoublePoint &point)
         }
 	    d_graph->setActiveTool(NULL);
 	    return;
-    } else {
-      DataCurve *c = dynamic_cast<DataCurve *>(d_selected_curve);
-        double d;
+    }
+  } else if (DataCurve *c = dynamic_cast<DataCurve *>(d_selected_curve)) {
+    double d;
 		QString col_name;
 		switch(d_dir) {
 			case Vertical:
diff --git a/Code/Mantid/MantidPlot/src/VectorCurve.cpp b/Code/Mantid/MantidPlot/src/VectorCurve.cpp
index 524a47f8fcde9d4337462f76db703ffe369f5e8d..3d2d5b9424b8612b8688501e74cb8942d39202b6 100644
--- a/Code/Mantid/MantidPlot/src/VectorCurve.cpp
+++ b/Code/Mantid/MantidPlot/src/VectorCurve.cpp
@@ -35,14 +35,15 @@
 VectorCurve::VectorCurve(VectorStyle style, Table *t, const QString& xColName, const char *name,
 				const QString& endCol1, const QString& endCol2, int startRow, int endRow):
     DataCurve(t, xColName, name, startRow, endRow),
-	pen(QPen(Qt::black, 1, Qt::SolidLine)),
-	filledArrow (true),
-	d_style (style),
-	d_headLength (4),
-	d_headAngle (45),
-	d_position (Tail),
-	d_end_x_a (endCol1),
-	d_end_y_m (endCol2)
+    vectorEnd(NULL),
+    pen(QPen(Qt::black, 1, Qt::SolidLine)),
+    filledArrow(true),
+    d_style(style),
+    d_headLength(4),
+    d_headAngle(45),
+    d_position(Tail),
+    d_end_x_a(endCol1),
+    d_end_y_m(endCol2)
 {
 	if (style == XYXY)
 		setType(Graph::VectXYXY);
diff --git a/Code/Mantid/MantidPlot/src/lib/3rdparty/qtcolorpicker/src/qtcolorpicker.cpp b/Code/Mantid/MantidPlot/src/lib/3rdparty/qtcolorpicker/src/qtcolorpicker.cpp
index f354805621b82d51c662102841fe21275adee948..3e1bf061c9b3c3a8190edf4e0eecb76b05720871 100644
--- a/Code/Mantid/MantidPlot/src/lib/3rdparty/qtcolorpicker/src/qtcolorpicker.cpp
+++ b/Code/Mantid/MantidPlot/src/lib/3rdparty/qtcolorpicker/src/qtcolorpicker.cpp
@@ -436,20 +436,22 @@ void QtColorPicker::setCurrentColor(const QColor &color)
 
     ColorPickerItem *item = popup->find(color);
     if (!item) {
-	insertColor(color, tr("Custom"));
-	item = popup->find(color);
+      insertColor(color, tr("Custom"));
+      item = popup->find(color);
     }
 
-    col = color;
-    setText(item->text());
+    if (item) {
+      col = color;
+      setText(item->text());
 
-    dirty = true;
+      dirty = true;
 
-    popup->hide();
-    repaint();
+      popup->hide();
+      repaint();
 
-    item->setSelected(true);
-    emit colorChanged(color);
+      item->setSelected(true);
+      emit colorChanged(color);
+    }
 }
 
 /*!
@@ -670,8 +672,10 @@ void ColorPickerPopup::updateSelected()
 
   if (sender() && sender()->inherits("ColorPickerItem")) {
     ColorPickerItem *item = dynamic_cast<ColorPickerItem *>(sender());
-    lastSel = item->color();
-    emit selected(item->color());
+    if (item) {
+      lastSel = item->color();
+      emit selected(item->color());
+    }
   }
 
   hide();
diff --git a/Code/Mantid/MantidPlot/src/lib/src/ExtensibleFileDialog.cpp b/Code/Mantid/MantidPlot/src/lib/src/ExtensibleFileDialog.cpp
index 13a0d24b96aa13f963f3db3d7a2eabaaebecd0ab..ddd056c17655921a2c3d93ab4d21cb0cccf47a0b 100644
--- a/Code/Mantid/MantidPlot/src/lib/src/ExtensibleFileDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/lib/src/ExtensibleFileDialog.cpp
@@ -38,6 +38,7 @@ ExtensibleFileDialog::ExtensibleFileDialog(QWidget *parent, bool extended, Qt::W
   : QFileDialog(parent, flags)
 {
   d_extension = 0;
+  d_extension_row = 0;
 
   d_extension_toggle = new QPushButton();
   d_extension_toggle->setCheckable(true);
diff --git a/Code/Mantid/MantidPlot/src/origin/OPJFile.h b/Code/Mantid/MantidPlot/src/origin/OPJFile.h
index 6b2d13738ab4e4c90e92b25f68d7b22b9c7c6780..7f4f529ad2930f7b4f87b3e496087b44ff50599e 100644
--- a/Code/Mantid/MantidPlot/src/origin/OPJFile.h
+++ b/Code/Mantid/MantidPlot/src/origin/OPJFile.h
@@ -85,6 +85,7 @@ struct originWindow {
 	originWindow(std::string _name="", std::string _label="", bool _bHidden=false)
 	:	name(_name)
 	,	label(_label)
+	,	objectID(0)
 	,	bHidden(_bHidden)
 	,	state(Normal)
 	,	title(Both)
@@ -144,10 +145,12 @@ struct spreadSheet : public originWindow {
 	bool bMultisheet;
 	std::vector <spreadColumn> column;
 	spreadSheet(std::string _name="")
-	:	originWindow(_name)
+        :	originWindow(_name)
+        ,	maxRows(0)
 	,	bLoose(true)
 	,	bMultisheet(false)
-	{};
+	,	column()          
+        {};
 };
 
 struct excel : public originWindow {
@@ -178,7 +181,9 @@ struct matrix : public originWindow {
 	HeaderViewType header;
 	std::vector <double> data;
 	matrix(std::string _name="", int _index=0)
-	:	originWindow(_name)
+        :	originWindow(_name)
+        ,       nr_rows(0)
+        ,       nr_cols(0)
 	,	value_type_specification(0)
 	,	significant_digits(6)
 	,	decimal_places(6)
@@ -223,7 +228,15 @@ struct text {
 
 	text(const std::string& _txt="")
 		:	txt(_txt)
-	{};
+		,	clientRect()
+                ,	color(0)
+                ,	fontsize(0)
+                ,	rotation(0)
+                ,	tab(0)
+                ,	border_type(0)
+                ,	attach(0)
+        {};
+
 	text(const std::string& _txt, const rect& _clientRect, int _color, int _fontsize, int _rotation, int _tab, int _border_type, int _attach)
 		:	txt(_txt)
 		,	clientRect(_clientRect)
@@ -256,13 +269,21 @@ struct pieProperties
 	unsigned short distance;
 
 	pieProperties()
-	:	clockwise_rotation(false)
+	:	view_angle(0)
+	,	thickness(0)
+	,	clockwise_rotation(false)
+	,	rotation(0)
+	,	radius(0)
+	,	horizontal_offset(0)
+	,	displaced_sections(0)
+	,	displacement(0)
 	,	format_automatic(false)
 	,	format_values(false)
 	,	format_percentages(false)
 	,	format_categories(false)
 	,	position_associate(false)
-	{};
+	,	distance(0)
+        {};
 };
 
 struct vectorProperties
@@ -283,11 +304,19 @@ struct vectorProperties
 	int const_magnitude;
 
 	vectorProperties()
-	:	arrow_closed(false)
-	,	position(0)
-	,	multiplier(1.0)
-	,	const_angle(0)
-	,	const_magnitude(0)
+        :	color(0)
+        ,	width(0.0)
+        ,	arrow_lenght(0)
+        ,	arrow_angle(0)
+        ,	arrow_closed(false)
+        ,	endXColName()
+        ,	endYColName()
+        ,	position(0)
+        ,	angleColName()
+        ,	magnitudeColName(0)
+        ,	multiplier(1.0)
+        ,	const_angle(0)
+        ,	const_magnitude(0)
 	{};
 };
 
@@ -343,7 +372,15 @@ struct graphAxisBreak {
 	unsigned char minor_ticks_after;
 
 	graphAxisBreak()
-	:	show(false)
+	:   show(false)
+          , log10(false)
+          , from(0.0)
+          , to(0.0)
+          , position(0)
+          , scale_increment_before(0)
+          , scale_increment_after(0)
+          , minor_ticks_before(0)
+          , minor_ticks_after(0)
 	{
 	}
 };
@@ -484,7 +521,9 @@ struct graph : public originWindow {
 
 	graph(std::string _name="")
 	:	originWindow(_name)
-	{};
+        ,	width(0)
+        ,	height(0)
+        {};
 };
 
 struct note : public originWindow {
diff --git a/Code/Mantid/MantidQt/API/inc/MantidQtAPI/InterfaceManager.h b/Code/Mantid/MantidQt/API/inc/MantidQtAPI/InterfaceManager.h
index d864c1f1fa6125a9437835c71ef99dbbf0da18f6..b86e753ec4f83b4bae4526373638601f4416e2af 100644
--- a/Code/Mantid/MantidQt/API/inc/MantidQtAPI/InterfaceManager.h
+++ b/Code/Mantid/MantidQt/API/inc/MantidQtAPI/InterfaceManager.h
@@ -109,6 +109,26 @@ public:
    * @return the help window
    */
   MantidHelpInterface *createHelpWindow() const;
+
+  /// @param url Relative URL of help page to show.
+  void showHelpPage(const QString &url = QString());
+
+  /// @param page Wiki page to show help for
+  void showWikiPage(const QString &page = QString());
+
+  /// @param name of algorithm to show help for
+  /// @param version of algorithm
+  void showAlgorithmHelp(const QString &name, const int version = -1);
+
+  /// @param name of concept to show help for
+  void showConceptHelp(const QString &name);
+
+  /// @param name of fit function to show help for
+  void showFitFunctionHelp(const QString &name = QString());
+
+  /// @param name of interface to show help for
+  void showCustomInterfaceHelp(const QString &name);
+
   /**
    * Registration function for the help window factory.
    * @param factory the factory instance
diff --git a/Code/Mantid/MantidQt/API/inc/MantidQtAPI/MantidHelpInterface.h b/Code/Mantid/MantidQt/API/inc/MantidQtAPI/MantidHelpInterface.h
index e5d69ed02069b90e86f4d996f0c3490b6bb6612e..c7f4da234a5eff40811453664345256d584c6635 100644
--- a/Code/Mantid/MantidQt/API/inc/MantidQtAPI/MantidHelpInterface.h
+++ b/Code/Mantid/MantidQt/API/inc/MantidQtAPI/MantidHelpInterface.h
@@ -51,11 +51,13 @@ public:
   virtual void showPage(const QString & url);
   virtual void showPage(const QUrl & url);
   virtual void showWikiPage(const std::string &page=std::string());
+  virtual void showWikiPage(const QString &page);
   virtual void showAlgorithm(const std::string &name=std::string(), const int version=-1);
   virtual void showAlgorithm(const QString &name, const int version=-1);
   virtual void showConcept(const std::string &name);
   virtual void showConcept(const QString &name);
   virtual void showFitFunction(const std::string &name=std::string());
+  virtual void showFitFunction(const QString &name);
   virtual void showCustomInterface(const std::string &name);
   virtual void showCustomInterface(const QString &name);
 
diff --git a/Code/Mantid/MantidQt/API/src/InterfaceManager.cpp b/Code/Mantid/MantidQt/API/src/InterfaceManager.cpp
index 45047ac64bcb84ad1cbbedf8c648d30ea8012b88..9bba267c27daf9362ab6344cc4508745b45ec889 100644
--- a/Code/Mantid/MantidQt/API/src/InterfaceManager.cpp
+++ b/Code/Mantid/MantidQt/API/src/InterfaceManager.cpp
@@ -245,3 +245,34 @@ MantidHelpInterface *InterfaceManager::createHelpWindow() const
     return interface;
   }
 }
+
+void InterfaceManager::showHelpPage(const QString &url) {
+  auto window = createHelpWindow();
+  window->showPage(url);
+}
+
+void InterfaceManager::showWikiPage(const QString &page) {
+  auto window = createHelpWindow();
+  window->showWikiPage(page);
+}
+
+void InterfaceManager::showAlgorithmHelp(const QString &name,
+                                         const int version) {
+  auto window = createHelpWindow();
+  window->showAlgorithm(name, version);
+}
+
+void InterfaceManager::showConceptHelp(const QString &name) {
+  auto window = createHelpWindow();
+  window->showConcept(name);
+}
+
+void InterfaceManager::showFitFunctionHelp(const QString &name) {
+  auto window = createHelpWindow();
+  window->showFitFunction(name);
+}
+
+void InterfaceManager::showCustomInterfaceHelp(const QString &name) {
+  auto window = createHelpWindow();
+  window->showCustomInterface(name);
+}
diff --git a/Code/Mantid/MantidQt/API/src/MantidHelpInterface.cpp b/Code/Mantid/MantidQt/API/src/MantidHelpInterface.cpp
index 52fafb2673819e96a4ea6e05c16b4a6d8e761828..c5d67b0569f1ded10fa2a60a33e6df3da56d4325 100644
--- a/Code/Mantid/MantidQt/API/src/MantidHelpInterface.cpp
+++ b/Code/Mantid/MantidQt/API/src/MantidHelpInterface.cpp
@@ -31,6 +31,11 @@ void MantidHelpInterface::showWikiPage(const std::string &page)
   UNUSED_ARG(page);
 }
 
+void MantidHelpInterface::showWikiPage(const QString &page)
+{
+  UNUSED_ARG(page);
+}
+
 void MantidHelpInterface::showConcept(const std::string &page)
 {
   UNUSED_ARG(page);
@@ -57,6 +62,11 @@ void MantidHelpInterface::showFitFunction(const std::string &name)
   UNUSED_ARG(name);
 }
 
+void MantidHelpInterface::showFitFunction(const QString &name)
+{
+  UNUSED_ARG(name);
+}
+
 void MantidHelpInterface::showCustomInterface(const std::string &name)
 {
   UNUSED_ARG(name);
diff --git a/Code/Mantid/MantidQt/API/src/MantidQwtIMDWorkspaceData.cpp b/Code/Mantid/MantidQt/API/src/MantidQwtIMDWorkspaceData.cpp
index 2e1e942fe87f6a4b88abf50365af08c4ec280899..0d968f53822a87d994c52846cbbcf12082260e52 100644
--- a/Code/Mantid/MantidQt/API/src/MantidQwtIMDWorkspaceData.cpp
+++ b/Code/Mantid/MantidQt/API/src/MantidQwtIMDWorkspaceData.cpp
@@ -44,6 +44,9 @@ MantidQwtIMDWorkspaceData::MantidQwtIMDWorkspaceData(Mantid::API::IMDWorkspace_c
     bool isDistribution)
  : m_workspace(workspace),
    m_logScale(logScale),
+   m_minY(DBL_MAX),
+   m_minPositive(DBL_MAX),
+   m_maxY(-DBL_MAX),
    m_preview(false),
    m_start(start),
    m_end(end),
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ConvFit.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ConvFit.h
index 9dc32f42959be89955a977fafc41ae7083f2601e..6885ebb07c5831eaee2c488c74eddd7de4d51f9c 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ConvFit.h
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ConvFit.h
@@ -47,6 +47,7 @@ namespace IDA
     void unFixItem();
     void showTieCheckbox(QString);
     void updatePlotOptions();
+    void singleFitComplete(bool error);
 
   private:
     boost::shared_ptr<Mantid::API::CompositeFunction> createFunction(bool tieCentres=false);
@@ -58,6 +59,7 @@ namespace IDA
     void populateFunction(Mantid::API::IFunction_sptr func, Mantid::API::IFunction_sptr comp, QtProperty* group, const std::string & pref, bool tie);
     QString fitTypeString() const;
     QString backgroundString() const;
+    QString minimizerString(QString outputName) const;
 
     Ui::ConvFit m_uiForm;
     QtStringPropertyManager* m_stringManager;
@@ -66,6 +68,8 @@ namespace IDA
     Mantid::API::MatrixWorkspace_sptr m_cfInputWS;
     QString m_cfInputWSName;
     bool m_confitResFileType;
+    Mantid::API::IAlgorithm_sptr m_singleFitAlg;
+    QString m_singleFitOutputName;
 
   };
 } // namespace IDA
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Elwin.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Elwin.ui
index ab156ca3e5bfa119574f379cf664daa66b1025a5..6cae8fdba688152e181dbaf1941147b18359e29b 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Elwin.ui
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Elwin.ui
@@ -121,6 +121,20 @@
        </property>
       </widget>
      </item>
+     <item>
+      <widget class="QComboBox" name="leLogValue">
+       <item>
+        <property name="text">
+         <string>last value</string>
+        </property>
+       </item>
+       <item>
+        <property name="text">
+         <string>average</string>
+        </property>
+       </item>
+      </widget>
+     </item>
      <item>
       <spacer name="horizontalSpacer_2">
        <property name="orientation">
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IqtFit.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IqtFit.h
index 16119b74a27d3f677ed22b4b0c10a26cefe688a8..526075458a29b7c7e3f36470d014b30e3cb1e7ef 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IqtFit.h
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IqtFit.h
@@ -43,12 +43,14 @@ namespace IDA
     void xMinSelected(double val);
     void xMaxSelected(double val);
     void backgroundSelected(double val);
-    void propertyChanged(QtProperty*, double);
+    void propertyChanged(QtProperty *, double);
+    void checkBoxUpdate(QtProperty * prop, bool checked);
     void singleFit();
     void plotGuess(QtProperty*);
     void fitContextMenu(const QPoint &);
     void fixItem();
     void unFixItem();
+    void singleFitComplete(bool error);
 
   private:
     boost::shared_ptr<Mantid::API::CompositeFunction> createFunction(bool tie=false);
@@ -58,6 +60,7 @@ namespace IDA
     void setDefaultParameters(const QString& name);
     QString fitTypeString() const;
     void constrainIntensities(Mantid::API::CompositeFunction_sptr func);
+    QString minimizerString(QString outputName) const;
 
     Ui::IqtFit m_uiForm;
     QtStringPropertyManager* m_stringManager;
@@ -68,6 +71,8 @@ namespace IDA
     Mantid::API::MatrixWorkspace_sptr m_ffOutputWS;
     QString m_ffInputWSName;
     QString m_ties;
+    Mantid::API::IAlgorithm_sptr m_singleFitAlg;
+    QString m_singleFitOutputName;
 
   };
 } // namespace IDA
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/DataComparison.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/DataComparison.cpp
index 240476a99036c5c7b49b8b01c4ad1ea6aa630814..69e18d48b525b78e2d07a6309a2d0efb02657500 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/DataComparison.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/DataComparison.cpp
@@ -33,6 +33,9 @@ DataComparison::DataComparison(QWidget *parent) :
   UserSubWindow(parent),
   WorkspaceObserver(),
   m_plot(new QwtPlot(parent)),
+  m_zoomTool(NULL),
+  m_panTool(NULL),
+  m_magnifyTool(NULL),
   m_diffWorkspaceNames(qMakePair(QString(), QString()))
 {
   observeAfterReplace();
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ConvFit.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ConvFit.cpp
index 7c9d0bad230e166bcc6a00253e4b57eed872a259..cbfe823e1b3fc77d287132f91b346015b3a0dee7 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ConvFit.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ConvFit.cpp
@@ -37,6 +37,7 @@ namespace IDA
     m_uiForm.setupUi(parent);
   }
 
+
   void ConvFit::setup()
   {
     // Create Property Managers
@@ -66,6 +67,13 @@ namespace IDA
     m_cfTree->addProperty(m_properties["Convolve"]);
     m_blnManager->setValue(m_properties["Convolve"], true);
 
+    // Max iterations option
+    m_properties["MaxIterations"] = m_dblManager->addProperty("Max Iterations");
+    m_dblManager->setDecimals(m_properties["MaxIterations"], 0);
+    m_dblManager->setValue(m_properties["MaxIterations"], 500);
+    m_cfTree->addProperty(m_properties["MaxIterations"]);
+
+    // Fitting range
     m_properties["FitRange"] = m_grpManager->addProperty("Fitting Range");
     m_properties["StartX"] = m_dblManager->addProperty("StartX");
     m_dblManager->setDecimals(m_properties["StartX"], NUM_DECIMALS);
@@ -75,6 +83,17 @@ namespace IDA
     m_properties["FitRange"]->addSubProperty(m_properties["EndX"]);
     m_cfTree->addProperty(m_properties["FitRange"]);
 
+    // FABADA
+    m_properties["FABADA"] = m_grpManager->addProperty("Bayesian");
+    m_properties["UseFABADA"] = m_blnManager->addProperty("Use FABADA");
+    m_properties["FABADA"]->addSubProperty(m_properties["UseFABADA"]);
+    m_properties["OutputFABADAChain"] = m_blnManager->addProperty("Output Chain");
+    m_properties["FABADAChainLength"] = m_dblManager->addProperty("Chain Length");
+    m_dblManager->setDecimals(m_properties["FABADAChainLength"], 0);
+    m_dblManager->setValue(m_properties["FABADAChainLength"], 10000);
+    m_cfTree->addProperty(m_properties["FABADA"]);
+
+    // Background type
     m_properties["LinearBackground"] = m_grpManager->addProperty("Background");
     m_properties["BGA0"] = m_dblManager->addProperty("A0");
     m_dblManager->setDecimals(m_properties["BGA0"], NUM_DECIMALS);
@@ -92,6 +111,7 @@ namespace IDA
     m_properties["DeltaFunction"]->addSubProperty(m_properties["UseDeltaFunc"]);
     m_cfTree->addProperty(m_properties["DeltaFunction"]);
 
+    // Fit functions
     m_properties["Lorentzian1"] = createLorentzian("Lorentzian 1");
     m_properties["Lorentzian2"] = createLorentzian("Lorentzian 2");
     m_properties["DiffSphere"] = createDiffSphere("Diffusion Sphere");
@@ -148,6 +168,7 @@ namespace IDA
     updatePlotOptions();
   }
 
+
   void ConvFit::run()
   {
     if ( m_cfInputWS == NULL )
@@ -173,6 +194,7 @@ namespace IDA
     QString enX = m_properties["EndX"]->valueText();
     QString specMin = m_uiForm.spSpectraMin->text();
     QString specMax = m_uiForm.spSpectraMax->text();
+    int maxIterations = static_cast<int>(m_dblManager->value(m_properties["MaxIterations"]));
 
     QString pyInput =
       "from IndirectDataAnalysis import confitSeq\n"
@@ -184,6 +206,8 @@ namespace IDA
       "ties = " + ties + "\n"
       "specMin = " + specMin + "\n"
       "specMax = " + specMax + "\n"
+      "max_iterations = " + QString::number(maxIterations) + "\n"
+      "minimizer = '" + minimizerString("$outputname_$wsindex") + "'\n"
       "save = " + (m_uiForm.ckSave->isChecked() ? "True\n" : "False\n");
 
     if ( m_blnManager->value(m_properties["Convolve"]) ) pyInput += "convolve = True\n";
@@ -203,7 +227,7 @@ namespace IDA
     pyInput +=
       "bg = '" + bgType + "'\n"
       "ftype = '" + fitType + "'\n"
-      "confitSeq(input, func, startx, endx, ftype, bg, temp, specMin, specMax, convolve, Plot=plot, Save=save)\n";
+      "confitSeq(input, func, startx, endx, ftype, bg, temp, specMin, specMax, convolve, max_iterations=max_iterations, minimizer=minimizer, Plot=plot, Save=save)\n";
 
     QString pyOutput = runPythonCode(pyInput);
 
@@ -215,6 +239,7 @@ namespace IDA
     updatePlot();
   }
 
+
   /**
    * Validates the user's inputs in the ConvFit tab.
    */
@@ -273,6 +298,7 @@ namespace IDA
     updatePlot();
   }
 
+
   /**
    * Create a resolution workspace with the same number of histograms as in the sample.
    *
@@ -311,6 +337,7 @@ namespace IDA
     }
   }
 
+
   namespace
   {
     ////////////////////////////
@@ -333,6 +360,7 @@ namespace IDA
       return prefix.str();
     }
 
+
     /**
      * Takes an index, a sub index and a name, and constructs a double level
      * (nested) parameter name for use with function ties, etc.
@@ -351,6 +379,7 @@ namespace IDA
     }
   }
 
+
   /**
    * Creates a function to carry out the fitting in the "ConvFit" tab.  The function consists
    * of various sub functions, with the following structure:
@@ -562,6 +591,7 @@ namespace IDA
     return comp;
   }
 
+
   void ConvFit::createTemperatureCorrection(CompositeFunction_sptr product)
   {
     //create temperature correction function to multiply with the lorentzians
@@ -582,6 +612,7 @@ namespace IDA
     product->applyTies();
   }
 
+
   double ConvFit::getInstrumentResolution(std::string workspaceName)
   {
     using namespace Mantid::API;
@@ -634,6 +665,7 @@ namespace IDA
     return resolution;
   }
 
+
   QtProperty* ConvFit::createLorentzian(const QString & name)
   {
     QtProperty* lorentzGroup = m_grpManager->addProperty(name);
@@ -655,6 +687,7 @@ namespace IDA
     return lorentzGroup;
   }
 
+
   QtProperty* ConvFit::createDiffSphere(const QString & name)
   {
     QtProperty* diffSphereGroup = m_grpManager->addProperty(name);
@@ -677,6 +710,7 @@ namespace IDA
     return diffSphereGroup;
   }
 
+
   QtProperty* ConvFit::createDiffRotDiscreteCircle(const QString & name)
   {
     QtProperty* diffRotDiscreteCircleGroup = m_grpManager->addProperty(name);
@@ -704,6 +738,7 @@ namespace IDA
     return diffRotDiscreteCircleGroup;
   }
 
+
   void ConvFit::populateFunction(IFunction_sptr func, IFunction_sptr comp, QtProperty* group, const std::string & pref, bool tie)
   {
     // Get subproperties of group and apply them as parameters on the function object
@@ -732,6 +767,7 @@ namespace IDA
     }
   }
 
+
   /**
    * Generate a string to describe the fit type selected by the user.
    * Used when naming the resultant workspaces.
@@ -765,6 +801,7 @@ namespace IDA
     return fitType;
   }
 
+
   /**
    * Generate a string to describe the background selected by the user.
    * Used when naming the resultant workspaces.
@@ -789,6 +826,33 @@ namespace IDA
     }
   }
 
+
+  /**
+   * Generates a string that defines the fitting minimizer based on the user
+   * options.
+   *
+   * @return Minimizer as a string
+   */
+  QString ConvFit::minimizerString(QString outputName) const
+  {
+    QString minimizer = "Levenberg-Marquardt";
+
+    if(m_blnManager->value(m_properties["UseFABADA"]))
+    {
+      minimizer = "FABADA";
+
+      int chainLength = static_cast<int>(m_dblManager->value(m_properties["FABADAChainLength"]));
+      minimizer += ",ChainLength=" + QString::number(chainLength);
+      minimizer += ",PDF=" + outputName + "_PDF";
+
+      if(m_blnManager->value(m_properties["OutputFABADAChain"]))
+        minimizer += ",Chains=" + outputName + "_Chain";
+    }
+
+    return minimizer;
+  }
+
+
   void ConvFit::typeSelection(int index)
   {
     m_cfTree->removeProperty(m_properties["Lorentzian1"]);
@@ -833,6 +897,7 @@ namespace IDA
     updatePlotOptions();
   }
 
+
   void ConvFit::bgTypeSelection(int index)
   {
     if ( index == 2 )
@@ -845,6 +910,7 @@ namespace IDA
     }
   }
 
+
   void ConvFit::updatePlot()
   {
     using Mantid::Kernel::Exception::NotFoundError;
@@ -895,6 +961,7 @@ namespace IDA
     }
   }
 
+
   void ConvFit::plotGuess()
   {
     m_uiForm.ppPlot->removeSpectrum("Guess");
@@ -958,6 +1025,7 @@ namespace IDA
     m_uiForm.ppPlot->addSpectrum("Guess", guessWs, 0, Qt::green);
   }
 
+
   void ConvFit::singleFit()
   {
     if(!validate())
@@ -978,24 +1046,42 @@ namespace IDA
       g_log.error("No fit type defined!");
     }
 
-    QString outputNm = runPythonCode(QString("from IndirectCommon import getWSprefix\nprint getWSprefix('") + m_cfInputWSName + QString("')\n")).trimmed();
-    outputNm += QString("conv_") + fitType + bgType + m_uiForm.spPlotSpectrum->text();
-    std::string output = outputNm.toStdString();
-
-    IAlgorithm_sptr alg = AlgorithmManager::Instance().create("Fit");
-    alg->initialize();
-    alg->setPropertyValue("Function", function->asString());
-    alg->setPropertyValue("InputWorkspace", m_cfInputWSName.toStdString());
-    alg->setProperty<int>("WorkspaceIndex", m_uiForm.spPlotSpectrum->text().toInt());
-    alg->setProperty<double>("StartX", m_dblManager->value(m_properties["StartX"]));
-    alg->setProperty<double>("EndX", m_dblManager->value(m_properties["EndX"]));
-    alg->setProperty("Output", output);
-    alg->setProperty("CreateOutput", true);
-    alg->setProperty("OutputCompositeMembers", true);
-    alg->setProperty("ConvolveMembers", true);
-    alg->execute();
-
-    if ( ! alg->isExecuted() )
+    m_singleFitOutputName = runPythonCode(QString("from IndirectCommon import getWSprefix\nprint getWSprefix('") + m_cfInputWSName + QString("')\n")).trimmed();
+    m_singleFitOutputName += QString("conv_") + fitType + bgType + m_uiForm.spPlotSpectrum->text();
+    int maxIterations = static_cast<int>(m_dblManager->value(m_properties["MaxIterations"]));
+
+    m_singleFitAlg = AlgorithmManager::Instance().create("Fit");
+    m_singleFitAlg->initialize();
+    m_singleFitAlg->setPropertyValue("Function", function->asString());
+    m_singleFitAlg->setPropertyValue("InputWorkspace", m_cfInputWSName.toStdString());
+    m_singleFitAlg->setProperty<int>("WorkspaceIndex", m_uiForm.spPlotSpectrum->text().toInt());
+    m_singleFitAlg->setProperty<double>("StartX", m_dblManager->value(m_properties["StartX"]));
+    m_singleFitAlg->setProperty<double>("EndX", m_dblManager->value(m_properties["EndX"]));
+    m_singleFitAlg->setProperty("Output", m_singleFitOutputName.toStdString());
+    m_singleFitAlg->setProperty("CreateOutput", true);
+    m_singleFitAlg->setProperty("OutputCompositeMembers", true);
+    m_singleFitAlg->setProperty("ConvolveMembers", true);
+    m_singleFitAlg->setProperty("MaxIterations", maxIterations);
+    m_singleFitAlg->setProperty("Minimizer", minimizerString(m_singleFitOutputName).toStdString());
+
+    m_batchAlgoRunner->addAlgorithm(m_singleFitAlg);
+    connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)),
+            this, SLOT(singleFitComplete(bool)));
+    m_batchAlgoRunner->executeBatchAsync();
+  }
+
+
+  /**
+   * Handle completion of the fit algorithm for single fit.
+   *
+   * @param error If the fit algorithm failed
+   */
+  void ConvFit::singleFitComplete(bool error)
+  {
+    disconnect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)),
+               this, SLOT(singleFitComplete(bool)));
+
+    if(error)
     {
       showMessageBox("Fit algorithm failed.");
       return;
@@ -1003,9 +1089,9 @@ namespace IDA
 
     // Plot the line on the mini plot
     m_uiForm.ppPlot->removeSpectrum("Guess");
-    m_uiForm.ppPlot->addSpectrum("Fit", outputNm+"_Workspace", 1, Qt::red);
+    m_uiForm.ppPlot->addSpectrum("Fit", m_singleFitOutputName+"_Workspace", 1, Qt::red);
 
-    IFunction_sptr outputFunc = alg->getProperty("Function");
+    IFunction_sptr outputFunc = m_singleFitAlg->getProperty("Function");
 
     // Get params.
     QMap<QString,double> parameters;
@@ -1130,6 +1216,7 @@ namespace IDA
     m_pythonExportWsName = "";
   }
 
+
   /**
    * Handles the user entering a new minimum spectrum index.
    *
@@ -1142,6 +1229,7 @@ namespace IDA
     m_uiForm.spSpectraMax->setMinimum(value);
   }
 
+
   /**
    * Handles the user entering a new maximum spectrum index.
    *
@@ -1154,16 +1242,19 @@ namespace IDA
     m_uiForm.spSpectraMin->setMaximum(value);
   }
 
+
   void ConvFit::minChanged(double val)
   {
     m_dblManager->setValue(m_properties["StartX"], val);
   }
 
+
   void ConvFit::maxChanged(double val)
   {
     m_dblManager->setValue(m_properties["EndX"], val);
   }
 
+
   void ConvFit::hwhmChanged(double val)
   {
     const double peakCentre = m_dblManager->value(m_properties["Lorentzian 1.PeakCentre"]);
@@ -1176,11 +1267,13 @@ namespace IDA
     hwhmRangeSelector->blockSignals(false);
   }
 
+
   void ConvFit::backgLevel(double val)
   {
     m_dblManager->setValue(m_properties["BGA0"], val);
   }
 
+
   void ConvFit::updateRS(QtProperty* prop, double val)
   {
     auto fitRangeSelector = m_uiForm.ppPlot->getRangeSelector("ConvFitRange");
@@ -1196,6 +1289,7 @@ namespace IDA
     }
   }
 
+
   void ConvFit::hwhmUpdateRS(double val)
   {
     const double peakCentre = m_dblManager->value(m_properties["Lorentzian 1.PeakCentre"]);
@@ -1204,14 +1298,34 @@ namespace IDA
     hwhmRangeSelector->setMaximum(peakCentre+val/2);
   }
 
+
   void ConvFit::checkBoxUpdate(QtProperty* prop, bool checked)
   {
     UNUSED_ARG(checked);
 
     if(prop == m_properties["UseDeltaFunc"])
       updatePlotOptions();
+    else if(prop == m_properties["UseFABADA"])
+    {
+      if(checked)
+      {
+        // FABADA needs a much higher iteration limit
+        m_dblManager->setValue(m_properties["MaxIterations"], 20000);
+
+        m_properties["FABADA"]->addSubProperty(m_properties["OutputFABADAChain"]);
+        m_properties["FABADA"]->addSubProperty(m_properties["FABADAChainLength"]);
+      }
+      else
+      {
+        m_dblManager->setValue(m_properties["MaxIterations"], 500);
+
+        m_properties["FABADA"]->removeSubProperty(m_properties["OutputFABADAChain"]);
+        m_properties["FABADA"]->removeSubProperty(m_properties["FABADAChainLength"]);
+      }
+    }
   }
 
+
   void ConvFit::fitContextMenu(const QPoint &)
   {
     QtBrowserItem* item(NULL);
@@ -1254,6 +1368,7 @@ namespace IDA
     menu->popup(QCursor::pos());
   }
 
+
   void ConvFit::fixItem()
   {
     QtBrowserItem* item = m_cfTree->currentItem();
@@ -1272,6 +1387,7 @@ namespace IDA
     item->parent()->property()->removeSubProperty(prop);
   }
 
+
   void ConvFit::unFixItem()
   {
     QtBrowserItem* item = m_cfTree->currentItem();
@@ -1291,11 +1407,13 @@ namespace IDA
     delete prop;
   }
 
+
   void ConvFit::showTieCheckbox(QString fitType)
   {
     m_uiForm.ckTieCentres->setVisible( fitType == "Two Lorentzians" );
   }
 
+
   void ConvFit::updatePlotOptions()
   {
     m_uiForm.cbPlotType->clear();
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Elwin.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Elwin.cpp
index 3cc9867a2a20e66c5ebabce68ce73de73aed9f8f..df51ca0839841487b467b05c45c97b5cf92f1bfd 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Elwin.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Elwin.cpp
@@ -146,6 +146,7 @@ namespace IDA
     elwinMultAlg->setProperty("OutputELF", elfWorkspace.toStdString());
 
     elwinMultAlg->setProperty("SampleEnvironmentLogName", m_uiForm.leLogName->text().toStdString());
+    elwinMultAlg->setProperty("SampleEnvironmentLogValue", m_uiForm.leLogValue->currentText().toStdString());
 
     elwinMultAlg->setProperty("Range1Start", m_dblManager->value(m_properties["IntegrationStart"]));
     elwinMultAlg->setProperty("Range1End", m_dblManager->value(m_properties["IntegrationEnd"]));
@@ -261,15 +262,25 @@ namespace IDA
   void Elwin::setDefaultSampleLog(Mantid::API::MatrixWorkspace_const_sptr ws)
   {
     auto inst = ws->getInstrument();
+    // Set sample environment log name
     auto log = inst->getStringParameter("Workflow.SE-log");
     QString logName("sample");
-
     if(log.size() > 0)
     {
       logName = QString::fromStdString(log[0]);
     }
-
     m_uiForm.leLogName->setText(logName);
+    // Set sample environment log value
+    auto logval = inst->getStringParameter("Workflow.SE-log-value");
+    if(logval.size() > 0)
+    {
+      auto logValue = QString::fromStdString(logval[0]);
+      int  index = m_uiForm.leLogValue->findText(logValue);
+      if (index >= 0)
+      {
+        m_uiForm.leLogValue->setCurrentIndex(index);
+      }
+    }
   }
 
   /**
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ISISCalibration.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ISISCalibration.cpp
index d2535faf70719ea4ee848164266af16363e54fb2..d1ad9e91dd2a6b0b0f09f76ae665f749c4ef269a 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ISISCalibration.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ISISCalibration.cpp
@@ -156,7 +156,8 @@ namespace CustomInterfaces
   {
     // Get properties
     QString firstFile = m_uiForm.leRunNo->getFirstFilename();
-    QString filenames = m_uiForm.leRunNo->getFilenames().join(",");
+    QStringList filenameList = m_uiForm.leRunNo->getFilenames();
+    QString filenames = filenameList.join(",");
 
     auto instDetails = getInstrumentDetails();
     QString instDetectorRange = instDetails["spectra-min"] + "," + instDetails["spectra-max"];
@@ -168,7 +169,10 @@ namespace CustomInterfaces
     QString outputWorkspaceNameStem = firstFileInfo.baseName() + "_" + getInstrumentConfiguration()->getAnalyserName()
                                       + getInstrumentConfiguration()->getReflectionName();
 
-    QString calibrationWsName = outputWorkspaceNameStem + "_calib";
+    QString calibrationWsName = outputWorkspaceNameStem;
+    if(filenameList.size() > 1)
+        calibrationWsName += "_multi";
+    calibrationWsName += "_calib";
 
     // Configure the calibration algorithm
     IAlgorithm_sptr calibrationAlg = AlgorithmManager::Instance().create("IndirectCalibration");
@@ -209,7 +213,10 @@ namespace CustomInterfaces
     // Configure the resolution algorithm
     if(m_uiForm.ckCreateResolution->isChecked())
     {
-      QString resolutionWsName = outputWorkspaceNameStem + "_res";
+      QString resolutionWsName = outputWorkspaceNameStem;
+      if(filenameList.size() > 1)
+        resolutionWsName += "_multi";
+      resolutionWsName += "_res";
 
       QString resDetectorRange = QString::number(m_dblManager->value(m_properties["ResSpecMin"])) + ","
           + QString::number(m_dblManager->value(m_properties["ResSpecMax"]));
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDataReductionTab.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDataReductionTab.cpp
index c203b5d3f12a6b2b398bc336d3977647be37c37f..02b99a6010ea555d1f712bcaa6a984baa2ec7243 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDataReductionTab.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDataReductionTab.cpp
@@ -21,7 +21,7 @@ namespace CustomInterfaces
   /** Constructor
    */
   IndirectDataReductionTab::IndirectDataReductionTab(IndirectDataReduction *idrUI, QObject *parent) :
-    IndirectTab(parent), m_idrUI(idrUI)
+    IndirectTab(parent), m_idrUI(idrUI), m_tabRunning(false)
   {
     connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(tabExecutionComplete(bool)));
   }
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTab.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTab.cpp
index 825811403b4de84430121cc21af57ed0a80b54f8..27c0e8a8aa42227bba34e3b055bf67bb2b1921e1 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTab.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTab.cpp
@@ -195,9 +195,9 @@ namespace CustomInterfaces
   {
     QString pyInput = "from mantidplot import plotSpectrum\n";
 
-    pyInput += "plotSpectrum('";
+    pyInput += "plotSpectrum(['";
     pyInput += workspaceNames.join("','");
-    pyInput += "', ";
+    pyInput += "'], ";
     pyInput += QString::number(specIndex);
     pyInput += ")\n";
 
@@ -234,9 +234,9 @@ namespace CustomInterfaces
   {
     QString pyInput = "from mantidplot import plotSpectrum\n";
 
-    pyInput += "plotSpectrum('";
+    pyInput += "plotSpectrum(['";
     pyInput += workspaceNames.join("','");
-    pyInput += "', range(";
+    pyInput += "'], range(";
     pyInput += QString::number(specStart);
     pyInput += ",";
     pyInput += QString::number(specEnd);
@@ -296,9 +296,9 @@ namespace CustomInterfaces
   {
     QString pyInput = "from mantidplot import plotTimeBin\n";
 
-    pyInput += "plotTimeBin('";
+    pyInput += "plotTimeBin(['";
     pyInput += workspaceNames.join("','");
-    pyInput += "', ";
+    pyInput += "'], ";
     pyInput += QString::number(specIndex);
     pyInput += ")\n";
 
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IqtFit.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IqtFit.cpp
index 2be248cd4e8bd868f36857abe893affdae718f9a..35f97d2f46fa7f253309dd933c665f847ea00459 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IqtFit.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IqtFit.cpp
@@ -60,13 +60,27 @@ namespace IDA
     // setupTreePropertyBrowser
     m_ffRangeManager = new QtDoublePropertyManager(m_parentWidget);
 
+    m_ffTree->setFactoryForManager(m_blnManager, m_blnEdFac);
     m_ffTree->setFactoryForManager(m_dblManager, m_dblEdFac);
     m_ffTree->setFactoryForManager(m_ffRangeManager, m_dblEdFac);
 
     m_properties["StartX"] = m_ffRangeManager->addProperty("StartX");
     m_ffRangeManager->setDecimals(m_properties["StartX"], NUM_DECIMALS);
     m_properties["EndX"] = m_ffRangeManager->addProperty("EndX");
-    m_ffRangeManager->setDecimals(m_properties["EndX"], NUM_DECIMALS);
+    m_dblManager->setDecimals(m_properties["EndX"], NUM_DECIMALS);
+    m_properties["MaxIterations"] = m_dblManager->addProperty("Max Iterations");
+    m_dblManager->setDecimals(m_properties["MaxIterations"], 0);
+    m_dblManager->setValue(m_properties["MaxIterations"], 500);
+
+    // FABADA
+    m_properties["FABADA"] = m_grpManager->addProperty("Bayesian");
+    m_properties["UseFABADA"] = m_blnManager->addProperty("Use FABADA");
+    m_properties["FABADA"]->addSubProperty(m_properties["UseFABADA"]);
+    m_properties["OutputFABADAChain"] = m_blnManager->addProperty("Output Chain");
+    m_properties["FABADAChainLength"] = m_dblManager->addProperty("Chain Length");
+    m_dblManager->setDecimals(m_properties["FABADAChainLength"], 0);
+    m_dblManager->setValue(m_properties["FABADAChainLength"], 10000);
+    m_ffTree->addProperty(m_properties["FABADA"]);
 
     connect(m_ffRangeManager, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(propertyChanged(QtProperty*, double)));
     connect(m_dblManager, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(propertyChanged(QtProperty*, double)));
@@ -113,6 +127,8 @@ namespace IDA
     // Set a custom handler for the QTreePropertyBrowser's ContextMenu event
     m_ffTree->setContextMenuPolicy(Qt::CustomContextMenu);
     connect(m_ffTree, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(fitContextMenu(const QPoint &)));
+
+    connect(m_blnManager, SIGNAL(valueChanged(QtProperty *, bool)), this, SLOT(checkBoxUpdate(QtProperty *, bool)));
   }
 
   void IqtFit::run()
@@ -148,7 +164,9 @@ namespace IDA
       "plot = '" + m_uiForm.cbPlotType->currentText() + "'\n"
       "spec_min = " + specMin + "\n"
       "spec_max = " + specMax + "\n"
-      "spec_max = None\n";
+      "spec_max = None\n"
+      "minimizer = '" + minimizerString("$outputname_$wsindex") + "'\n"
+      "max_iterations = " + QString::number(m_dblManager->value(m_properties["MaxIterations"])) + "\n";
 
     if (constrainIntens) pyInput += "constrain_intens = True \n";
     else pyInput += "constrain_intens = False \n";
@@ -158,11 +176,11 @@ namespace IDA
 
     if( !constrainBeta )
     {
-      pyInput += "furyfitSeq(input, func, ftype, startx, endx, spec_min=spec_min, spec_max=spec_max, intensities_constrained=constrain_intens, Save=save, Plot=plot)\n";
+      pyInput += "furyfitSeq(input, func, ftype, startx, endx, spec_min=spec_min, spec_max=spec_max, intensities_constrained=constrain_intens, Save=save, Plot=plot, minimizer=minimizer, max_iterations=max_iterations)\n";
     }
     else
     {
-      pyInput += "furyfitMult(input, func, ftype, startx, endx, spec_min=spec_min, spec_max=spec_max, intensities_constrained=constrain_intens, Save=save, Plot=plot)\n";
+      pyInput += "furyfitMult(input, func, ftype, startx, endx, spec_min=spec_min, spec_max=spec_max, intensities_constrained=constrain_intens, Save=save, Plot=plot, minimizer=minimizer, max_iterations=max_iterations)\n";
     }
 
     QString pyOutput = runPythonCode(pyInput);
@@ -332,7 +350,9 @@ namespace IDA
 
     m_ffTree->addProperty(m_properties["StartX"]);
     m_ffTree->addProperty(m_properties["EndX"]);
+    m_ffTree->addProperty(m_properties["MaxIterations"]);
     m_ffTree->addProperty(m_properties["LinearBackground"]);
+    m_ffTree->addProperty(m_properties["FABADA"]);
 
     //option should only be available with a single stretched exponential
     m_uiForm.ckConstrainBeta->setEnabled((index == 2));
@@ -518,6 +538,27 @@ namespace IDA
     }
   }
 
+  void IqtFit::checkBoxUpdate(QtProperty * prop, bool checked)
+  {
+    if(prop == m_properties["UseFABADA"])
+    {
+      if(checked)
+      {
+        m_dblManager->setValue(m_properties["MaxIterations"], 20000);
+
+        m_properties["FABADA"]->addSubProperty(m_properties["OutputFABADAChain"]);
+        m_properties["FABADA"]->addSubProperty(m_properties["FABADAChainLength"]);
+      }
+      else
+      {
+        m_dblManager->setValue(m_properties["MaxIterations"], 500);
+
+        m_properties["FABADA"]->removeSubProperty(m_properties["OutputFABADAChain"]);
+        m_properties["FABADA"]->removeSubProperty(m_properties["FABADAChainLength"]);
+      }
+    }
+  }
+
   void IqtFit::constrainIntensities(CompositeFunction_sptr func)
   {
     std::string paramName = "f1.Intensity";
@@ -554,6 +595,31 @@ namespace IDA
     }
   }
 
+  /**
+   * Generates a string that defines the fitting minimizer based on the user
+   * options.
+   *
+   * @return Minimizer as a string
+   */
+  QString IqtFit::minimizerString(QString outputName) const
+  {
+    QString minimizer = "Levenberg-Marquardt";
+
+    if(m_blnManager->value(m_properties["UseFABADA"]))
+    {
+      minimizer = "FABADA";
+
+      int chainLength = static_cast<int>(m_dblManager->value(m_properties["FABADAChainLength"]));
+      minimizer += ",ChainLength=" + QString::number(chainLength);
+      minimizer += ",PDF=" + outputName + "_PDF";
+
+      if(m_blnManager->value(m_properties["OutputFABADAChain"]))
+        minimizer += ",Chains=" + outputName + "_Chain";
+    }
+
+    return minimizer;
+  }
+
   void IqtFit::singleFit()
   {
     if(!validate())
@@ -592,23 +658,37 @@ namespace IDA
 
     QString pyInput = "from IndirectCommon import getWSprefix\nprint getWSprefix('%1')\n";
     pyInput = pyInput.arg(m_ffInputWSName);
-    QString outputNm = runPythonCode(pyInput).trimmed();
-    outputNm += QString("fury_") + ftype + m_uiForm.spPlotSpectrum->text();
-    std::string output = outputNm.toStdString();
+    m_singleFitOutputName = runPythonCode(pyInput).trimmed() +
+                            QString("fury_") +
+                            ftype +
+                            m_uiForm.spPlotSpectrum->text();
 
     // Create the Fit Algorithm
-    IAlgorithm_sptr alg = AlgorithmManager::Instance().create("Fit");
-    alg->initialize();
-    alg->setPropertyValue("Function", function->asString());
-    alg->setPropertyValue("InputWorkspace", m_ffInputWSName.toStdString());
-    alg->setProperty("WorkspaceIndex", m_uiForm.spPlotSpectrum->text().toInt());
-    alg->setProperty("StartX", m_ffRangeManager->value(m_properties["StartX"]));
-    alg->setProperty("EndX", m_ffRangeManager->value(m_properties["EndX"]));
-    alg->setProperty("Ties", m_ties.toStdString());
-    alg->setPropertyValue("Output", output);
-    alg->execute();
-
-    if ( ! alg->isExecuted() )
+    m_singleFitAlg = AlgorithmManager::Instance().create("Fit");
+    m_singleFitAlg->initialize();
+    m_singleFitAlg->setPropertyValue("Function", function->asString());
+    m_singleFitAlg->setPropertyValue("InputWorkspace", m_ffInputWSName.toStdString());
+    m_singleFitAlg->setProperty("WorkspaceIndex", m_uiForm.spPlotSpectrum->text().toInt());
+    m_singleFitAlg->setProperty("StartX", m_ffRangeManager->value(m_properties["StartX"]));
+    m_singleFitAlg->setProperty("EndX", m_ffRangeManager->value(m_properties["EndX"]));
+    m_singleFitAlg->setProperty("MaxIterations", static_cast<int>(m_dblManager->value(m_properties["MaxIterations"])));
+    m_singleFitAlg->setProperty("Minimizer", minimizerString(m_singleFitOutputName).toStdString());
+    m_singleFitAlg->setProperty("Ties", m_ties.toStdString());
+    m_singleFitAlg->setPropertyValue("Output", m_singleFitOutputName.toStdString());
+
+    connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)),
+            this, SLOT(singleFitComplete(bool)));
+
+    m_batchAlgoRunner->addAlgorithm(m_singleFitAlg);
+    m_batchAlgoRunner->executeBatchAsync();
+  }
+
+  void IqtFit::singleFitComplete(bool error)
+  {
+    disconnect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)),
+               this, SLOT(singleFitComplete(bool)));
+
+    if(error)
     {
       QString msg = "There was an error executing the fitting algorithm. Please see the "
         "Results Log pane for more details.";
@@ -616,7 +696,7 @@ namespace IDA
       return;
     }
 
-    IFunction_sptr outputFunc = alg->getProperty("Function");
+    IFunction_sptr outputFunc = m_singleFitAlg->getProperty("Function");
 
     // Get params.
     QMap<QString,double> parameters;
@@ -631,6 +711,7 @@ namespace IDA
 
     m_ffRangeManager->setValue(m_properties["BackgroundA0"], parameters["f0.A0"]);
 
+    const int fitType = m_uiForm.cbFitType->currentIndex();
     if ( fitType != 2 )
     {
       // Exp 1
@@ -663,7 +744,7 @@ namespace IDA
     // Plot the guess first so that it is under the fit
     plotGuess(NULL);
     // Now show the fitted curve of the mini plot
-    m_uiForm.ppPlot->addSpectrum("Fit", outputNm+"_Workspace", 1, Qt::red);
+    m_uiForm.ppPlot->addSpectrum("Fit", m_singleFitOutputName + "_Workspace", 1, Qt::red);
 
     m_pythonExportWsName = "";
   }
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/MultiDatasetFit/MultiDatasetFit.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/MultiDatasetFit/MultiDatasetFit.cpp
index b6cc142dd83123a6b2cad135ac02fa4bde57e3f0..1fcf28f2ae2922722e0a2ce4ea1fe0c7e32dbc48 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/MultiDatasetFit/MultiDatasetFit.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/MultiDatasetFit/MultiDatasetFit.cpp
@@ -31,7 +31,8 @@ DECLARE_SUBWINDOW(MultiDatasetFit)
 /// Constructor
 /// @param parent :: The parent widget
 MultiDatasetFit::MultiDatasetFit(QWidget *parent)
-:UserSubWindow(parent)
+:UserSubWindow(parent), m_plotController(NULL), m_dataController(NULL), m_functionBrowser(NULL),
+ m_fitOptionsBrowser(NULL)
 {
 }
 
diff --git a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MantidHelpWindow.h b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MantidHelpWindow.h
index 3bbe46a13a368687ff38532910bf108817f3f179..d3a6921200e0b0f60a9df260e97393d486248a5c 100644
--- a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MantidHelpWindow.h
+++ b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MantidHelpWindow.h
@@ -29,11 +29,13 @@ public:
   virtual void showPage(const QString & url);
   virtual void showPage(const QUrl & url);
   virtual void showWikiPage(const std::string &page=std::string());
+  virtual void showWikiPage(const QString &page);
   virtual void showAlgorithm(const std::string &name=std::string(), const int version=-1);
   virtual void showAlgorithm(const QString &name, const int version=-1);
   virtual void showConcept(const std::string &name);
   virtual void showConcept(const QString &name);
   virtual void showFitFunction(const std::string &name=std::string());
+  virtual void showFitFunction(const QString &name);
   virtual void showCustomInterface(const std::string &name=std::string());
   virtual void showCustomInterface(const QString &name);
 
diff --git a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h
index b33d9f330f01014ba3af9be08736d10c90244c83..8be10cb155fd55e144ac3d0630617f4fbed0192a 100644
--- a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h
+++ b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h
@@ -120,7 +120,7 @@ namespace MantidWidgets
       size_t wsIndex;
 
       PlotCurveConfiguration():
-        curve(NULL), label(NULL) {}
+        curve(NULL), label(NULL), colour(), wsIndex(0) {}
     };
 
     void handleRemoveEvent(Mantid::API::WorkspacePreDeleteNotification_ptr pNf);
diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/FitPropertyBrowser.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/FitPropertyBrowser.cpp
index 53d7efde8cfcccd0b4b8e4e7f779a1189b7eb252..79aa704b506e9c5de7a1a506038ae69d593dfa28 100644
--- a/Code/Mantid/MantidQt/MantidWidgets/src/FitPropertyBrowser.cpp
+++ b/Code/Mantid/MantidQt/MantidWidgets/src/FitPropertyBrowser.cpp
@@ -87,7 +87,16 @@ namespace MantidWidgets
  */
 FitPropertyBrowser::FitPropertyBrowser(QWidget *parent, QObject* mantidui):
   QDockWidget("Fit Function",parent),
+  m_workspaceIndex(NULL),
+  m_startX(NULL),
+  m_endX(NULL),
+  m_output(NULL),
+  m_minimizer(NULL),
+  m_ignoreInvalidData(NULL),
+  m_costFunction(NULL),
+  m_maxIterations(NULL),
   m_logValue(NULL),
+  m_plotDiff(NULL),
   m_plotCompositeMembers(NULL),
   m_convolveMembers(NULL),
   m_rawData(NULL),
diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/IndirectInstrumentConfig.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/IndirectInstrumentConfig.cpp
index 77a28a51facd67450ea4a321e5c9edfb98a8a860..d27843d6d5de9a3e5f622d477a39b9ed99c91e84 100644
--- a/Code/Mantid/MantidQt/MantidWidgets/src/IndirectInstrumentConfig.cpp
+++ b/Code/Mantid/MantidQt/MantidWidgets/src/IndirectInstrumentConfig.cpp
@@ -24,7 +24,9 @@ namespace MantidQt
 
     IndirectInstrumentConfig::IndirectInstrumentConfig(QWidget *parent): API::MantidWidget(parent),
       m_algRunner(),
-      m_disabledInstruments()
+      m_disabledInstruments(),
+      m_removeDiffraction(false),
+      m_forceDiffraction(false)
     {
       m_uiForm.setupUi(this);
 
diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/MantidHelpWindow.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/MantidHelpWindow.cpp
index 02e286257fa05460a5cf792325d5481168e76746..110d04a7ce3b306156982e09c7d770337e3c11f1 100644
--- a/Code/Mantid/MantidQt/MantidWidgets/src/MantidHelpWindow.cpp
+++ b/Code/Mantid/MantidQt/MantidWidgets/src/MantidHelpWindow.cpp
@@ -187,6 +187,17 @@ void MantidHelpWindow::showWikiPage(const string &page)
         this->openWebpage(WIKI_BASE_URL + page.c_str());
 }
 
+/**
+ * Convenience method for HelpWindowImpl::showWikiPage(const string &).
+ *
+ * @param page The name of the wiki page to show. If this is empty show
+ * the wiki homepage.
+ */
+void MantidHelpWindow::showWikiPage(const QString &page)
+{
+    this->showWikiPage(page.toStdString());
+}
+
 /**
  * Show the help page for a particular algorithm. The page is picked
  * using matching naming conventions.
@@ -215,7 +226,7 @@ void MantidHelpWindow::showAlgorithm(const string &name, const int version)
     else // qt-assistant disabled
     {
         if (name.empty())
-            this->showWikiPage("Category:Algorithms");
+            this->showWikiPage(std::string("Category:Algorithms"));
         else
             this->showWikiPage(name);
     }
@@ -236,7 +247,7 @@ void MantidHelpWindow::showAlgorithm(const QString &name, const int version)
 
 
 /**
- * Show the help page for a particular concept. 
+ * Show the help page for a particular concept.
  *
  * @param name The name of the concept to show. If this is empty show
  * the concept index.
@@ -256,7 +267,7 @@ void MantidHelpWindow::showConcept(const string &name)
     else // qt-assistant disabled
     {
         if (name.empty())
-            this->showWikiPage("Category:Concepts");
+            this->showWikiPage(std::string("Category:Concepts"));
         else
             this->showWikiPage(name);
     }
@@ -264,7 +275,7 @@ void MantidHelpWindow::showConcept(const string &name)
 
 
 /**
- * Show the help page for a particular concept. 
+ * Show the help page for a particular concept.
  *
  * @param name The name of the concept to show. If this is empty show
  * the concept index.
@@ -297,12 +308,24 @@ void MantidHelpWindow::showFitFunction(const std::string &name)
     else // qt-assistant disabled
     {
         if (name.empty())
-            this->showWikiPage("Category:Fit_functions");
+            this->showWikiPage(std::string("Category:Fit_functions"));
         else
             this->showWikiPage(name);
     }
 }
 
+/**
+ * Show the help page for a particular fit function. The page is
+ * picked using matching naming conventions.
+ *
+ * @param name The name of the fit function to show. If it is empty show
+ * the fit function index.
+ */
+void MantidHelpWindow::showFitFunction(const QString &name)
+{
+    this->showFitFunction(name.toStdString());
+}
+
 /**
  * Show the help page for a given custom interface.
  *
@@ -355,7 +378,7 @@ void MantidHelpWindow::findCollectionFile(std::string &binDir)
     m_collectionFile = "";
 
     QDir searchDir(QString::fromStdString(binDir));
-        
+
     // try next to the executable
     QString path = searchDir.absoluteFilePath(COLLECTION_FILE);
     g_log.debug() << "Trying \"" << path.toStdString() << "\"\n";
diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/SelectWorkspacesDialog.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/SelectWorkspacesDialog.cpp
index 529d6af69f61f5319341b8f691d447f8332c9887..09c5fa2037cbd92fbc42cd87549a21c104a7dd3b 100644
--- a/Code/Mantid/MantidQt/MantidWidgets/src/SelectWorkspacesDialog.cpp
+++ b/Code/Mantid/MantidQt/MantidWidgets/src/SelectWorkspacesDialog.cpp
@@ -53,7 +53,7 @@ namespace MantidWidgets
 */
 SelectWorkspacesDialog::SelectWorkspacesDialog(QWidget* parent, const std::string& typeFilter,
                                                const std::string& customButtonLabel) :
-QDialog(parent)
+  QDialog(parent), m_wsList(NULL), m_okButton(NULL), m_customButton(NULL)
 {
   setWindowTitle("MantidPlot - Select workspace");
   m_wsList = new QListWidget(parent);
diff --git a/Code/Mantid/MantidQt/Python/mantidqt.in.sip b/Code/Mantid/MantidQt/Python/mantidqt.in.sip
deleted file mode 100644
index b44a820a5b2bae5434bf747f1ebccc3736fa16e4..0000000000000000000000000000000000000000
--- a/Code/Mantid/MantidQt/Python/mantidqt.in.sip
+++ /dev/null
@@ -1,418 +0,0 @@
-/***************************************************************************/
-/**
- This file is a SIP file for binding C++ methods of the 
- MantidQt widgets (SliceViewer and RefDetectorViewer in particular)
- to Python.
- 
-*/
-/***************************************************************************/
-
-// Define the module name. This has to match the library filename
-%Module mantidqtpython
-
-/******************************** SIP Imports ****************/
-%Import QtCore/QtCoremod.sip
-%Import QtGui/QtGuimod.sip
-%Include qwttypes.sip
-
-/***************************************************************************/
-/**************** Exceptions ***********************************************/
-/***************************************************************************/
-%Exception std::exception(SIP_Exception) /PyName=StdException/
-{
-%TypeHeaderCode
-#include <stdexcept>
-%End
-%RaiseCode
-    const char *detail = sipExceptionRef.what();
-
-    SIP_BLOCK_THREADS
-    PyErr_SetString(sipException_std_exception, detail);
-    SIP_UNBLOCK_THREADS
-%End
-};
-
-%Exception std::invalid_argument(SIP_Exception) /PyName=StdInvalidArgument/
-{
-%TypeHeaderCode
-#include <stdexcept>
-%End
-%RaiseCode
-    const char *detail = sipExceptionRef.what();
-
-    SIP_BLOCK_THREADS
-    PyErr_SetString(sipException_std_invalid_argument, detail);
-    SIP_UNBLOCK_THREADS
-%End
-};
-
-%Exception std::runtime_error(SIP_Exception) /PyName=StdRuntimeError/
-{
-%TypeHeaderCode
-#include <stdexcept>
-%End
-%RaiseCode
-    const char *detail = sipExceptionRef.what();
-
-    SIP_BLOCK_THREADS
-    PyErr_SetString(sipException_std_runtime_error, detail);
-    SIP_UNBLOCK_THREADS
-%End
-};
-
-
-namespace Mantid
-{
-namespace API
-{
-
-
-enum MDNormalization
-{
-//%TypeHeaderCode
-//#include "../Framework/API/inc/MantidAPI/IMDWorkspace.h"
-//%End
-  NoNormalization,
-  VolumeNormalization,
-  NumEventsNormalization
-};
-
-}; // end namespace
-}; // end namespace
-
-
-namespace MantidQt
-{
-namespace SliceViewer
-{
-
-//*WIKI* == Classes ==
-//*WIKI* Here follows a list of the classes exposed to python and the methods you can execute on them.
-
-
-/***************************************************************************/
-/***************************************************************************/
-/***************************************************************************/
-class SliceViewerWindow : QMainWindow
-{
-%TypeHeaderCode
-#include "SliceViewer/inc/MantidQtSliceViewer/SliceViewerWindow.h"
-%End
-%Docstring
-
-SliceViewerWindow
-=================
-
-    The SliceViewerWindow is a window containing a SliceViewer widget
-    and a LineViewer Widget.
-
-    It allows you to look at 2D slices in a workspace such as a
-    MDEventWorkspace or a MDHistoWorkspace, and then perform 1D line
-    sections.
-
-    You can access the two contained widgets using:
-        getSlicer() (for the SliceViewer)
-        getLiner() (for the LineViewer)
-
-    However, the methods of the SliceViewer are exposed to the
-    SliceViewerWindow, so you do not need to get the SliceViewer
-    widget directly; you can call the methods on the SliceViewerWindow
-    directly. For example:
-
-       svw.setSlicePoint(2, 10.5)
-
-    See the methods for SliceViewer, below.
-
-%End
-
-public:
-  SliceViewerWindow(const QString& wsName, const QString& label, Qt::WFlags f);
-  MantidQt::SliceViewer::SliceViewer* getSlicer();
-  MantidQt::SliceViewer::LineViewer* getLiner();
-  const QString& getLabel() const;
-
-};
-
-
-
-
-/***************************************************************************/
-/***************************************************************************/
-/***************************************************************************/
-class LineViewer : QWidget
-{
-%TypeHeaderCode
-#include "SliceViewer/inc/MantidQtSliceViewer/LineViewer.h"
-%End
-
-%Docstring
-
-LineViewer
-==========
-
-    The LineViewer is a widget to select 1D line sections out of
-    a workspace such as the MDEventWorkspace or a MDHistoWorkspace.
-
-    It is connected to the SliceViewer.
-
-%End
-
-public:
-
-void apply()   throw (std::runtime_error);
-void showPreview();
-void showFull();
-
-//*WIKI* ==== Start/End Points ====
-void setStartXY(double x, double y)   throw (std::runtime_error);
-void setEndXY(double x, double y)   throw (std::runtime_error);
-
-//*WIKI* ==== Width ====
-void setThickness(double width);
-void setThickness(int dim, double width)   throw (std::invalid_argument, std::runtime_error);
-void setThickness(const QString & dim, double width)   throw (std::invalid_argument, std::runtime_error);
-void setPlanarWidth(double width);
-double getPlanarWidth() const;
-
-//*WIKI* ==== Binning ====
-void setNumBins(int numBins)   throw (std::invalid_argument);
-void setFixedBinWidthMode(bool fixedWidth, double binWidth)   throw (std::invalid_argument);
-double getFixedBinWidth() const;
-bool getFixedBinWidthMode() const;
-int getNumBins() const;
-double getBinWidth() const;
-
-////*WIKI* ==== Plotting ====
-void setPlotAxis(int choice);
-int getPlotAxis() const;
-
-};
-
-
-/***************************************************************************/
-/***************************************************************************/
-/***************************************************************************/
-class SliceViewer : QWidget
-{
-%TypeHeaderCode
-#include "SliceViewer/inc/MantidQtSliceViewer/SliceViewer.h"
-%End
-
-%Docstring
-
-SliceViewer
-===========
-
-    The SliceViewer is a widget showing a 2D slice of a multi-dimensional
-    workspace such as the MDEventWorkspace or a MDHistoWorkspace.
-
-%End
-
-public:
-  //*WIKI* ==== Basics ====
-  void setWorkspace(const QString & wsName)   throw (std::runtime_error);
-  QString getWorkspaceName() const;
-  void showControls(bool visible);
-  void openFromXML(const QString & xml)   throw (std::invalid_argument, std::runtime_error);
-  QPixmap getImage();
-  void saveImage(const QString & filename);
-  void copyImageToClipboard();
-  void setFastRender(bool fast);
-  bool getFastRender() const;
-  void toggleLineMode(bool lineMode);
-
-  //*WIKI* ==== X/Y Dimension ====
-  void setXYDim(int indexX, int indexY)     throw (std::invalid_argument);
-  void setXYDim(const QString & dimX, const QString & dimY)     throw (std::invalid_argument, std::runtime_error);
-  int getDimX() const;
-  int getDimY() const;
-
-  //*WIKI* ==== Slice Point ====
-  void setSlicePoint(int dim, double value)     throw (std::invalid_argument);
-  void setSlicePoint(const QString & dim, double value)   throw (std::invalid_argument, std::runtime_error);
-  double getSlicePoint(int dim) const     throw (std::invalid_argument);
-  double getSlicePoint(const QString & dim) const   throw (std::invalid_argument, std::runtime_error);
-
-  //*WIKI* ==== View Limits ====
-  void setXYLimits(double xleft, double xright, double ybottom, double ytop);
-  QwtDoubleInterval getXLimits() const;
-  QwtDoubleInterval getYLimits() const;
-  void zoomBy(double factor);
-  void setXYCenter(double x, double y);
-  void resetZoom();
-
-  //*WIKI* ==== Color Map and Scale ====
-  void loadColorMap(QString filename);
-  void setColorScale(double min, double max, bool log)      throw (std::invalid_argument);
-  void setColorScaleMin(double min)      throw (std::invalid_argument);
-  void setColorScaleMax(double max)      throw (std::invalid_argument);
-  void setColorScaleLog(bool log);
-  double getColorScaleMin() const;
-  double getColorScaleMax() const;
-  bool getColorScaleLog() const;
-  void setColorScaleAutoFull();
-  void setColorScaleAutoSlice() ;
-  void setColorMapBackground(int r, int g, int b);
-  void setTransparentZeros(bool transparent);
-  void setNormalization(Mantid::API::MDNormalization norm);
-  Mantid::API::MDNormalization getNormalization() const;
-
-  //*WIKI* ==== Dynamic Rebinning ====
-  void setRebinThickness(int dim, double thickness)   throw (std::runtime_error);
-  void setRebinNumBins(int xBins, int yBins)   throw (std::runtime_error);
-  void setRebinMode(bool mode, bool locked)   throw (std::runtime_error);
-  void refreshRebin()   throw (std::runtime_error);
-};
-
-
-}; // end namespace
-}; // end namespace
-
-
-
-
-
-
-
-
-namespace MantidQt
-{
-namespace Factory
-{
-
-/***************************************************************************/
-/***************************************************************************/
-/***************************************************************************/
-class WidgetFactory
-{
-%TypeHeaderCode
-#include "Factory/inc/MantidQtFactory/WidgetFactory.h"
-#include <QVector>
-%End
-
-%Docstring
-WidgetFactory
-=============
-
-    The WidgetFactory is a class to create custom widgets.
-    It currently supports creating SliceViewerWindows using:
-        WidgetFactory.Instance().createSliceViewerWindow()
-
-    You can also retrieve a previously-created window with:
-        WidgetFactory.Instance().getSliceViewerWindow()
-    This applies to windows created by Python or via the GUI.
-
-%End
-
-
-public:
-  static MantidQt::Factory::WidgetFactory* Instance();
-  MantidQt::SliceViewer::SliceViewerWindow* createSliceViewerWindow(const QString& wsName, const QString& label);
-  MantidQt::SliceViewer::SliceViewerWindow* getSliceViewerWindow(const QString& wsName, const QString& label)   throw (std::runtime_error);
-  void closeAllSliceViewerWindows();
-
-  MantidQt::SliceViewer::SliceViewer* createSliceViewer(const QString& wsName);
-
-private:
-  WidgetFactory();
-};
-
-}; // end namespace
-}; // end namespace
-
-
-
-/****************************************************************************
-/*** RefDetectorViewer ******************************************************
-/****************************************************************************
-namespace MantidQt
-{
-namespace RefDetectorViewer
-{
-	
-//*WIKI* == Classes ==
-//*WIKI* Here follows a list of the classes exposed to python and the methods you can execute on them.
-
-
-
-
-
-
-
-
-/**************************************/
-/**************************************/
-/**************************************/
-
-class ArrayDataSource
-{
-%TypeHeaderCode
-#include "RefDetectorViewer/inc/MantidQtRefDetectorViewer/ArrayDataSource.h"
-%End
-%Docstring
-
-ArrayDataSource
-===============
-
-	This class provides a wrapper around a simple 2D array of doubles stored
-	in row-major order in a 1D array, so that the array can be viewed using
-	the RefDetector data viewer.
-
-%End
-
-public:
-	ArrayDataSource(double total_xmin, double total_xmax,
-				    double total_ymin, double total_ymax,
-				    int total_rows, int total_cols, 
-				    float* data);
-	MantidQt::RefDetectorViewer::DataArray* getDataArray( double xmin,
-														  double xmax,
-														  double ymin,
-														  double ymax,
-														  int n_rows,
-														  int n_cols,
-														  bool is_log_x);
-														  
-};
-
-
-
-
-
-
-
-/**************************************/
-/**************************************/
-/**************************************/
-
-class ImageView : QMainWindow
-{
-%TypeHeaderCode
-#include "RefDetectorViewer/inc/MantidQtRefDetectorViewer/ImageView.h"
-%End
-%Docstring
-
-ImageView
-=========
-
-	This is the QMainWindow for the RefDetectorViewer. Data is
-	displayed in an ImageView by constructing the ImageView object
-	and specifying a particular Data Source
-	
-%End
-
-public:
-	ImageView(ImageDataSource* dataSource);
-	
-};
-
-}; // end namespace
-}; // end namespace
-
-
-
-
-
-
-
-
diff --git a/Code/Mantid/MantidQt/Python/mantidqt.sip b/Code/Mantid/MantidQt/Python/mantidqt.sip
index 89b157802ef4eb028147b0af50470e9ab5506ac7..d3b4d115d6ea77d5710e1f6a5a26eb540be05cd7 100644
--- a/Code/Mantid/MantidQt/Python/mantidqt.sip
+++ b/Code/Mantid/MantidQt/Python/mantidqt.sip
@@ -1,9 +1,9 @@
 /***************************************************************************/
 /**
- This file is a SIP file for binding C++ methods of the 
+ This file is a SIP file for binding C++ methods of the
  MantidQt widgets (SliceViewer in particular)
  to Python.
- 
+
 */
 /***************************************************************************/
 
@@ -120,6 +120,17 @@ public:
                                                        QWidget* = 0, bool = false);
   MantidQt::API::UserSubWindow* createSubWindow(const QString& interface_name, QWidget* parent = 0);
 
+  void showHelpPage(const QString & url=QString());
+
+  void showWikiPage(const QString &page=QString());
+
+  void showAlgorithmHelp(const QString &name, const int version=-1);
+
+  void showConceptHelp(const QString &name);
+
+  void showFitFunctionHelp(const QString &name=QString());
+
+  void showCustomInterfaceHelp(const QString &name);
 };
 
 };
@@ -198,10 +209,10 @@ MantidQt::SliceViewer::SliceViewer* SliceViewerWindow::getSlicer()
     Get the SliceViewer widget inside the SliceViewerWindow.
     This is the main widget for controlling the 2D views
     and slice points.
-   
+
     Returns:
         a pointer to the SliceViewer widget.
-   
+
 %End
 
   MantidQt::SliceViewer::LineViewer* getLiner();
@@ -211,10 +222,10 @@ MantidQt::SliceViewer::LineViewer* SliceViewerWindow::getLiner()
     Get the LineViewer widget inside the SliceViewerWindow.
     This is the widget for controlling the 1D line integration
     settings.
-   
+
     Returns:
         a pointer to the LineViewer widget.
-   
+
 %End
 
   const QString& getLabel() const;
@@ -249,10 +260,10 @@ void apply()   throw (std::runtime_error);
 void LineViewer::apply()
 ------------------------
     Perform the 1D integration using the current parameters.
-    
+
     Raises:
         std::runtime_error if an error occurs.
-    
+
 %End
 
 void showPreview();
@@ -260,7 +271,7 @@ void showPreview();
 void LineViewer::showPreview()
 ------------------------------
     Calculate and show the preview (non-integrated) line,
-    using the current parameters. 
+    using the current parameters.
 %End
 
 void showFull();
@@ -269,7 +280,7 @@ void LineViewer::showFull()
 ---------------------------
     Calculate and show the full (integrated) line, using the latest
     integrated workspace. The apply() method must have been called
-    before calling this. 
+    before calling this.
 %End
 
 
@@ -279,13 +290,13 @@ void setStartXY(double x, double y)   throw (std::runtime_error);
 void LineViewer::setStartXY(double x, double y)
 -----------------------------------------------
     Set the start point of the line to integrate
-   
+
     Args:
         x :: position of the start in the "X" dimension
            (as shown in the SliceViewer).
         y :: position of the start in the "Y" dimension
            (as shown in the SliceViewer).
-   
+
 %End
 
 void setEndXY(double x, double y)   throw (std::runtime_error);
@@ -293,13 +304,13 @@ void setEndXY(double x, double y)   throw (std::runtime_error);
 void LineViewer::setEndXY(double x, double y)
 ---------------------------------------------
     Set the start point of the line to integrate
-   
+
     Args:
         x :: position of the start in the "X" dimension
            (as shown in the SliceViewer).
         y :: position of the start in the "Y" dimension
            (as shown in the SliceViewer).
-   
+
 %End
 
 
@@ -309,13 +320,13 @@ void setThickness(double width);
 void LineViewer::setThickness(double width)
 -------------------------------------------
     Set the thickness to integrate to be the same in all dimensions
-   
+
     This sets the planar width and all the other dimensions' thicknesses
     to the same value.
-   
+
     Args:
         width :: width of integration, in the units of all dimensions
-   
+
 %End
 
 void setThickness(int dim, double width)   throw (std::invalid_argument, std::runtime_error);
@@ -323,19 +334,19 @@ void setThickness(int dim, double width)   throw (std::invalid_argument, std::ru
 void LineViewer::setThickness(int dim, double width)
 ----------------------------------------------------
     Set the thickness to integrate in a particular dimension.
-   
+
     Integration is performed perpendicular to the XY plane,
     from -thickness below to +thickness above the center.
-   
+
     Use setPlanarWidth() to set the width along the XY plane.
-   
+
     Args:
         dim :: index of the dimension to change
         width :: width of integration, in the units of the dimension.
-    
+
     Raises:
         std::invalid_argument if the index is invalid
-   
+
 %End
 
 void setThickness(const QString & dim, double width)   throw (std::invalid_argument, std::runtime_error);
@@ -343,19 +354,19 @@ void setThickness(const QString & dim, double width)   throw (std::invalid_argum
 void LineViewer::setThickness(const QString & dim, double width)
 ----------------------------------------------------------------
     Set the thickness to integrate in a particular dimension.
-   
+
     Integration is performed perpendicular to the XY plane,
     from -thickness below to +thickness above the center.
-   
+
     Use setPlanarWidth() to set the width along the XY plane.
-   
+
     Args:
         dim :: name of the dimension to change
         width :: thickness of integration, in the units of the dimension.
-    
+
     Raises:
         std::runtime_error if the name is not found in the workspace
-   
+
 %End
 
 void setPlanarWidth(double width);
@@ -364,18 +375,18 @@ void LineViewer::setPlanarWidth(double width)
 ---------------------------------------------
     Set the width of the line in the planar dimension only.
     Other dimensions' widths will follow unless they were manually changed
-    
+
     Args:
-        width :: width in the plane. 
+        width :: width in the plane.
 %End
 
 double getPlanarWidth() const;
 %Docstring
 double LineViewer::getPlanarWidth()
 -----------------------------------
-    
+
     Returns:
-        the width in the plane, or the width in dimension 0 if not restricted to a plane 
+        the width in the plane, or the width in dimension 0 if not restricted to a plane
 %End
 
 
@@ -385,13 +396,13 @@ void setNumBins(int numBins)   throw (std::invalid_argument);
 void LineViewer::setNumBins(int numBins)
 ----------------------------------------
     Set the number of bins in the line.
-    
+
     Args:
         numBins :: # of bins
-    
+
     Raises:
         std::invalid_argument if numBins < 1
-    
+
 %End
 
 void setFixedBinWidthMode(bool fixedWidth, double binWidth)   throw (std::invalid_argument);
@@ -399,21 +410,21 @@ void setFixedBinWidthMode(bool fixedWidth, double binWidth)   throw (std::invali
 void LineViewer::setFixedBinWidthMode(bool fixedWidth, double binWidth)
 -----------------------------------------------------------------------
     Sets the fixed bin width mode on or off.
-   
+
     In fixed bin width mode, the width of each bin along the line length
     is constant, and the number of bins is adjusted to as the line
     gets longer.
     If off, then you use a fixed number of bins, and the bin width is
     then simply: width = length / number_of_bins.
-   
+
     Args:
         fixedWidth :: if True, then keep the bin width fixed.
         binWidth :: for fixed bin width mode, this specified the desired
            bin width. Must be > 0. Ignored for non-fixed-bin-width mode.
-    
+
     Raises:
         std::invalid_argument if binWidth <= 0
-   
+
 %End
 
 double getFixedBinWidth() const;
@@ -421,10 +432,10 @@ double getFixedBinWidth() const;
 double LineViewer::getFixedBinWidth()
 -------------------------------------
     For fixed-bin-width mode, get the desired fixed bin width.
-    
+
     Returns:
         the desired fixed bin width
-   
+
 %End
 
 bool getFixedBinWidthMode() const;
@@ -432,10 +443,10 @@ bool getFixedBinWidthMode() const;
 bool LineViewer::getFixedBinWidthMode()
 ---------------------------------------
     Is the LineViewer in fixed-bin-width mode?
-    
+
     Returns:
         True if in fixed bin width mode.
-   
+
 %End
 
 int getNumBins() const;
@@ -443,10 +454,10 @@ int getNumBins() const;
 int LineViewer::getNumBins()
 ----------------------------
     Get the number of bins
-   
+
     Returns:
         the number of bins in the line to integrate (int)
-   
+
 %End
 
 double getBinWidth() const;
@@ -454,10 +465,10 @@ double getBinWidth() const;
 double LineViewer::getBinWidth()
 --------------------------------
     Get the width of each bin
-   
+
     Returns:
         the width of each bin (double)
-   
+
 %End
 
 int getXAxisDimensionIndex() const;
@@ -465,10 +476,10 @@ int getXAxisDimensionIndex() const;
 int LineViewer::getXAxisDimensionIndex()
 --------------------------------
     Get the index of the dimension used for the x axis
-   
+
     Returns:
         the index of the dimension used for the x axis (int)
-   
+
 %End
 
 
@@ -478,10 +489,10 @@ void setPlotAxis(int choice);
 void LineViewer::setPlotAxis(int choice)
 ----------------------------------------
     Choose which coordinates to use as the X axis to plot in the line view.
-   
+
     Args:
         choice :: PlotAxisChoice, either Auto, X, Y or Distance.
-   
+
 %End
 
 int getPlotAxis() const;
@@ -489,10 +500,10 @@ int getPlotAxis() const;
 int LineViewer::getPlotAxis()
 -----------------------------
     Return which coordinates to use as the X axis to plot in the line view.
-   
+
     Returns:
         PlotAxisChoice, either Auto, X, Y or Distance.
-   
+
 %End
 
 
@@ -522,46 +533,46 @@ public:
 void PeaksPresenter::setForegroundColor(const QColor color)
 ------------------------------------------------------
     Sets the Foreground color of the peaks workspace as displayed in the peaks overlay.
-   
+
     Args:
         color :: color to change foreground to
-%End    
+%End
     virtual void setForegroundColor(const QColor) = 0;
 %Docstring
 void PeaksPresenter::setBackgroundColor(const QColor color)
 ------------------------------------------------------
     Sets the Background color of the peaks workspace as displayed in the peaks overlay.
-   
+
     Args:
         color :: color to change background to
-%End  
+%End
     virtual void setBackgroundColor(const QColor) = 0;
 %Docstring
 void PeaksPresenter::showBackgroundRadius(const bool shown)
 ------------------------------------------------------
     Toggle the background radius on and off.
-   
+
     Args:
         shown :: True to show the background radius, otherwise false.
-%End 
+%End
     virtual void showBackgroundRadius(const bool shown) = 0;
 %Docstring
 void PeaksPresenter::setShown(const bool shown)
 ------------------------------------------------------
     Toggle the overplotted state of this PeaksWorkspace in the PeaksOverlay
-   
+
     Args:
         shown :: True to show. False to hide.
-%End     
+%End
     virtual void setShown(const bool shown) = 0;
 %Docstring
 void PeaksPresenter::zoomToPeak(const int index)
 ------------------------------------------------------
     Zoom in on a peak of the PeaksWorkspace. Provide an index (0 based) to go to the peak.
-   
+
     Args:
         index :: Index into the peaks workspace (0 based) to zoom to.
-%End 
+%End
     virtual void zoomToPeak(const int index) = 0;
 };
 
@@ -610,24 +621,24 @@ void SliceViewer::setWorkspace(const QString & wsName)
     Set the workspace to view using its name.
     The workspace should be a MDHistoWorkspace or a MDEventWorkspace,
     with at least 2 dimensions.
-   
+
     Args:
         wsName :: name of the MDWorkspace to look for
-    
+
     Raises:
         std::runtime_error if the workspace is not found or is a MatrixWorkspace
-   
+
 %End
 
   QString getWorkspaceName() const;
 %Docstring
 QString SliceViewer::getWorkspaceName()
 ---------------------------------------
-    
+
     Returns:
         the name of the workspace selected, or a blank string
     if no workspace is set.
-   
+
 %End
 
   void showControls(bool visible);
@@ -635,10 +646,10 @@ QString SliceViewer::getWorkspaceName()
 void SliceViewer::showControls(bool visible)
 --------------------------------------------
     Programmatically show/hide the controls (sliders etc)
-   
+
     Args:
         visible :: true if you want to show the controls.
-   
+
 %End
 
   void openFromXML(const QString & xml)   throw (std::invalid_argument, std::runtime_error);
@@ -647,13 +658,13 @@ void SliceViewer::openFromXML(const QString & xml)
 --------------------------------------------------
     Opens a workspace and sets the view and slice points
     given the XML from the MultiSlice view in XML format.
-   
+
     Args:
         xml :: string describing workspace, slice point, etc.
-    
+
     Raises:
         std::runtime_error if error in parsing XML
-   
+
 %End
 
   QPixmap getImage();
@@ -662,12 +673,12 @@ QPixmap SliceViewer::getImage()
 -------------------------------
     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.
-   
+
     See also saveImage() and copyImageToClipboard()
-   
+
     Returns:
         QPixmap containing the image.
-   
+
 %End
 
   void saveImage(const QString & filename);
@@ -675,12 +686,12 @@ QPixmap SliceViewer::getImage()
 void SliceViewer::saveImage(const QString & filename)
 -----------------------------------------------------
     Save the rendered 2D slice to an image file.
-   
+
     Args:
         filename :: full path to the file to save, including extension
            (e.g. .png). If not specified or empty, then a dialog will prompt
            the user to pick a file.
-   
+
 %End
 
   void copyImageToClipboard();
@@ -688,7 +699,7 @@ void SliceViewer::saveImage(const QString & filename)
 void SliceViewer::copyImageToClipboard()
 ----------------------------------------
     Copy the rendered 2D image to the clipboard
-   
+
 %End
 
   void setFastRender(bool fast);
@@ -697,15 +708,15 @@ void SliceViewer::setFastRender(bool fast)
 ------------------------------------------
     Sets whether the image should be rendered in "fast" mode, where
     the workspace's resolution is used to guess how many pixels to render.
-   
+
     If false, each pixel on screen will be rendered. This is the most
     accurate view but the slowest.
-   
+
     This redraws the screen.
-   
+
     Args:
         fast :: true to use "fast" rendering mode.
-   
+
 %End
 
   bool getFastRender() const;
@@ -713,14 +724,14 @@ void SliceViewer::setFastRender(bool fast)
 bool SliceViewer::getFastRender()
 ---------------------------------
     Return true if the image is in "fast" rendering mode.
-   
+
     In "fast" mode, the workspace's resolution is used to guess how many
     pixels to render. If false, each pixel on screen will be rendered.
     This is the most accurate view but the slowest.
-   
+
     Returns:
         True if the image is in "fast" rendering mode.
-   
+
 %End
 
   void toggleLineMode(bool lineMode);
@@ -728,10 +739,10 @@ bool SliceViewer::getFastRender()
 void SliceViewer::toggleLineMode(bool lineMode)
 -----------------------------------------------
     Toggle "line-drawing" mode (to draw 1D lines using the mouse)
-   
+
     Args:
         lineMode :: True to go into line mode, False to exit it.
-   
+
 %End
 
 
@@ -743,16 +754,16 @@ void SliceViewer::setXYDim(int indexX, int indexY)
     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.
-   
+
     To be called from Python, primarily.
-   
+
     Args:
         indexX :: index of the X dimension, from 0 to NDims-1.
         indexY :: index of the Y dimension, from 0 to NDims-1.
-    
+
     Raises:
         std::invalid_argument if an index is invalid or repeated.
-   
+
 %End
 
   void setXYDim(const QString & dimX, const QString & dimY)     throw (std::invalid_argument, std::runtime_error);
@@ -760,36 +771,36 @@ void SliceViewer::setXYDim(int indexX, int indexY)
 void SliceViewer::setXYDim(const QString & dimX, const QString & dimY)
 ----------------------------------------------------------------------
     Set the dimensions that will be shown as the X and Y axes
-   
+
     Args:
         dimX :: name of the X dimension. Must match the workspace dimension names.
         dimY :: name of the Y dimension. Must match the workspace dimension names.
-    
+
     Raises:
         std::runtime_error if the dimension name is not found.
-   
+
 %End
 
   int getDimX() const;
 %Docstring
 int SliceViewer::getDimX()
 --------------------------
-    
+
     Returns:
         the index of the dimension that is currently
     being shown as the X axis of the plot.
-   
+
 %End
 
   int getDimY() const;
 %Docstring
 int SliceViewer::getDimY()
 --------------------------
-    
+
     Returns:
         the index of the dimension that is currently
     being shown as the Y axis of the plot.
-   
+
 %End
 
 
@@ -800,15 +811,15 @@ void SliceViewer::setSlicePoint(int dim, double value)
 ------------------------------------------------------
     Sets the slice point in the given dimension:
     that is, what is the position of the plane in that dimension
-   
+
     Args:
         dim :: index of the dimension to change
         value :: value of the slice point, in the units of the given dimension.
            This should be within the range of min/max for that dimension.
-    
+
     Raises:
         std::invalid_argument if the index is invalid
-   
+
 %End
 
   void setSlicePoint(const QString & dim, double value)   throw (std::invalid_argument, std::runtime_error);
@@ -817,15 +828,15 @@ void SliceViewer::setSlicePoint(const QString & dim, double value)
 ------------------------------------------------------------------
     Sets the slice point in the given dimension:
     that is, what is the position of the plane in that dimension
-   
+
     Args:
         dim :: name of the dimension to change
         value :: value of the slice point, in the units of the given dimension.
            This should be within the range of min/max for that dimension.
-    
+
     Raises:
         std::runtime_error if the name is not found in the workspace
-   
+
 %End
 
   double getSlicePoint(int dim) const     throw (std::invalid_argument);
@@ -833,17 +844,17 @@ void SliceViewer::setSlicePoint(const QString & dim, double value)
 double SliceViewer::getSlicePoint(int dim)
 ------------------------------------------
     Returns the slice point in the given dimension
-   
+
     Args:
         dim :: index of the dimension
-    
+
     Returns:
         slice point for that dimension. Value has no significance for the
             X or Y display dimensions.
-    
+
     Raises:
         std::invalid_argument if the index is invalid
-   
+
 %End
 
   double getSlicePoint(const QString & dim) const   throw (std::invalid_argument, std::runtime_error);
@@ -851,17 +862,17 @@ double SliceViewer::getSlicePoint(int dim)
 double SliceViewer::getSlicePoint(const QString & dim)
 ------------------------------------------------------
     Returns the slice point in the given dimension
-   
+
     Args:
         dim :: name of the dimension
-    
+
     Returns:
         slice point for that dimension. Value has no significance for the
             X or Y display dimensions.
-    
+
     Raises:
         std::runtime_error if the name is not found in the workspace
-   
+
 %End
 
 
@@ -874,34 +885,34 @@ void SliceViewer::setXYLimits(double xleft, double xright, double ybottom, doubl
     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
     dimensions in the displayed workspace using setXYDim().
-   
+
     You can flip the direction of the scale if you specify,
     e.g., xleft > xright.
-   
+
     Args:
         xleft   :: x-value on the left side of the graph
         xright  :: x-value on the right side of the graph
         ybottom :: y-value on the bottom of the graph
         ytop    :: y-value on the top of the graph
-   
+
 %End
 
   QwtDoubleInterval getXLimits() const;
 %Docstring
 QwtDoubleInterval SliceViewer::getXLimits()
 -------------------------------------------
-    
+
     Returns:
-        Returns the [left, right] limits of the view in the X axis. 
+        Returns the [left, right] limits of the view in the X axis.
 %End
 
   QwtDoubleInterval getYLimits() const;
 %Docstring
 QwtDoubleInterval SliceViewer::getYLimits()
 -------------------------------------------
-    
+
     Returns:
-        Returns the [bottom, top] limits of the view in the Y axis. 
+        Returns the [bottom, top] limits of the view in the Y axis.
 %End
 
   void zoomBy(double factor);
@@ -909,11 +920,11 @@ QwtDoubleInterval SliceViewer::getYLimits()
 void SliceViewer::zoomBy(double factor)
 ---------------------------------------
     Zoom in or out, keeping the center of the plot in the same position.
-   
+
     Args:
         factor :: double, if > 1 : zoom in by this factor.
                      if < 1 : it will zoom out.
-   
+
 %End
 
   void setXYCenter(double x, double y);
@@ -924,11 +935,11 @@ void SliceViewer::setXYCenter(double x, double y)
     This keeps the plot the same size as previously.
     Use setXYLimits() to modify the size of the plot by setting the X/Y edges,
     or you can use zoomBy() to zoom in/out
-   
+
     Args:
         x :: new position of the center in X
         y :: new position of the center in Y
-   
+
 %End
 
   void resetZoom();
@@ -939,7 +950,7 @@ void SliceViewer::resetZoom()
     This will reset the XY limits to the full range of the workspace.
     Use zoomBy() or setXYLimits() to modify the view range.
     This corresponds to the "View Extents" button.
-   
+
 %End
 
 
@@ -949,10 +960,10 @@ void SliceViewer::resetZoom()
 void SliceViewer::loadColorMap(QString filename)
 ------------------------------------------------
     Load a color map from a file
-   
+
     Args:
         filename :: file to open; empty to ask via a dialog box.
-   
+
 %End
 
   void setColorScale(double min, double max, bool log)      throw (std::invalid_argument);
@@ -960,16 +971,16 @@ void SliceViewer::loadColorMap(QString filename)
 void SliceViewer::setColorScale(double min, double max, bool log)
 -----------------------------------------------------------------
     Set the color scale limits and log mode via a method call.
-   
+
     Args:
         min :: minimum value corresponding to the lowest color on the map
         max :: maximum value corresponding to the highest color on the map
         log :: true for a log color scale, false for linear
-    
+
     Raises:
         std::invalid_argument if max < min or if the values are
            inconsistent with a log color scale
-   
+
 %End
 
   void setColorScaleMin(double min)      throw (std::invalid_argument);
@@ -977,14 +988,14 @@ void SliceViewer::setColorScale(double min, double max, bool log)
 void SliceViewer::setColorScaleMin(double min)
 ----------------------------------------------
     Set the minimum value corresponding to the lowest color on the map
-   
+
     Args:
         min :: minimum value corresponding to the lowest color on the map
-    
+
     Raises:
         std::invalid_argument if max < min or if the values are
            inconsistent with a log color scale
-   
+
 %End
 
   void setColorScaleMax(double max)      throw (std::invalid_argument);
@@ -992,14 +1003,14 @@ void SliceViewer::setColorScaleMin(double min)
 void SliceViewer::setColorScaleMax(double max)
 ----------------------------------------------
     Set the maximum value corresponding to the lowest color on the map
-   
+
     Args:
         max :: maximum value corresponding to the lowest color on the map
-    
+
     Raises:
         std::invalid_argument if max < min or if the values are
            inconsistent with a log color scale
-   
+
 %End
 
   void setColorScaleLog(bool log);
@@ -1007,41 +1018,41 @@ void SliceViewer::setColorScaleMax(double max)
 void SliceViewer::setColorScaleLog(bool log)
 --------------------------------------------
     Set whether the color scale is logarithmic
-   
+
     Args:
         log :: true for a log color scale, false for linear
-    
+
     Raises:
         std::invalid_argument if the min/max values are inconsistent
            with a log color scale
-   
+
 %End
 
   double getColorScaleMin() const;
 %Docstring
 double SliceViewer::getColorScaleMin()
 --------------------------------------
-    
+
     Returns:
-        the value that corresponds to the lowest color on the color map 
+        the value that corresponds to the lowest color on the color map
 %End
 
   double getColorScaleMax() const;
 %Docstring
 double SliceViewer::getColorScaleMax()
 --------------------------------------
-    
+
     Returns:
-        the value that corresponds to the highest color on the color map 
+        the value that corresponds to the highest color on the color map
 %End
 
   bool getColorScaleLog() const;
 %Docstring
 bool SliceViewer::getColorScaleLog()
 ------------------------------------
-    
+
     Returns:
-        True if the color scale is in logarithmic mode 
+        True if the color scale is in logarithmic mode
 %End
 
   void setColorScaleAutoFull();
@@ -1051,7 +1062,7 @@ void SliceViewer::setColorScaleAutoFull()
     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).
-   
+
 %End
 
   void setColorScaleAutoSlice() ;
@@ -1062,7 +1073,7 @@ void SliceViewer::setColorScaleAutoSlice()
     using the limits in the data that is currently visible
     in the plot (only the bins in this slice and within the
     view limits)
-   
+
 %End
 
   void setColorMapBackground(int r, int g, int b);
@@ -1070,18 +1081,18 @@ void SliceViewer::setColorScaleAutoSlice()
 void SliceViewer::setColorMapBackground(int r, int g, int b)
 ------------------------------------------------------------
     Set the "background" color to use in the color map. Default is white.
-   
+
     This is the color that is shown when:
-   
+
      - The coordinate is out of bounds of the workspace.
      - When a signal is NAN (not-a-number).
      - When the signal is Zero, if that option is selected using setTransparentZeros()
-   
+
     Args:
         r :: red component, from 0-255
         g :: green component, from 0-255
         b :: blue component, from 0-255
-   
+
 %End
 
   void setTransparentZeros(bool transparent);
@@ -1089,10 +1100,10 @@ void SliceViewer::setColorMapBackground(int r, int g, int b)
 void SliceViewer::setTransparentZeros(bool transparent)
 -------------------------------------------------------
     Set whether to display 0 signal as "transparent" color.
-   
+
     Args:
         transparent :: true if you want zeros to be transparent.
-   
+
 %End
 
   void setNormalization(Mantid::API::MDNormalization norm);
@@ -1100,19 +1111,19 @@ void SliceViewer::setTransparentZeros(bool transparent)
 void SliceViewer::setNormalization(Mantid::API::MDNormalization norm)
 ---------------------------------------------------------------------
     Set the normalization mode for viewing the data
-   
+
     Args:
         norm :: MDNormalization enum. 0=none; 1=volume; 2=# of events
-   
+
 %End
 
   Mantid::API::MDNormalization getNormalization() const;
 %Docstring
 Mantid::API::MDNormalization SliceViewer::getNormalization()
 ------------------------------------------------------------
-    
+
     Returns:
-        the current normalization 
+        the current normalization
 %End
 
 
@@ -1122,14 +1133,14 @@ Mantid::API::MDNormalization SliceViewer::getNormalization()
 void SliceViewer::setRebinThickness(int dim, double thickness)
 --------------------------------------------------------------
     Set the thickness (above and below the plane) for dynamic rebinning.
-   
+
     Args:
         dim :: index of the dimension to adjust
         thickness :: thickness to set, in units of the dimension.
-    
+
     Raises:
         runtime_error if the dimension index is invalid or the thickness is <= 0.0.
-   
+
 %End
 
   void setRebinNumBins(int xBins, int yBins)   throw (std::runtime_error);
@@ -1137,14 +1148,14 @@ void SliceViewer::setRebinThickness(int dim, double thickness)
 void SliceViewer::setRebinNumBins(int xBins, int yBins)
 -------------------------------------------------------
     Set the number of bins for dynamic rebinning.
-   
+
     Args:
         xBins :: number of bins in the viewed X direction
         yBins :: number of bins in the viewed Y direction
-    
+
     Raises:
         runtime_error if the number of bins is < 1
-   
+
 %End
 
   void setRebinMode(bool mode, bool locked)   throw (std::runtime_error);
@@ -1156,12 +1167,12 @@ void SliceViewer::setRebinMode(bool mode, bool locked)
     limits to rebin.
     See setRebinNumBins() to adjust the number of bins in the X/Y dimensions.
     See setRebinThickness() to adjust the thickness in other dimensions.
-   
+
     Args:
         mode :: true for rebinning mode
         locked :: if true, then the rebinned area is only refreshed manually
            or when changing rebinning parameters.
-   
+
 %End
 
   void refreshRebin()   throw (std::runtime_error);
@@ -1170,16 +1181,16 @@ void SliceViewer::refreshRebin()
 --------------------------------
     When in dynamic rebinning mode, this refreshes the rebinned area to be the
     currently viewed area. See setXYLimits(), setRebinNumBins(), setRebinThickness()
-   
+
 %End
 
   MantidQt::SliceViewer::ProxyCompositePeaksPresenter* setPeaksWorkspaces(const QStringList&);
 %Docstring
 void SliceViewer::setPeaksWorkspaces(const QStringList&)
 --------------------------------
-    Enable overplotting of one or more peaks workspaces. 
+    Enable overplotting of one or more peaks workspaces.
     See clearPeaksWorkspaces() for removal.
-   
+
 %End
 
   void clearPeaksWorkspaces();
@@ -1188,7 +1199,7 @@ void SliceViewer::clearPeaksWorkspaces()
 --------------------------------
     Clear overplotting of all overplotted peaks workspaces.
     See setPeaksWorkspaces() for addition.
-   
+
 %End
 };
 
@@ -1241,7 +1252,7 @@ public:
 void WidgetFactory::closeAllSliceViewerWindows()
 ------------------------------------------------
     Closes every previously-open instance of a SliceViewerWindow.
-   
+
 %End
 
 
@@ -1252,15 +1263,15 @@ MantidQt::SliceViewer::SliceViewer* WidgetFactory::createSliceViewer(const QStri
     Create an instance of a bare SliceViewer Widget.
     This is only capable of doing 2D views, and cannot do line plots
     since it does not have a LineViewer.
-   
+
     Use WidgetFactory::createSliceViewerWindow to create a window combining both.
-   
+
     Args:
         wsName :: name of the workspace to show. Optional, blank for no workspace.
-    
+
     Returns:
         the created SliceViewer *
-   
+
 %End
 
 
@@ -1272,7 +1283,7 @@ WidgetFactory::WidgetFactory()
     Private constructor. This is not accessible,
     use the Instance() method to access the singleton instance
     instead.
-   
+
 %End
 
 };
@@ -1301,7 +1312,7 @@ class RefIVConnections: QWidget
 
 RefIVConnections
 ================
-    A RefIVConnections object is responsible for emitting signals about 
+    A RefIVConnections object is responsible for emitting signals about
     changes in the state of the image view.
 %End
 
@@ -1325,26 +1336,26 @@ RefMatrixWSImageView
     A RefMatrixWSImageView is the gateway to the image view display. To
     bring up an image display simply construct an object of this type, i.e.
         image_view = RefMatrixWSImageView("test_ws")
-        
+
     See the methods for RefMatrixWSImageView, below.
 %End
 
 
 public:
   RefMatrixWSImageView(QString wsname, int peak_min, int peak_max, int back_min, int back_max, int tof_min, int tof_max);
-  
+
   MantidQt::RefDetectorViewer::RefIVConnections * getConnections();
 %Docstring
 MantidQt::RefDetectorViewer::RefIVConnections* RefMatrixWSImageView::getConnections()
 -------------------------------------------------------------------------------------
     Get the connections widget inside the image view. This object is responsible for
     emitting signals about changes in the state of the image view.
-   
+
     Returns:
         a pointer to the RefIVConnections object.
-   
+
 %End
-  
+
 
 };
 
diff --git a/Code/Mantid/Testing/Data/UnitTest/ENGINX00228061.nxs.md5 b/Code/Mantid/Testing/Data/UnitTest/ENGINX00228061.nxs.md5
new file mode 100644
index 0000000000000000000000000000000000000000..1cb7b8dde68c0053180a9e299dbf0b2316ad66ee
--- /dev/null
+++ b/Code/Mantid/Testing/Data/UnitTest/ENGINX00228061.nxs.md5
@@ -0,0 +1 @@
+7607c04f6cbc9fbb7a6c205bbe97c01d
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/CalibrateRectangularDetector_Test.py b/Code/Mantid/Testing/SystemTests/tests/analysis/CalibrateRectangularDetector_Test.py
index 13fc2950bf67b8e28e1029bd54991c9bc74f86ca..f4bcac786a4bb6bbcce9842157170474a7546c8b 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/CalibrateRectangularDetector_Test.py
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/CalibrateRectangularDetector_Test.py
@@ -7,7 +7,10 @@ def _skip_test():
     """Helper function to determine if we run the test"""
     import platform
 
-    # Only runs on RHEL6 at the moment
+    # don't run on rhel6
+    if "redhat-6" in platform.platform():
+        return True
+    # run on any other linux
     return ("Linux" not in platform.platform())
 
 class PG3Calibration(stresstesting.MantidStressTest):
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/EnginXCalibrateTest.py b/Code/Mantid/Testing/SystemTests/tests/analysis/EnginXCalibrateTest.py
index e52c9093a086bfb9af2ccf91b0cab9f3adf05ef3..2dd1ae90bf144788dd003cfe89dfe32b942d3760 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/EnginXCalibrateTest.py
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/EnginXCalibrateTest.py
@@ -24,10 +24,10 @@ class EnginXCalibrateTest(stresstesting.MantidStressTest):
         if sys.platform == "darwin":
           # Mac fitting tests produce differences for some reason.
             self.assertDelta(self.difc, 18405.4, 0.1)
-            self.assertDelta(self.zero, 3.53, 0.05)
+            self.assertDelta(self.zero, 3.60, 0.05)
         else:
-            self.assertDelta(self.difc, 18404.522, 0.001)
-            self.assertDelta(self.zero, 4.426, 0.001)
+            self.assertDelta(self.difc, 18404.496, 0.001)
+            self.assertDelta(self.zero, 4.4345, 0.001)
 
     def cleanup(self):
         mtd.remove('positions')
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/OffspecSESANS.py b/Code/Mantid/Testing/SystemTests/tests/analysis/OffspecSESANS.py
deleted file mode 100644
index 44fb2fd8250b00ebebee0a4f7e420783e02212d8..0000000000000000000000000000000000000000
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/OffspecSESANS.py
+++ /dev/null
@@ -1,27 +0,0 @@
-#pylint: disable=no-init,unused-import
-from stresstesting import MantidStressTest
-from mantid.simpleapi import config
-
-class OffspecSESANS(MantidStressTest):
-
-    def skipTests(self):
-        skip = False
-        try:
-            import offspec
-        except ImportError:
-            skip = True
-        return skip
-
-    def requiredFiles(self):
-        return ["OFFSPEC00010791.raw","OFFSPEC00010792.raw","OFFSPEC00010793.raw"]
-
-    def runTest(self):
-        import offspec
-        binning=["2.0","0.2","12.0","2"]
-        config["default.instrument"] = "OFFSPEC"
-        offspec.nrSESANSP0Fn("10792","P055","109","119","2","1",binning)
-        offspec.nrSESANSFn("10791+10793","dPMMA","","P055pol",
-                           "100","130","2","1","2","3009.9",binning,"2","0")
-
-    def validate(self):
-        return "dPMMASESANS","OffspecSESANS.nxs"
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/OffspecSESANSP0.py b/Code/Mantid/Testing/SystemTests/tests/analysis/OffspecSESANSP0.py
deleted file mode 100644
index c5d2517bb5712594025806a1e269b5ad874f744a..0000000000000000000000000000000000000000
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/OffspecSESANSP0.py
+++ /dev/null
@@ -1,28 +0,0 @@
-#pylint: disable=no-init
-from stresstesting import MantidStressTest
-from mantid.simpleapi import config
-
-class OffspecSESANSP0(MantidStressTest):
-
-    def skipTests(self):
-        skip = False
-        try:
-            import offspec
-        except ImportError:
-            skip = True
-        return skip
-
-    def requiredFiles(self):
-        return ["OFFSPEC00010792.raw"]
-
-    def runTest(self):
-        import offspec
-        binning=["2.0","0.2","12.0","2"]
-        config["default.instrument"] = "OFFSPEC"
-        offspec.nrSESANSP0Fn("10792","P055","109","119","2","1",binning)
-
-    def cleanup(self):
-        pass
-
-    def validate(self):
-        return "P055pol","OffspecSESANSP0.nxs"
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/SpaceGroupFactoryTest.py b/Code/Mantid/Testing/SystemTests/tests/analysis/SpaceGroupFactoryTest.py
index 65609fce93531b59158f07ae28d26aed94b85a68..b3a3cc068805ca2e5736b474b31dbaa8fd2d9a46 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/SpaceGroupFactoryTest.py
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/SpaceGroupFactoryTest.py
@@ -21,6 +21,10 @@ class SpaceGroupFactoryTest(stresstesting.MantidStressTest):
     def checkSpaceGroup(self, symbol):
         group = SpaceGroupFactory.createSpaceGroup(symbol)
 
+        self.assertTrue(group.isGroup(),
+                        ("Space group " + str(group.getNumber()) + " (" + symbol + ") does not "
+                        "fulfill group axioms"))
+
         groupOperations = set(group.getSymmetryOperationStrings())
         referenceOperations = self.spaceGroupData[group.getNumber()]
 
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/reference/PG3_4866_reference.gsa.md5 b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/PG3_4866_reference.gsa.md5
index 4098ae460a70c30ef5dfb07d8f4f997cbcfc428d..36d98dddb064c4a37b38d689373e5699585f87d8 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/reference/PG3_4866_reference.gsa.md5
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/PG3_4866_reference.gsa.md5
@@ -1 +1 @@
-f06a8fc5325f3ae2f9a0d25668df8c1e
\ No newline at end of file
+72b172aaf014201035cf0549a4cc026a
diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/reference/PG3_golden.cal.md5 b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/PG3_golden.cal.md5
index 64215e72c7c3e52fae9f3fa358a400974fa1f586..56c87345a23e1ac08bde40117461a11488956170 100644
--- a/Code/Mantid/Testing/SystemTests/tests/analysis/reference/PG3_golden.cal.md5
+++ b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/PG3_golden.cal.md5
@@ -1 +1 @@
-69889b01c7aa33d5802360a8182740e1
\ No newline at end of file
+fc483dfa4759f0f754ce03a362b89a7e
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/vtkScaleWorkspace.cxx b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/vtkScaleWorkspace.cxx
index cb73097af1a5fd6acf1c30ef7db50a9c97f5cd6e..18e57fefaee4b04fee465e37d79fa0c60b158d17 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/vtkScaleWorkspace.cxx
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/vtkScaleWorkspace.cxx
@@ -45,6 +45,10 @@ int vtkScaleWorkspace::RequestData(vtkInformation*, vtkInformationVector **input
   vtkDataSetToScaledDataSet scaler(inputDataSet, outputDataSet);
   scaler.initialize(m_xScaling, m_yScaling, m_zScaling);
   scaler.execute();
+
+  // Need to call an update on the meta data, as it is not guaranteed that RequestInformation will be called
+  // before we access the metadata.
+  updateMetaData(inputDataSet);
   return 1;
 }
 
@@ -53,20 +57,7 @@ int vtkScaleWorkspace::RequestInformation(vtkInformation*, vtkInformationVector*
   // Set the meta data 
   vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
   vtkUnstructuredGrid *inputDataSet = vtkUnstructuredGrid::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT()));
-
-  vtkFieldData* fieldData = inputDataSet->GetFieldData();
-  
-  // Extract information for meta data in Json format.
-  FieldDataToMetadata fieldDataToMetadata;
-
-  std::string jsonString = fieldDataToMetadata(fieldData, m_vatesConfigurations->getMetadataIdJson());
-  m_metadataJsonManager->readInSerializedJson(jsonString);
-
-  m_minValue = m_metadataJsonManager->getMinValue();
-  m_maxValue = m_metadataJsonManager->getMaxValue();
-  m_instrument = m_metadataJsonManager->getInstrument();
-  m_specialCoordinates = m_metadataJsonManager->getSpecialCoordinates();
-
+  updateMetaData(inputDataSet);
   return 1;
 }
 
@@ -146,4 +137,23 @@ const char* vtkScaleWorkspace::GetInstrument()
 int vtkScaleWorkspace::GetSpecialCoordinates()
 {
   return m_specialCoordinates;
+}
+
+/**
+ * Update the metadata fields of the plugin based on the information of the inputDataSet
+ * @param inputDataSet :: the input data set.
+ */
+void vtkScaleWorkspace::updateMetaData(vtkUnstructuredGrid *inputDataSet) {
+  vtkFieldData* fieldData = inputDataSet->GetFieldData();
+  
+  // Extract information for meta data in Json format.
+  FieldDataToMetadata fieldDataToMetadata;
+
+  std::string jsonString = fieldDataToMetadata(fieldData, m_vatesConfigurations->getMetadataIdJson());
+  m_metadataJsonManager->readInSerializedJson(jsonString);
+
+  m_minValue = m_metadataJsonManager->getMinValue();
+  m_maxValue = m_metadataJsonManager->getMaxValue();
+  m_instrument = m_metadataJsonManager->getInstrument();
+  m_specialCoordinates = m_metadataJsonManager->getSpecialCoordinates();
 }
\ No newline at end of file
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/vtkScaleWorkspace.h b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/vtkScaleWorkspace.h
index de4d54991d0e47166611445d15e7d0a7ce8e749a..55fb8eb7241d4b490e073513603d9577ea6f6573 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/vtkScaleWorkspace.h
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/vtkScaleWorkspace.h
@@ -28,6 +28,7 @@ protected:
 private:
   vtkScaleWorkspace(const vtkScaleWorkspace&);
   void operator = (const vtkScaleWorkspace&);
+  void updateMetaData(vtkUnstructuredGrid *inputDataSet);
   double m_xScaling;
   double m_yScaling;
   double m_zScaling;
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/CMakeLists.txt b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/CMakeLists.txt
index 3b65aaaf2e61fe2ab3f6aa287222f25e697d022c..86f54cc2f1a94310d2a7c761f9fb46d556ec8adb 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/CMakeLists.txt
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/CMakeLists.txt
@@ -1,6 +1,3 @@
-# add_subdirectory( SQWReader ) #Candidate for removal
-add_subdirectory( SQWEventReader ) 
-add_subdirectory( EventNexusReader )
 add_subdirectory( MDEWNexusReader )
 add_subdirectory( PeaksReader )
 add_subdirectory( NexusPeaksReader )
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/EventNexusReader.xml b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/EventNexusReader.xml
deleted file mode 100644
index 1aa53472280d2bc921847362747ecb1a8269fb11..0000000000000000000000000000000000000000
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/EventNexusReader.xml
+++ /dev/null
@@ -1,54 +0,0 @@
-<ServerManagerConfiguration>
-  <!-- Begin EventNexusReader -->
-  <ProxyGroup name="sources">
-    <SourceProxy name="EventNexusReader" class="vtkEventNexusReader">
-	    <StringVectorProperty
-         name="WorkspaceTypeName"
-         command="GetWorkspaceTypeName"
-         number_of_elements="1"
-         information_only="1">
-        <SimpleStringInformationHelper /> 
-       </StringVectorProperty>
-	    <IntVectorProperty
-         name="Load All Into Memory"
-         command="SetInMemory"
-         number_of_elements="1"
-         default_values="0">
-         <BooleanDomain name="bool"/>
-        </IntVectorProperty>
-		<IntVectorProperty
-         name="Recursion Depth"
-         command="SetDepth"
-         number_of_elements="1"
-         default_values="5">
-       </IntVectorProperty>
-	   <StringVectorProperty
-         name="InputGeometryXML"
-         command="GetInputGeometryXML"
-         number_of_elements="1"
-         information_only="1">
-        <SimpleStringInformationHelper /> 
-       </StringVectorProperty>
-       <StringVectorProperty
-        name="FileName"
-        command="SetFileName"
-        number_of_elements="1">
-        <FileListDomain name="files"/>
-      </StringVectorProperty>
-	  <DoubleVectorProperty 
-        name="TimestepValues"
-        information_only="1">
-        <TimeStepsInformationHelper/>
-        <Documentation>
-          Available timestep values.
-        </Documentation>
-      </DoubleVectorProperty>
-      <Hints>
-        <ReaderFactory
-          extensions="nxs"
-          file_description="Event Nexus File" />
-      </Hints>
-    </SourceProxy>
-  </ProxyGroup>
-  <!-- End EventNexusReader -->
-</ServerManagerConfiguration>
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/EventNexusReaderGUI.xml b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/EventNexusReaderGUI.xml
deleted file mode 100644
index 72280ea634edc77e49fab7245b39d9d6f81c99fd..0000000000000000000000000000000000000000
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/EventNexusReaderGUI.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<ParaViewReaders>
-  <Reader name="EventNexusReader"
-    extensions="nxs"
-    file_description="Event Nexus File">
-  </Reader>
-</ParaViewReaders>
\ No newline at end of file
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/vtkEventNexusReader.cxx b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/vtkEventNexusReader.cxx
deleted file mode 100644
index c48089d1f5af1a256f6921b654b25f8a9d62cd0d..0000000000000000000000000000000000000000
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/vtkEventNexusReader.cxx
+++ /dev/null
@@ -1,225 +0,0 @@
-#include "vtkEventNexusReader.h"
-#include "vtkInformation.h"
-#include "vtkInformationVector.h"
-#include "vtkObjectFactory.h"
-#include "vtkCellArray.h"
-#include "vtkCellData.h"
-#include "vtkPointData.h"
-#include "vtkTransform.h"
-#include "vtkFloatArray.h"
-#include "vtkStreamingDemandDrivenPipeline.h"
-#include "vtkPVClipDataSet.h"
-#include "vtkPVInformationKeys.h"
-#include "vtkBox.h"
-#include "vtkUnstructuredGrid.h"
-#include "MantidVatesAPI/vtkMDHexFactory.h"
-#include "MantidVatesAPI/vtkMDQuadFactory.h"
-#include "MantidVatesAPI/vtkMDLineFactory.h"
-#include "MantidVatesAPI/IgnoreZerosThresholdRange.h"
-#include "MantidVatesAPI/FilteringUpdateProgressAction.h"
-#include "MantidVatesAPI/MDLoadingViewAdapter.h"
-
-vtkStandardNewMacro(vtkEventNexusReader)
-
-using namespace Mantid::VATES;
-using Mantid::Geometry::IMDDimension_sptr;
-using Mantid::Geometry::IMDDimension_sptr;
-
-
-vtkEventNexusReader::vtkEventNexusReader() : 
-  m_presenter(NULL),
-  m_loadInMemory(false),
-  m_depth(1),
-  m_time(0)
-{
-  this->FileName = NULL;
-  this->SetNumberOfInputPorts(0);
-  this->SetNumberOfOutputPorts(1);
-
-}
-
-vtkEventNexusReader::~vtkEventNexusReader()
-{
-  delete m_presenter;
-  this->SetFileName(0);
-}
-
-void vtkEventNexusReader::SetDepth(int depth)
-{
-  size_t temp = depth;
-  if(m_depth != temp)
-  {
-   this->m_depth = temp;
-   this->Modified();
-  }
-}
-
-size_t vtkEventNexusReader::getRecursionDepth() const
-{
-  return this->m_depth;
-}
-
-bool vtkEventNexusReader::getLoadInMemory() const
-{
-  return m_loadInMemory;
-}
-
-double vtkEventNexusReader::getTime() const
-{
-  return m_time;
-}
-
-/**
-  Sets algorithm in-memory property. If this is changed, the file is reloaded.
-  @param inMemory : true if the entire file should be loaded into memory.
-*/
-void vtkEventNexusReader::SetInMemory(bool inMemory)
-{
-  if(m_loadInMemory != inMemory)
-  {
-    this->Modified(); 
-  }
-  m_loadInMemory = inMemory;
-}
-
-
-/**
-  Gets the geometry xml from the workspace. Allows object panels to configure themeselves.
-  @return geometry xml const * char reference.
-*/
-const char* vtkEventNexusReader::GetInputGeometryXML()
-{
-  if(m_presenter == NULL)
-  {
-    return "";
-  }
-  try
-  {
-    return m_presenter->getGeometryXML().c_str();
-  }
-  catch(std::runtime_error&)
-  {
-    return "";
-  }
-}
-
-int vtkEventNexusReader::RequestData(vtkInformation * vtkNotUsed(request), vtkInformationVector ** vtkNotUsed(inputVector), vtkInformationVector *outputVector)
-{
- 
-  using namespace Mantid::VATES;
-  //get the info objects
-  vtkInformation *outInfo = outputVector->GetInformationObject(0);
-
-  if (outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()))
-  {
-    // usually only one actual step requested
-    m_time =outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP());
-  }
-
-  FilterUpdateProgressAction<vtkEventNexusReader> loadingProgressUpdate(this, "Loading...");
-  FilterUpdateProgressAction<vtkEventNexusReader> drawingProgressUpdate(this, "Drawing...");
- 
-  ThresholdRange_scptr thresholdRange(new IgnoreZerosThresholdRange());
-  vtkMDHexFactory* hexahedronFactory = new vtkMDHexFactory(thresholdRange, "signal");
-  vtkMDQuadFactory* quadFactory = new vtkMDQuadFactory(thresholdRange, "signal");
-  vtkMDLineFactory* lineFactory = new vtkMDLineFactory(thresholdRange, "signal");
-
-  hexahedronFactory->SetSuccessor(quadFactory);
-  quadFactory->SetSuccessor(lineFactory);
-
-  hexahedronFactory->setTime(m_time);
-  vtkDataSet* product = m_presenter->execute(hexahedronFactory, loadingProgressUpdate, drawingProgressUpdate);
-  
-  //-------------------------------------------------------- Corrects problem whereby boundaries not set propertly in PV.
-  vtkBox* box = vtkBox::New();
-  box->SetBounds(product->GetBounds());
-  vtkPVClipDataSet* clipper = vtkPVClipDataSet::New();
-  clipper->SetInputData(product);
-  clipper->SetClipFunction(box);
-  clipper->SetInsideOut(true);
-  clipper->Update();
-  vtkDataSet* clipperOutput = clipper->GetOutput();
-   //--------------------------------------------------------
-
-  vtkUnstructuredGrid *output = vtkUnstructuredGrid::SafeDownCast(
-    outInfo->Get(vtkDataObject::DATA_OBJECT()));
-  output->ShallowCopy(clipperOutput);
-
-  clipper->Delete();
-  
-  return 1;
-}
-
-int vtkEventNexusReader::RequestInformation(
-  vtkInformation *vtkNotUsed(request),
-  vtkInformationVector **vtkNotUsed(inputVector),
-  vtkInformationVector *outputVector)
-{
-  if(m_presenter == NULL)
-  {
-    m_presenter = new EventNexusLoadingPresenter(new MDLoadingViewAdapter<vtkEventNexusReader>(this), FileName);
-    m_presenter->executeLoadMetadata();
-    setTimeRange(outputVector);
-  }
-  return 1;
-}
-
-void vtkEventNexusReader::PrintSelf(ostream& os, vtkIndent indent)
-{
-  this->Superclass::PrintSelf(os,indent);
-}
-
-int vtkEventNexusReader::CanReadFile(const char* fname)
-{
-  EventNexusLoadingPresenter temp(new MDLoadingViewAdapter<vtkEventNexusReader>(this), fname);
-  return temp.canReadFile();
-}
-
-unsigned long vtkEventNexusReader::GetMTime()
-{
-  return Superclass::GetMTime();
-}
-
-/**
-  Update/Set the progress.
-  @param progress : progress increment.
-*/
-void vtkEventNexusReader::updateAlgorithmProgress(double progress, const std::string& message)
-{
-  progressMutex.lock();
-  this->SetProgressText(message.c_str());
-  this->UpdateProgress(progress);
-  progressMutex.unlock();
-}
-
-/** Helper function to setup the time range.
-@param outputVector : vector onto which the time range will be set.
-*/
-void vtkEventNexusReader::setTimeRange(vtkInformationVector* outputVector)
-{
-  if(m_presenter->hasTDimensionAvailable())
-  {
-    vtkInformation *outInfo = outputVector->GetInformationObject(0);
-    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],
-      static_cast<int> (timeStepValues.size()));
-    double timeRange[2];
-    timeRange[0] = timeStepValues.front();
-    timeRange[1] = timeStepValues.back();
-
-    outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(), timeRange, 2);
-  }
-}
-
-/*
-Getter for the workspace type name.
-*/
-char* vtkEventNexusReader::GetWorkspaceTypeName()
-{
-  //Forward request on to MVP presenter
-  typeName = m_presenter->getWorkspaceTypeName();
-  return const_cast<char*>(typeName.c_str());
-}
-
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/vtkEventNexusReader.h b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/vtkEventNexusReader.h
deleted file mode 100644
index a2dfe17e027145ca5f5ec27a91bc1d143e355d1a..0000000000000000000000000000000000000000
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/EventNexusReader/vtkEventNexusReader.h
+++ /dev/null
@@ -1,72 +0,0 @@
-#ifndef _vtkEventNexusReader_h 
-#define _vtkEventNexusReader_h
-#include "vtkUnstructuredGridAlgorithm.h"
-#include "MantidVatesAPI/EventNexusLoadingPresenter.h"
-#include "MantidKernel/MultiThreaded.h"
-
-class vtkImplicitFunction;
-// cppcheck-suppress class_X_Y
-class VTK_EXPORT vtkEventNexusReader : public vtkUnstructuredGridAlgorithm
-{
-public:
-
-  //------- MDLoadingView methods ----------------
-  virtual double getTime() const;
-  virtual size_t getRecursionDepth() const;
-  virtual bool getLoadInMemory() const;
-  //----------------------------------------------
-
-  static vtkEventNexusReader *New();
-  vtkTypeMacro(vtkEventNexusReader, vtkUnstructuredGridAlgorithm)
-  void PrintSelf(ostream& os, vtkIndent indent);
-  vtkSetStringMacro(FileName);
-  vtkGetStringMacro(FileName);
-  int CanReadFile(const char* fname);
-  void SetInMemory(bool inMemory);
-  void SetDepth(int depth);
-  /// Called by presenter to force progress information updating.
-  void updateAlgorithmProgress(double progress, const std::string& message);
-  /// Getter for the workspace type
-  char* GetWorkspaceTypeName();
-  /// Getter for the input geometry
-  const char* GetInputGeometryXML();
-
-protected:
-  vtkEventNexusReader();
-  ~vtkEventNexusReader();
-  int RequestInformation(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
-  int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
-  int Canreadfile(const char *fname);
-  ///Handle time variation.
-  unsigned long GetMTime();
-  
-private:
-
-  void setTimeRange(vtkInformationVector* outputVector);
-
-  vtkEventNexusReader(const vtkEventNexusReader&);
-  
-  void operator = (const vtkEventNexusReader&);
-
-  /// File name from which to read.
-  char *FileName;
-
-  /// Controller/Presenter.
-  Mantid::VATES::EventNexusLoadingPresenter* m_presenter;
-
-  /// Flag indicating that file loading algorithm should attempt to fully load the file into memory.
-  bool m_loadInMemory;
-
-  /// Mutex for thread-safe progress reporting.
-  Mantid::Kernel::Mutex progressMutex;
-
-  /// Recursion depth.
-  size_t m_depth;
-
-  //Time
-  double m_time;
-
-  //Cached workspace type name.
-  std::string typeName;
-};
-#endif
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/MDEWNexusReader.xml b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/MDEWNexusReader.xml
index 13657926b55e551b8e790dcd2311eb27b5936381..fad6cdc4c0ccf9be6aaf68dfdb6d0fcace4bf0b1 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/MDEWNexusReader.xml
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/MDEWNexusReader.xml
@@ -2,6 +2,15 @@
   <!-- Begin MDEWNexusReader -->
   <ProxyGroup name="sources">
     <SourceProxy name="MDEWNexusReader" class="vtkMDEWNexusReader">
+        <IntVectorProperty name="Normalization" number_of_elements="1" command="SetNormalization" default_values="3">
+            <EnumerationDomain name="enum"> 
+                <Entry text="None" value="0"/> 
+                <Entry text="Volume" value="1"/> 
+                <Entry text="Number of Events" value="2"/> 
+                <Entry text="Auto Select" value="3"/> 
+            </EnumerationDomain> 
+        <Documentation>Set the normalization type</Documentation> 
+        </IntVectorProperty>
 	    <StringVectorProperty
          name="WorkspaceTypeName"
          command="GetWorkspaceTypeName"
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.cxx b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.cxx
index 4eeb30cca8c852f57cab81afd317b0897077ae09..d65bd7540b146e133450c7999599182ea9c8cb51 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.cxx
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.cxx
@@ -106,6 +106,15 @@ const char* vtkMDEWNexusReader::GetInputGeometryXML()
   }
 }
 
+/**
+@param option : Normalization option chosen by index.
+*/
+void vtkMDEWNexusReader::SetNormalization(int option)
+{
+  m_normalization = static_cast<Mantid::VATES::VisualNormalization>(option);
+  this->Modified();
+}
+
 int vtkMDEWNexusReader::RequestData(vtkInformation * vtkNotUsed(request), vtkInformationVector ** vtkNotUsed(inputVector), vtkInformationVector *outputVector)
 {
 
@@ -124,9 +133,9 @@ int vtkMDEWNexusReader::RequestData(vtkInformation * vtkNotUsed(request), vtkInf
   FilterUpdateProgressAction<vtkMDEWNexusReader> drawingProgressAction(this, "Drawing...");
 
   ThresholdRange_scptr thresholdRange(new IgnoreZerosThresholdRange());
-  vtkMDHexFactory* hexahedronFactory = new vtkMDHexFactory(thresholdRange, "signal");
-  vtkMDQuadFactory* quadFactory = new vtkMDQuadFactory(thresholdRange, "signal");
-  vtkMDLineFactory* lineFactory = new vtkMDLineFactory(thresholdRange, "signal");
+  vtkMDHexFactory* hexahedronFactory = new vtkMDHexFactory(thresholdRange, m_normalization);
+  vtkMDQuadFactory* quadFactory = new vtkMDQuadFactory(thresholdRange, m_normalization);
+  vtkMDLineFactory* lineFactory = new vtkMDLineFactory(thresholdRange, m_normalization);
 
   hexahedronFactory->SetSuccessor(quadFactory);
   quadFactory->SetSuccessor(lineFactory);
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.h b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.h
index 1b1431072eae37834bcfc75abf55de3c750975f6..2bb5d1ff675091d08a4a008012daddb9c4f29261 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.h
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.h
@@ -1,6 +1,7 @@
 #ifndef _vtkMDEWNexusReader_h
 #define _vtkMDEWNexusReader_h
 #include "vtkUnstructuredGridAlgorithm.h"
+#include "MantidVatesAPI/Normalization.h"
 #include "MantidVatesAPI/MDEWEventNexusLoadingPresenter.h"
 #include "MantidKernel/MultiThreaded.h"
 
@@ -33,6 +34,8 @@ public:
   /// Getter for the input geometry
   const char* GetInputGeometryXML();
 
+  void SetNormalization(int option);
+
 protected:
   vtkMDEWNexusReader();
   ~vtkMDEWNexusReader();
@@ -70,5 +73,7 @@ private:
 
   //Cached workspace type name.
   std::string typeName;
+
+  Mantid::VATES::VisualNormalization m_normalization;
 };
 #endif
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/MDHWNexusReader.xml b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/MDHWNexusReader.xml
index 48fe5946222adfe365cbf0d224caa492f34dace5..2b8d677a94196ab2902e63de5016e4b4d3572bd7 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/MDHWNexusReader.xml
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/MDHWNexusReader.xml
@@ -2,6 +2,15 @@
   <!-- Begin MDHWNexusReader -->
   <ProxyGroup name="sources">
     <SourceProxy name="MDHWNexusReader" class="vtkMDHWNexusReader">
+        <IntVectorProperty name="Normalization" number_of_elements="1" command="SetNormalization" default_values="3">
+            <EnumerationDomain name="enum"> 
+                <Entry text="None" value="0"/> 
+                <Entry text="Volume" value="1"/> 
+                <Entry text="Number of Events" value="2"/> 
+                <Entry text="Auto Select" value="3"/> 
+            </EnumerationDomain> 
+        <Documentation>Set the normalization type</Documentation> 
+        </IntVectorProperty>
 	    <StringVectorProperty
          name="WorkspaceTypeName"
          command="GetWorkspaceTypeName"
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/vtkMDHWNexusReader.cxx b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/vtkMDHWNexusReader.cxx
index d97840f52aa3f225e87bafc6c7956a308436a35d..6d60ff6f6ddc2665174da01c2115992ebb75c8c2 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/vtkMDHWNexusReader.cxx
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/vtkMDHWNexusReader.cxx
@@ -29,7 +29,8 @@ vtkMDHWNexusReader::vtkMDHWNexusReader() :
   m_presenter(NULL),
   m_loadInMemory(false),
   m_depth(1),
-  m_time(0)
+  m_time(0),
+  m_normalizationOption(AutoSelect)
 {
   this->FileName = NULL;
   this->SetNumberOfInputPorts(0);
@@ -100,6 +101,16 @@ const char* vtkMDHWNexusReader::GetInputGeometryXML()
   }
 }
 
+/**
+Set the normalization option. This is how the signal data will be normalized before viewing.
+@param option : Normalization option
+*/
+void vtkMDHWNexusReader::SetNormalization(int option)
+{
+  m_normalizationOption = static_cast<Mantid::VATES::VisualNormalization>(option);
+  this->Modified();
+}
+
 int vtkMDHWNexusReader::RequestData(vtkInformation * vtkNotUsed(request), vtkInformationVector ** vtkNotUsed(inputVector), vtkInformationVector *outputVector)
 {
 
@@ -121,8 +132,8 @@ int vtkMDHWNexusReader::RequestData(vtkInformation * vtkNotUsed(request), vtkInf
 
   // Will attempt to handle drawing in 4D case and then in 3D case
   // if that fails.
-  vtkMDHistoHexFactory* successor = new vtkMDHistoHexFactory(thresholdRange, "signal");
-  vtkMDHistoHex4DFactory<TimeToTimeStep> *factory = new vtkMDHistoHex4DFactory<TimeToTimeStep>(thresholdRange, "signal", m_time);
+  vtkMDHistoHexFactory* successor = new vtkMDHistoHexFactory(thresholdRange, m_normalizationOption);
+  vtkMDHistoHex4DFactory<TimeToTimeStep> *factory = new vtkMDHistoHex4DFactory<TimeToTimeStep>(thresholdRange, m_normalizationOption, m_time);
   factory->SetSuccessor(successor);
 
   vtkDataSet* product = m_presenter->execute(factory, loadingProgressAction, drawingProgressAction);
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/vtkMDHWNexusReader.h b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/vtkMDHWNexusReader.h
index 986c9d3bc0d7e4d0ca71c62c9e64afdac3d73b9d..6c6508949d83bcd81136dcc6783b2ccb3939e822 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/vtkMDHWNexusReader.h
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/vtkMDHWNexusReader.h
@@ -1,7 +1,10 @@
 #ifndef _vtkMDHWNexusReader_h
 #define _vtkMDHWNexusReader_h
+
+
 #include "vtkUnstructuredGridAlgorithm.h"
 #include "MantidVatesAPI/MDHWNexusLoadingPresenter.h"
+#include "MantidVatesAPI/Normalization.h"
 #include "MantidKernel/MultiThreaded.h"
 
 class vtkImplicitFunction;
@@ -32,6 +35,8 @@ public:
   char* GetWorkspaceTypeName();
   /// Getter for the input geometry
   const char* GetInputGeometryXML();
+  /// Setter for the normalization
+  void SetNormalization(int option);
 
 protected:
   vtkMDHWNexusReader();
@@ -70,5 +75,8 @@ private:
 
   //Cached workspace type name.
   std::string typeName;
+
+  /// Normalization Option
+  Mantid::VATES::VisualNormalization m_normalizationOption;
 };
 #endif
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/SQWEventReader.xml b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/SQWEventReader.xml
deleted file mode 100644
index e22d5ca7d0322da05285ef678a23b665da45e54d..0000000000000000000000000000000000000000
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/SQWEventReader.xml
+++ /dev/null
@@ -1,59 +0,0 @@
-<ServerManagerConfiguration>
-  <!-- Begin SQWEventReader -->
-  <ProxyGroup name="sources">
-    <SourceProxy name="SQWEventReader" class="vtkSQWEventReader">
-	    <StringVectorProperty
-         name="WorkspaceTypeName"
-         command="GetWorkspaceTypeName"
-         number_of_elements="1"
-         information_only="1">
-        <SimpleStringInformationHelper /> 
-       </StringVectorProperty>
-	    <IntVectorProperty
-         name="Load All Into Memory"
-         command="SetInMemory"
-         number_of_elements="1"
-         default_values="0">
-         <BooleanDomain name="bool"/>
-        </IntVectorProperty>
-		<IntVectorProperty
-         name="Recursion Depth"
-         command="SetDepth"
-         number_of_elements="1"
-         default_values="5">
-       </IntVectorProperty>
-	   <StringVectorProperty
-         name="InputGeometryXML"
-         command="GetInputGeometryXML"
-         number_of_elements="1"
-         information_only="1">
-        <SimpleStringInformationHelper /> 
-       </StringVectorProperty>
-       <StringVectorProperty
-        name="FileName"
-        command="SetFileName"
-        number_of_elements="1">
-        <FileListDomain name="files"/>
-      </StringVectorProperty>
-	  <DoubleVectorProperty 
-        name="TimestepValues"
-        information_only="1">
-        <TimeStepsInformationHelper/>
-        <Documentation>
-          Available timestep values.
-        </Documentation>
-      </DoubleVectorProperty>
-      <StringVectorProperty
-        name="TimeLabelAnnotation"
-        information_only="1"
-        si_class="vtkSITimeLabelProperty">
-      </StringVectorProperty>
-      <Hints>
-        <ReaderFactory
-          extensions="sqw"
-          file_description="MD *.sqw format" />
-      </Hints>
-    </SourceProxy>
-  </ProxyGroup>
-  <!-- End SQWEventReader -->
-</ServerManagerConfiguration>
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/SQWEventReaderGUI.xml b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/SQWEventReaderGUI.xml
deleted file mode 100644
index b3a72733227b22dbc8e1ef363d31aac44f2c928f..0000000000000000000000000000000000000000
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/SQWEventReaderGUI.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<ParaViewReaders>
-  <Reader name="SQWEventReader"
-    extensions="sqw"
-    file_description="MD *.sqw format">
-  </Reader>
-</ParaViewReaders>
\ No newline at end of file
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/vtkSQWEventReader.cxx b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/vtkSQWEventReader.cxx
deleted file mode 100644
index a009a7a71cfc2c519815aac3e19fdd0966a9b387..0000000000000000000000000000000000000000
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/vtkSQWEventReader.cxx
+++ /dev/null
@@ -1,229 +0,0 @@
-#include "vtkSQWEventReader.h"
-#include "vtkInformation.h"
-#include "vtkInformationVector.h"
-#include "vtkObjectFactory.h"
-#include "vtkCellArray.h"
-#include "vtkCellData.h"
-#include "vtkPointData.h"
-#include "vtkTransform.h"
-#include "vtkFloatArray.h"
-#include "vtkUnstructuredGrid.h"
-#include "vtkStreamingDemandDrivenPipeline.h"
-#include "vtkPVClipDataSet.h"
-#include "vtkPVInformationKeys.h"
-#include "vtkBox.h"
-
-#include "MantidVatesAPI/vtkMDHexFactory.h"
-#include "MantidVatesAPI/vtkMDQuadFactory.h"
-#include "MantidVatesAPI/vtkMDLineFactory.h"
-#include "MantidVatesAPI/IgnoreZerosThresholdRange.h"
-#include "MantidVatesAPI/FilteringUpdateProgressAction.h"
-#include "MantidVatesAPI/MDLoadingViewAdapter.h"
-
-vtkStandardNewMacro(vtkSQWEventReader)
-
-using namespace Mantid::VATES;
-using Mantid::Geometry::IMDDimension_sptr;
-using Mantid::Geometry::IMDDimension_sptr;
-
-
-vtkSQWEventReader::vtkSQWEventReader() : 
-  m_presenter(NULL),
-  m_loadInMemory(false),
-  m_depth(1),
-  m_time(0)
-{
-  this->FileName = NULL;
-  this->SetNumberOfInputPorts(0);
-  this->SetNumberOfOutputPorts(1);
-
-}
-
-vtkSQWEventReader::~vtkSQWEventReader()
-{
-  delete m_presenter;
-  this->SetFileName(0);
-}
-
-void vtkSQWEventReader::SetDepth(int depth)
-{
-  size_t temp = depth;
-  if(m_depth != temp)
-  {
-   this->m_depth = temp;
-   this->Modified();
-  }
-}
-
-size_t vtkSQWEventReader::getRecursionDepth() const
-{
-  return this->m_depth;
-}
-
-bool vtkSQWEventReader::getLoadInMemory() const
-{
-  return m_loadInMemory;
-}
-
-double vtkSQWEventReader::getTime() const
-{
-  return m_time;
-}
-
-/**
-  Sets algorithm in-memory property. If this is changed, the file is reloaded.
-  @param inMemory : true if the entire file should be loaded into memory.
-*/
-void vtkSQWEventReader::SetInMemory(bool inMemory)
-{
-  if(m_loadInMemory != inMemory)
-  {
-    this->Modified(); 
-  }
-  m_loadInMemory = inMemory;
-}
-
-
-/**
-  Gets the geometry xml from the workspace. Allows object panels to configure themeselves.
-  @return geometry xml const * char reference.
-*/
-const char* vtkSQWEventReader::GetInputGeometryXML()
-{
-  if(m_presenter == NULL)
-  {
-    return "";
-  }
-  try
-  {
-    return m_presenter->getGeometryXML().c_str();
-  }
-  catch(std::runtime_error&)
-  {
-    return "";
-  }
-}
-
-int vtkSQWEventReader::RequestData(vtkInformation * vtkNotUsed(request), vtkInformationVector ** vtkNotUsed(inputVector), vtkInformationVector *outputVector)
-{
-  using namespace Mantid::VATES;
-  //get the info objects
-  vtkInformation *outInfo = outputVector->GetInformationObject(0);
-
-  FilterUpdateProgressAction<vtkSQWEventReader> loadingProgressUpdate(this, "Loading...");
-  FilterUpdateProgressAction<vtkSQWEventReader> drawingProgressUpdate(this, "Drawing...");
-
-  if (outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()))
-  {
-    // usually only one actual step requested
-    m_time =outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP());
-  }
-
-  ThresholdRange_scptr thresholdRange(new IgnoreZerosThresholdRange());
-  vtkMDHexFactory* hexahedronFactory = new vtkMDHexFactory(thresholdRange, "signal");
-  vtkMDQuadFactory* quadFactory = new vtkMDQuadFactory(thresholdRange, "signal");
-  vtkMDLineFactory* lineFactory = new vtkMDLineFactory(thresholdRange, "signal");
-
-  hexahedronFactory->SetSuccessor(quadFactory);
-  quadFactory->SetSuccessor(lineFactory);
-
-  hexahedronFactory->setTime(m_time);
-  vtkDataSet* product = m_presenter->execute(hexahedronFactory, loadingProgressUpdate, drawingProgressUpdate);
-
-  //-------------------------------------------------------- Corrects problem whereby boundaries not set propertly in PV.
-  vtkBox* box = vtkBox::New();
-  box->SetBounds(product->GetBounds());
-  vtkPVClipDataSet* clipper = vtkPVClipDataSet::New();
-  clipper->SetInputData(product);
-  clipper->SetClipFunction(box);
-  clipper->SetInsideOut(true);
-  clipper->Update();
-  vtkDataSet* clipperOutput = clipper->GetOutput();
-   //--------------------------------------------------------
-
-  vtkUnstructuredGrid *output = vtkUnstructuredGrid::SafeDownCast(
-    outInfo->Get(vtkDataObject::DATA_OBJECT()));
-  output->ShallowCopy(clipperOutput);
-
-  m_presenter->setAxisLabels(output);
-
-  clipper->Delete();
-  
-  return 1;
-}
-
-int vtkSQWEventReader::RequestInformation(
-  vtkInformation *vtkNotUsed(request),
-  vtkInformationVector **vtkNotUsed(inputVector),
-  vtkInformationVector *outputVector)
-{
-  if(m_presenter == NULL)
-  {
-    m_presenter = new SQWLoadingPresenter(new MDLoadingViewAdapter<vtkSQWEventReader>(this), FileName);
-    m_presenter->executeLoadMetadata();
-    setTimeRange(outputVector);
-  }
-  return 1;
-}
-
-void vtkSQWEventReader::PrintSelf(ostream& os, vtkIndent indent)
-{
-  this->Superclass::PrintSelf(os,indent);
-}
-
-int vtkSQWEventReader::CanReadFile(const char* fname)
-{
-  SQWLoadingPresenter temp(new MDLoadingViewAdapter<vtkSQWEventReader>(this), fname);
-  return temp.canReadFile();
-}
-
-unsigned long vtkSQWEventReader::GetMTime()
-{
-  return Superclass::GetMTime();
-}
-
-/**
-  Update/Set the progress.
-  @param progress : progress increment.
-  @param message : progress message
-*/
-void vtkSQWEventReader::updateAlgorithmProgress(double progress, const std::string& message)
-{
-  progressMutex.lock();
-  this->SetProgressText(message.c_str());
-  this->UpdateProgress(progress);
-  progressMutex.unlock();
-}
-
-/** Helper function to setup the time range.
-@param outputVector : vector onto which the time range will be set.
-*/
-void vtkSQWEventReader::setTimeRange(vtkInformationVector* outputVector)
-{
-  if(m_presenter->hasTDimensionAvailable())
-  {
-    vtkInformation *outInfo = outputVector->GetInformationObject(0);
-    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],
-      static_cast<int> (timeStepValues.size()));
-    double timeRange[2];
-    timeRange[0] = timeStepValues.front();
-    timeRange[1] = timeStepValues.back();
-
-    outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(), timeRange, 2);
-  }
-}
-
-/*
-Getter for the workspace type name.
-*/
-char* vtkSQWEventReader::GetWorkspaceTypeName()
-{
-  //Forward request on to MVP presenter
-  typeName = m_presenter->getWorkspaceTypeName();
-  return const_cast<char*>(typeName.c_str());
-
-}
-
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/vtkSQWEventReader.h b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/vtkSQWEventReader.h
deleted file mode 100644
index 89e67fc083db881e800621ff9b1950bff030a631..0000000000000000000000000000000000000000
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWEventReader/vtkSQWEventReader.h
+++ /dev/null
@@ -1,72 +0,0 @@
-#ifndef _vtkSQWEventReader_h
-#define _vtkSQWEventReader_h
-#include "vtkUnstructuredGridAlgorithm.h"
-#include "MantidVatesAPI/SQWLoadingPresenter.h"
-#include "MantidKernel/MultiThreaded.h"
-
-class vtkImplicitFunction;
-// cppcheck-suppress class_X_Y
-class VTK_EXPORT vtkSQWEventReader : public vtkUnstructuredGridAlgorithm
-{
-public:
-
-   //------- MDLoadingView methods ----------------
-  virtual double getTime() const;
-  virtual size_t getRecursionDepth() const;
-  virtual bool getLoadInMemory() const;
-  //----------------------------------------------
-
-  static vtkSQWEventReader *New();
-  vtkTypeMacro(vtkSQWEventReader, vtkUnstructuredGridAlgorithm)
-  void PrintSelf(ostream& os, vtkIndent indent);
-  vtkSetStringMacro(FileName);
-  vtkGetStringMacro(FileName);
-  int CanReadFile(const char* fname);
-  void SetInMemory(bool inMemory);
-  void SetDepth(int depth);
-  /// Called by presenter to force progress information updating.
-  void updateAlgorithmProgress(double progress, const std::string& message);
-  /// Getter for the workspace type
-  char* GetWorkspaceTypeName();
-  /// Getter for the input geometry
-  const char* GetInputGeometryXML();
-
-protected:
-  vtkSQWEventReader();
-  ~vtkSQWEventReader();
-  int RequestInformation(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
-  int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
-  int Canreadfile(const char *fname);
-  ///Handle time variation.
-  unsigned long GetMTime();
-  
-private:
-
-  vtkSQWEventReader(const vtkSQWEventReader&);
-  
-  void operator = (const vtkSQWEventReader&);
-
-  void setTimeRange(vtkInformationVector* outputVector);
-
-  /// File name from which to read.
-  char *FileName;
-
-  /// Controller/Presenter.
-  Mantid::VATES::SQWLoadingPresenter* m_presenter;
-
-  /// Flag indicating that file loading algorithm should attempt to fully load the file into memory.
-  bool m_loadInMemory;
-
-  /// Mutex for thread-safe progress reporting.
-  Mantid::Kernel::Mutex progressMutex;
-
-  /// Recursion depth.
-  size_t m_depth;
-
-  //Time
-  double m_time;
-
-  //Cached workspace type name.
-  std::string typeName;
-};
-#endif
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWReader/CMakeLists.txt b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWReader/CMakeLists.txt
deleted file mode 100644
index 689f53b054120133a355490a1406db72b39f80f5..0000000000000000000000000000000000000000
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWReader/CMakeLists.txt
+++ /dev/null
@@ -1,25 +0,0 @@
-project( MantidParaViewSQWReader )
-include_directories( SYSTEM ${PARAVIEW_INCLUDE_DIRS} )
-add_paraview_plugin( MantidParaViewSQWReaderSMPlugin "1.0"
-	SERVER_MANAGER_XML SQWReader.xml
-	SERVER_MANAGER_SOURCES vtkSQWReader.cxx
-    GUI_RESOURCE_FILES SQWReaderGUI.xml
-)
-
-# Add to the 'VatesParaViewPlugins' group in VS
-set_property( TARGET MantidParaViewSQWReaderSMPlugin PROPERTY FOLDER "MantidVatesParaViewPlugins" )
-
-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})
-
-install( TARGETS MantidParaViewSQWReaderSMPlugin ${SYSTEM_PACKAGE_TARGET} DESTINATION ${PVPLUGINS_DIR}/${PVPLUGINS_SUBDIR} )
-
-
-
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWReader/SQWReader.xml b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWReader/SQWReader.xml
deleted file mode 100755
index fa25e8e140392a52da309d7299d7ec4c0b352fd2..0000000000000000000000000000000000000000
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWReader/SQWReader.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<ServerManagerConfiguration>
-  <!-- Begin SQWReader -->
-  <ProxyGroup name="sources">
-    <SourceProxy name="SQWReader" class="vtkSQWReader" label="Old SQW Reader">
-	<Documentation
-       short_help="Read a Multidimensional SQW file, treat as old MDWorkspace."
-       long_help="Read a Multidimensional SQW file, treat as old MDWorkspace.">
-       Read a Multidimensional SQW file, treat as old MDWorkspace
-     </Documentation>
-      <StringVectorProperty
-        name="FileName"
-		animateable="0"
-        command="SetFileName"
-        number_of_elements="1">
-        <FileListDomain name="files"/>
-      </StringVectorProperty>
-      	<DoubleVectorProperty 
-        name="TimestepValues"
-        information_only="1">
-        <TimeStepsInformationHelper/>
-        <Documentation>
-          Available timestep values.
-        </Documentation>
-       </DoubleVectorProperty>
-    </SourceProxy>
-  </ProxyGroup>
-  <!-- End SQWReader -->
-</ServerManagerConfiguration>
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWReader/SQWReaderGUI.xml b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWReader/SQWReaderGUI.xml
deleted file mode 100755
index 08525bdcaedca5e0570022dbf0af0b751ba2e743..0000000000000000000000000000000000000000
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWReader/SQWReaderGUI.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<ParaViewReaders>
-  <Reader name="SQWReader"
-    extensions="sqw_old"
-    file_description="MD *.sqw files. Identified as old So that default loading route for .sqw files is as MDEWs.">
-  </Reader>
-</ParaViewReaders>
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWReader/vtkSQWReader.cxx b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWReader/vtkSQWReader.cxx
deleted file mode 100755
index a61f30ef2fefd790638fc2d60a3d601854562654..0000000000000000000000000000000000000000
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWReader/vtkSQWReader.cxx
+++ /dev/null
@@ -1,109 +0,0 @@
-#include "vtkSQWReader.h"
-#include "vtkInformation.h"
-#include "vtkInformationVector.h"
-#include "vtkObjectFactory.h"
-#include "vtkMath.h"
-#include "vtkCellArray.h"
-#include "vtkCellData.h"
-#include "vtkPointData.h"
-#include "vtkTransform.h"
-#include "vtkFloatArray.h"
-#include "vtkStreamingDemandDrivenPipeline.h"
-#include "MantidMDAlgorithms/PlaneImplicitFunction.h"
-#include "MantidVatesAPI/MultiDimensionalDbPresenter.h"
-#include "MantidVatesAPI/vtkStructuredGridFactory.h"
-#include "MantidVatesAPI/TimeToTimeStep.h"
-#include "MantidMDAlgorithms/Load_MDWorkspace.h"
-
-vtkStandardNewMacro(vtkSQWReader);
-
-vtkSQWReader::vtkSQWReader() : m_presenter()
-{
-  this->FileName = NULL;
-  this->SetNumberOfInputPorts(0);
-  this->SetNumberOfOutputPorts(1);
-}
-
-vtkSQWReader::~vtkSQWReader()
-{
-  this->SetFileName(0);
-}
-
-
-int vtkSQWReader::RequestData(vtkInformation* vtkNotUsed(request), vtkInformationVector ** vtkNotUsed(inputVector), vtkInformationVector *outputVector)
-{
-  using namespace Mantid::VATES;
-  //get the info objects
-  vtkInformation *outInfo = outputVector->GetInformationObject(0);
-
-  vtkStructuredGrid *output = vtkStructuredGrid::SafeDownCast(
-    outInfo->Get(vtkDataObject::DATA_OBJECT()));
-
-  int time = 0;
-  if (outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEPS()))
-  {
-     // usually only one actual step requested
-     time = static_cast<int>(outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEPS())[0]);
-  }
-
-  RebinningKnowledgeSerializer serializer;
-  vtkStructuredGridFactory<TimeToTimeStep> factory("signal", time);
-  vtkStructuredGrid* structuredMesh = vtkStructuredGrid::SafeDownCast(m_presenter.getMesh(serializer, factory));
-  structuredMesh->GetCellData()->AddArray(m_presenter.getScalarDataFromTime(factory));
-
-  int subext[6];
-  outInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), subext);
-
-  output->SetExtent(subext);
-  output->ShallowCopy(structuredMesh);
-
-  return 1;
-}
-
-int vtkSQWReader::RequestInformation(
-  vtkInformation *vtkNotUsed(request),
-  vtkInformationVector **vtkNotUsed(inputVector),
-  vtkInformationVector *outputVector)
-{
-  vtkInformation *outInfo = outputVector->GetInformationObject(0);
-
-
-  Mantid::MDAlgorithms::Load_MDWorkspace wsLoaderAlg;
-  wsLoaderAlg.initialize();
-  std::string wsId = "InputMDWs";
-  wsLoaderAlg.setPropertyValue("inFilename", FileName);
-  wsLoaderAlg.setPropertyValue("MDWorkspace",wsId);
-  m_presenter.execute(wsLoaderAlg, wsId);
-  int wholeExtent[6];
-
-  Mantid::VATES::VecExtents extents = m_presenter.getExtents();
-  wholeExtent[0] = extents[0];
-  wholeExtent[1] = extents[1];
-  wholeExtent[2] = extents[2];
-  wholeExtent[3] = extents[3];
-  wholeExtent[4] = extents[4];
-  wholeExtent[5] = extents[5];
-
-  outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(),
-               wholeExtent, 6);
-
-  std::vector<double> timeStepValues = m_presenter.getTimesteps();
-
-  outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(), &timeStepValues[0], static_cast<int>(timeStepValues.size()));
-  double timeRange[2];
-  timeRange[0] = timeStepValues.front();
-  timeRange[1] = timeStepValues.back();
-
-  outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(), timeRange, 2);
-  return 1;
-}
-
-void vtkSQWReader::PrintSelf(ostream& os, vtkIndent indent)
-{
-  this->Superclass::PrintSelf(os,indent);
-}
-
-int vtkSQWReader::CanReadFile(const char* vtkNotUsed(fname))
-{
-	return 1; //TODO: Apply checks here.
-}
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWReader/vtkSQWReader.h b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWReader/vtkSQWReader.h
deleted file mode 100755
index 9acb1ea4a56e260a75f5f5d6298f851ee5f142a1..0000000000000000000000000000000000000000
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWReader/vtkSQWReader.h
+++ /dev/null
@@ -1,29 +0,0 @@
-#ifndef _vtkSQWReader_h
-#define _vtkSQWReader_h
-
-#include "MantidVatesAPI/MultiDimensionalDbPresenter.h"
-#include "vtkStructuredGridAlgorithm.h"
-// cppcheck-suppress class_X_Y
-class VTK_EXPORT vtkSQWReader : public vtkStructuredGridAlgorithm
-{
-public:
-  static vtkSQWReader *New();
-  vtkTypeMacro(vtkSQWReader, vtkStructuredGridAlgorithm);
-  void PrintSelf(ostream& os, vtkIndent indent);
-  vtkSetStringMacro(FileName);
-  vtkGetStringMacro(FileName);
-  int CanReadFile(const char* fname);
-
-protected:
-  vtkSQWReader();
-  ~vtkSQWReader();
-  int RequestInformation(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
-  int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
-
-private:
-  vtkSQWReader(const vtkSQWReader&);
-  void operator = (const vtkSQWReader&);
-  Mantid::VATES::MultiDimensionalDbPresenter m_presenter;
-  char *FileName;
-};
-#endif
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/MDEWSource.xml b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/MDEWSource.xml
index 28fb60f14409eed211cdf53ffb24254eef8b0810..f7001706c000716cce9f324ce0c4ee4b90a21893 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/MDEWSource.xml
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/MDEWSource.xml
@@ -2,6 +2,18 @@
   <!-- Begin MDEWSource -->
   <ProxyGroup name="sources">
     <SourceProxy name="MDEW Source" class="vtkMDEWSource">
+    
+        <IntVectorProperty name="Normalization" number_of_elements="1" command="SetNormalization" default_values="3">
+            <EnumerationDomain name="enum"> 
+                <Entry text="None" value="0"/> 
+                <Entry text="Volume" value="1"/> 
+                <Entry text="Number of Events" value="2"/> 
+                <Entry text="Auto Select" value="3"/> 
+            </EnumerationDomain> 
+        <Documentation>Set the normalization type</Documentation> 
+        </IntVectorProperty>
+    
+    
 	    <StringVectorProperty
          name="WorkspaceTypeName"
          command="GetWorkspaceTypeName"
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.cxx b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.cxx
index 72b9d1da914e1ee426951e5b3ba7509d0770eed6..1bd478068b4fbd06e73f2a9e516db137078254ae 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.cxx
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.cxx
@@ -1,5 +1,6 @@
-#include "vtkBox.h"
 #include "vtkMDEWSource.h"
+
+#include "vtkBox.h"
 #include "vtkInformation.h"
 #include "vtkInformationVector.h"
 #include "vtkObjectFactory.h"
@@ -9,6 +10,7 @@
 #include "vtkUnstructuredGrid.h"
 #include "vtkStreamingDemandDrivenPipeline.h"
 
+#include "MantidAPI/IMDWorkspace.h"
 #include "MantidVatesAPI/MDEWInMemoryLoadingPresenter.h"
 #include "MantidVatesAPI/MDLoadingViewAdapter.h"
 #include "MantidVatesAPI/ADSWorkspaceProvider.h"
@@ -24,7 +26,7 @@ using namespace Mantid::VATES;
 vtkStandardNewMacro(vtkMDEWSource)
 
 /// Constructor
-vtkMDEWSource::vtkMDEWSource() :  m_wsName(""), m_depth(1000), m_time(0), m_presenter(NULL)
+vtkMDEWSource::vtkMDEWSource() :  m_wsName(""), m_depth(1000), m_time(0), m_presenter(NULL), m_normalization(AutoSelect)
 {
   this->SetNumberOfInputPorts(0);
   this->SetNumberOfOutputPorts(1);
@@ -166,6 +168,16 @@ const char* vtkMDEWSource::GetInstrument()
   }
 }
 
+/**
+Set the normalization option. This is how the signal data will be normalized before viewing.
+@param option : Normalization option
+*/
+void vtkMDEWSource::SetNormalization(int option)
+{
+  m_normalization = static_cast<Mantid::VATES::VisualNormalization>(option);
+  this->Modified();
+}
+
 
 int vtkMDEWSource::RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *outputVector)
 {
@@ -185,10 +197,10 @@ 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");
+    vtkMD0DFactory* zeroDFactory = new vtkMD0DFactory;
+    vtkMDHexFactory* hexahedronFactory = new vtkMDHexFactory(thresholdRange, m_normalization);
+    vtkMDQuadFactory* quadFactory = new vtkMDQuadFactory(thresholdRange, m_normalization);
+    vtkMDLineFactory* lineFactory = new vtkMDLineFactory(thresholdRange, m_normalization);
 
     hexahedronFactory->SetSuccessor(quadFactory);
     quadFactory->SetSuccessor(lineFactory);
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.h b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.h
index 7ad2525cf4cbe5878ed00c37ac366060eadbf7f5..fdde75d5a911e18b92425c24383a47b69f60c0cd 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.h
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.h
@@ -2,6 +2,8 @@
 #define _vtkMDEWSource_h
 
 #include "vtkUnstructuredGridAlgorithm.h"
+#include "MantidVatesAPI/Normalization.h"
+#include "MantidVatesAPI/vtkDataSetFactory.h"
 #include <string>
 
 namespace Mantid
@@ -50,6 +52,7 @@ public:
   
   void SetWsName(std::string wsName);
   void SetDepth(int depth);
+  void SetNormalization(int option);
 
   //------- MDLoadingView methods ----------------
   virtual double getTime() const;
@@ -97,6 +100,9 @@ private:
   /// Cached typename.
   std::string typeName;
 
+  /// Normalization option
+  Mantid::VATES::VisualNormalization m_normalization;
+
   vtkMDEWSource(const vtkMDEWSource&);
   void operator = (const vtkMDEWSource&);
   void setTimeRange(vtkInformationVector* outputVector);
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/MDHWSource.xml b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/MDHWSource.xml
index 14f349f1b1763f0cbf0a919f44a4e8914dd7af95..4f85039947dd3c776edf76fb3d7fe3a27830b6c5 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/MDHWSource.xml
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/MDHWSource.xml
@@ -2,6 +2,15 @@
   <!-- Begin MDEWSource -->
   <ProxyGroup name="sources">
     <SourceProxy name="MDHW Source" class="vtkMDHWSource">
+        <IntVectorProperty name="Normalization" number_of_elements="1" command="SetNormalization" default_values="3">
+            <EnumerationDomain name="enum"> 
+                <Entry text="None" value="0"/> 
+                <Entry text="Volume" value="1"/> 
+                <Entry text="Number of Events" value="2"/> 
+                <Entry text="Auto Select" value="3"/> 
+            </EnumerationDomain> 
+        <Documentation>Set the normalization type</Documentation> 
+        </IntVectorProperty>
 	    <StringVectorProperty
          name="WorkspaceTypeName"
          command="GetWorkspaceTypeName"
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.cxx b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.cxx
index 59539b18372925cb0cbdd08c02e27a2f8a251e8f..b2491e82070a7f1c1f666a0eee7dda3c7d156532 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.cxx
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.cxx
@@ -26,7 +26,7 @@ using namespace Mantid::VATES;
 vtkStandardNewMacro(vtkMDHWSource)
 
 /// Constructor
-vtkMDHWSource::vtkMDHWSource() :  m_wsName(""), m_time(0), m_presenter(NULL)
+vtkMDHWSource::vtkMDHWSource() :  m_wsName(""), m_time(0), m_presenter(NULL), m_normalizationOption(AutoSelect)
 {
   this->SetNumberOfInputPorts(0);
   this->SetNumberOfOutputPorts(1);
@@ -154,6 +154,17 @@ const char* vtkMDHWSource::GetInstrument()
   }
 }
 
+/**
+Set the normalization option. This is how the signal data will be normalized before viewing.
+@param option : Normalization option
+*/
+void vtkMDHWSource::SetNormalization(int option)
+{
+  m_normalizationOption = static_cast<Mantid::VATES::VisualNormalization>(option);
+  this->Modified();
+}
+
+
 int vtkMDHWSource::RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *outputVector)
 {
   if(m_presenter->canReadFile())
@@ -176,11 +187,11 @@ int vtkMDHWSource::RequestData(vtkInformation *, vtkInformationVector **, vtkInf
     /*
     Will attempt to handle drawing in 4D case and then in 3D case if that fails, and so on down to 1D
     */
-    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);
+    vtkMD0DFactory* zeroDFactory = new vtkMD0DFactory;
+    vtkMDHistoLineFactory* lineFactory = new vtkMDHistoLineFactory(thresholdRange, m_normalizationOption);
+    vtkMDHistoQuadFactory* quadFactory = new vtkMDHistoQuadFactory(thresholdRange, m_normalizationOption);
+    vtkMDHistoHexFactory* hexFactory = new vtkMDHistoHexFactory(thresholdRange, m_normalizationOption);
+    vtkMDHistoHex4DFactory<TimeToTimeStep> *factory = new vtkMDHistoHex4DFactory<TimeToTimeStep>(thresholdRange, m_normalizationOption, m_time);
 
     factory->SetSuccessor(hexFactory);
     hexFactory->SetSuccessor(quadFactory);
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.h b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.h
index 195fa4a0077d29cec11ed834fedbde069931cd91..5d0ab3ad6b90c9c04118de3b196e6fc2b66bef44 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.h
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.h
@@ -1,6 +1,7 @@
 #ifndef _vtkMDHWSource_h 
 #define _vtkMDHWSource_h
 
+#include "MantidVatesAPI/Normalization.h"
 #include "vtkUnstructuredGridAlgorithm.h"
 #include <string>
 
@@ -71,6 +72,8 @@ public:
   double GetMaxValue();
   /// Getter for the maximum value of the workspace data
   const char* GetInstrument();
+  /// Setter for the normalization
+  void SetNormalization(int option);
 
 protected:
   vtkMDHWSource();
@@ -92,6 +95,10 @@ private:
   /// Cached typename.
   std::string typeName;
 
+  /// Normalization Option
+  Mantid::VATES::VisualNormalization m_normalizationOption;
+
+
   vtkMDHWSource(const vtkMDHWSource&);
   void operator = (const vtkMDHWSource&);
   void setTimeRange(vtkInformationVector* outputVector);
diff --git a/Code/Mantid/Vates/VatesAPI/CMakeLists.txt b/Code/Mantid/Vates/VatesAPI/CMakeLists.txt
index ff049ce084bc66b6a831595aefc322915c08fd33..b957bf7aeb775c5499458db8e7e8903a0408c360 100644
--- a/Code/Mantid/Vates/VatesAPI/CMakeLists.txt
+++ b/Code/Mantid/Vates/VatesAPI/CMakeLists.txt
@@ -25,6 +25,7 @@ src/MetadataToFieldData.cpp
 src/MetadataToFieldData.cpp
 src/MetaDataExtractorUtils.cpp
 src/MetadataJsonManager.cpp
+src/Normalization.cpp
 src/NoThresholdRange.cpp
 src/ProgressAction.cpp
 src/SynchronisingGeometryPresenter.cpp
@@ -85,6 +86,7 @@ inc/MantidVatesAPI/MDLoadingViewAdapter.h
 inc/MantidVatesAPI/MedianAndBelowThresholdRange.h
 inc/MantidVatesAPI/MetaDataExtractorUtils.h
 inc/MantidVatesAPI/MetadataJsonManager.h
+inc/MantidVatesAPI/Normalization.h
 inc/MantidVatesAPI/IgnoreZerosThresholdRange.h
 inc/MantidVatesAPI/IMDDimensionComparitor.h
 inc/MantidVatesAPI/MetadataToFieldData.h
@@ -158,6 +160,7 @@ test/MDHWNexusLoadingPresenterTest.h
 test/MetaDataExtractorUtilsTest.h
 test/MetadataJsonManagerTest.h
 test/MetadataToFieldDataTest.h
+test/NormalizationTest.h
 test/SQWLoadingPresenterTest.h
 test/SynchronisingGeometryPresenterTest.h
 test/TimeStepToTimeStepTest.h
diff --git a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/Normalization.h b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/Normalization.h
new file mode 100644
index 0000000000000000000000000000000000000000..66fbc324874fe60cde2075ee7addbcad0a9a2cbe
--- /dev/null
+++ b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/Normalization.h
@@ -0,0 +1,55 @@
+#ifndef MANTID_VATES_NORMALIZATION_H_
+#define MANTID_VATES_NORMALIZATION_H_
+
+#include "MantidGeometry/MDGeometry/MDTypes.h"
+
+namespace Mantid {
+
+namespace API {
+// Forward declarations
+class IMDIterator;
+class IMDNode;
+class IMDWorkspace;
+class IMDEventWorkspace;
+}
+
+namespace VATES {
+
+/** Enum describing different ways to normalize the signal
+* in a MDWorkspace. We define the VisualNormalization separate from the MDNormalization because from the
+visual perspective we want an AutoSelect option, which is too high level for the API MDNormalization and will cause
+confusion as to it's meaning if left in the core core.
+Do not change the enum integers. Adding new options to the enum is ok.
+*/
+enum VisualNormalization {
+  /// Don't normalize = return raw counts
+  NoNormalization = 0,
+  /// Divide the signal by the volume of the box/bin
+  VolumeNormalization = 1,
+  /// Divide the signal by the number of events that contributed to it.
+  NumEventsNormalization = 2,
+  /// Auto select Normalization. We ask the IMDWorkspace to tell us it's preference
+  AutoSelect = 3
+};
+
+// Helper typedef
+typedef Mantid::signal_t (Mantid::API::IMDNode::*NormFuncIMDNodePtr)() const;
+
+/**
+Determine which normalization function will be called on an IMDNode
+*/
+NormFuncIMDNodePtr makeMDEventNormalizationFunction(
+    VisualNormalization normalizationOption,
+    Mantid::API::IMDEventWorkspace const *const ws);
+
+/**
+Determine which normalization function will be called on an IMDIterator of an IMDWorkspace
+*/
+Mantid::API::IMDIterator * createIteratorWithNormalization(
+    const VisualNormalization normalizationOption,
+    Mantid::API::IMDWorkspace const * const ws);
+
+}
+}
+
+#endif /*MANTID_VATES_NORMALIZATION_H_*/
\ No newline at end of file
diff --git a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetFactory.h b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetFactory.h
index e6350eb0b69d915f25acc53c9e5edd534fbd66cd..34209f572212545a7ebb37ba8340fef41ec572ba 100644
--- a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetFactory.h
+++ b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetFactory.h
@@ -3,19 +3,17 @@
 #ifndef MANTID_VATES_VTKDATASETFACTORY_H_
 #define MANTID_VATES_VTKDATASETFACTORY_H_
 
+#include "MantidAPI/IMDWorkspace.h"
 #include "MantidAPI/Workspace.h"
 #include "MantidKernel/System.h"
 #include "vtkDataSet.h"
 #include <boost/shared_ptr.hpp>
+#include <boost/tuple/tuple.hpp>
 #include <string>
 
 class vtkFloatArray;
 namespace Mantid
 {
-  namespace API
-  {
-    class IMDWorkspace;
-  }
 
 namespace VATES
 {
@@ -31,6 +29,8 @@ namespace VATES
     vtkIdType pointId;
   };
 
+
+
 /** Abstract type to generate a vtk dataset on demand from a MDWorkspace.
  Uses Chain Of Responsibility pattern to self-manage and ensure that the workspace rendering is delegated to another factory
  if the present concrete type can't handle it.
@@ -114,6 +114,8 @@ public:
   /// Dimensionalities of interest.
   enum Dimensionality{OneDimensional=1, TwoDimensional=2, ThreeDimensional=3, FourDimensional=4};
 
+  static const std::string ScalarName;
+
 protected:
   
   /**
@@ -227,6 +229,7 @@ private:
 
 typedef boost::shared_ptr<vtkDataSetFactory> vtkDataSetFactory_sptr;
 
+
 }
 }
 
diff --git a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMD0DFactory.h b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMD0DFactory.h
index 5469d9fae87453ef79e9682a04398e92f173df05..910fedff15bcb42d079c1dd6100e99027bdd4788 100644
--- a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMD0DFactory.h
+++ b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMD0DFactory.h
@@ -39,13 +39,7 @@ namespace Mantid
     public:
 
       /// Constructor
-      vtkMD0DFactory(ThresholdRange_scptr thresholdRange, const std::string& scalarName);
-
-      /// Assignment operator
-      vtkMD0DFactory& operator=(const vtkMD0DFactory& other);
-
-      /// Copy constructor.
-      vtkMD0DFactory(const vtkMD0DFactory& other);
+      vtkMD0DFactory();
 
       /// Destructor
       virtual ~vtkMD0DFactory();
@@ -63,9 +57,6 @@ namespace Mantid
     protected:
         virtual void validate() const;
 
-    private:
-      mutable ThresholdRange_scptr m_thresholdRange;
-      std::string m_scalarName;
     };
     
   }
diff --git a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHexFactory.h b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHexFactory.h
index fbd0925ad026c673c43c5999b488717980e6b5b4..432639357f7594016fd5a497b14844163d9dd34c 100644
--- a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHexFactory.h
+++ b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHexFactory.h
@@ -4,9 +4,12 @@
 #include "MantidAPI/IMDEventWorkspace.h"
 #include "MantidDataObjects/MDEventFactory.h"
 #include "MantidDataObjects/MDEventWorkspace.h"
+#include "MantidVatesAPI/Normalization.h"
 #include "MantidVatesAPI/ThresholdRange.h"
-#include "MantidVatesAPI/vtkDataSetFactory.h"
 #include "MantidVatesAPI/TimeToTimeStep.h"
+#include "MantidVatesAPI/vtkDataSetFactory.h"
+
+
 #include <boost/shared_ptr.hpp>
 
 using Mantid::DataObjects::MDEventWorkspace;
@@ -49,7 +52,7 @@ class DLLExport vtkMDHexFactory : public vtkDataSetFactory
 public:
 
   /// Constructor
-  vtkMDHexFactory(ThresholdRange_scptr thresholdRange, const std::string& scalarName, const size_t maxDepth = 1000);
+  vtkMDHexFactory(ThresholdRange_scptr thresholdRange, const VisualNormalization normalizationOption, const size_t maxDepth = 1000);
 
   /// Destructor
   virtual ~vtkMDHexFactory();
@@ -82,8 +85,8 @@ private:
   /// Threshold range strategy.
   ThresholdRange_scptr m_thresholdRange;
 
-  /// Scalar name to provide on dataset.
-  const std::string m_scalarName;
+  /// Normalization option and info.
+  const VisualNormalization m_normalizationOption;
 
   /// Member workspace to generate vtkdataset from.
   Mantid::API::Workspace_sptr m_workspace;
diff --git a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoHex4DFactory.h b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoHex4DFactory.h
index 56e6cdc84eb00c424e012086108d4c917de5e944..39e1506fd6dff46709c345f64f76185015cb0cf0 100644
--- a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoHex4DFactory.h
+++ b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoHex4DFactory.h
@@ -29,6 +29,7 @@
  */
 
 #include "MantidAPI/IMDWorkspace.h"
+#include "MantidVatesAPI/Normalization.h"
 #include "MantidVatesAPI/ThresholdRange.h"
 #include "MantidVatesAPI/vtkDataSetFactory.h"
 #include "MantidVatesAPI/vtkMDHistoHexFactory.h"
@@ -48,7 +49,7 @@ class DLLExport vtkMDHistoHex4DFactory: public vtkMDHistoHexFactory
 public:
 
   /// Constructor
-  vtkMDHistoHex4DFactory(ThresholdRange_scptr thresholdRange, const std::string& scalarname,
+  vtkMDHistoHex4DFactory(ThresholdRange_scptr thresholdRange, const VisualNormalization normalizationOption,
       const double timestep);
 
   /// Assignment operator
diff --git a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoHexFactory.h b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoHexFactory.h
index 584aad4d4afe351fd9baf8b772b03335bfb26a2a..3375718080ceb794002101ced00ad9bef2dbffe3 100644
--- a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoHexFactory.h
+++ b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoHexFactory.h
@@ -30,6 +30,7 @@
 
 #include "MantidVatesAPI/vtkDataSetFactory.h"
 #include "MantidAPI/IMDWorkspace.h"
+#include "MantidVatesAPI/Normalization.h"
 #include "MantidVatesAPI/ThresholdRange.h"
 #include <vtkUnstructuredGrid.h>
 #include <vtkFloatArray.h>
@@ -47,7 +48,7 @@ class DLLExport vtkMDHistoHexFactory: public vtkDataSetFactory
 public:
 
   /// Constructor
-  vtkMDHistoHexFactory(ThresholdRange_scptr thresholdRange, const std::string& scalarname);
+  vtkMDHistoHexFactory(ThresholdRange_scptr thresholdRange, const VisualNormalization normalizationOption);
 
   /// Assignment operator
   vtkMDHistoHexFactory& operator=(const vtkMDHistoHexFactory& other);
@@ -73,7 +74,7 @@ protected:
 
   virtual void validate() const;
 
-  vtkDataSet* create3Dor4D(size_t timestep, bool do4D, ProgressAction & update) const;
+  vtkDataSet* create3Dor4D(size_t timestep, ProgressAction & update) const;
 
   void validateWsNotNull() const;
 
@@ -82,8 +83,8 @@ protected:
   /// Image from which to draw.
   Mantid::DataObjects::MDHistoWorkspace_sptr m_workspace;
 
-  /// Name of the scalar to provide on mesh.
-  std::string m_scalarName;
+  /// Normalization option
+  VisualNormalization m_normalizationOption;
 
   /// Threshold range.
   mutable ThresholdRange_scptr m_thresholdRange;
diff --git a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoLineFactory.h b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoLineFactory.h
index 98b9eae6a3953499508a28bffdb2733bc9c3fe3f..2c9dfd9509f4cb738fac755a483ec7a062771a54 100644
--- a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoLineFactory.h
+++ b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoLineFactory.h
@@ -5,6 +5,7 @@
 #include "MantidVatesAPI/vtkDataSetFactory.h"
 #include "MantidAPI/IMDWorkspace.h"
 #include "vtkUnstructuredGrid.h"
+#include "MantidVatesAPI/Normalization.h"
 #include "MantidVatesAPI/ThresholdRange.h"
 #include "MantidDataObjects/MDHistoWorkspace.h"
 
@@ -43,7 +44,7 @@ namespace Mantid
     public:
 
       /// Constructor
-      vtkMDHistoLineFactory(ThresholdRange_scptr thresholdRange, const std::string& scalarName);
+      vtkMDHistoLineFactory(ThresholdRange_scptr thresholdRange, const VisualNormalization normalizationOption);
 
       /// Assignment operator
       vtkMDHistoLineFactory& operator=(const vtkMDHistoLineFactory& other);
@@ -74,7 +75,7 @@ namespace Mantid
 
       Mantid::DataObjects::MDHistoWorkspace_sptr m_workspace;
 
-      std::string m_scalarName;
+      VisualNormalization m_normalizationOption;
 
       mutable ThresholdRange_scptr m_thresholdRange;
     
diff --git a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoQuadFactory.h b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoQuadFactory.h
index b4643b92cba65ea94381bc684c46fd3ba2492153..59eba17ad789cc0382f21c5fac59335703f68b65 100644
--- a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoQuadFactory.h
+++ b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoQuadFactory.h
@@ -2,8 +2,10 @@
 #define MANTID_VATES_VTK_MD_HISTO_QUAD_FACTORY_H_
 
 #include "MantidKernel/System.h"
-#include "MantidVatesAPI/vtkDataSetFactory.h"
+#include "MantidVatesAPI/Normalization.h"
 #include "MantidVatesAPI/ThresholdRange.h"
+#include "MantidVatesAPI/vtkDataSetFactory.h"
+
 #include "MantidAPI/IMDWorkspace.h"
 #include "vtkUnstructuredGrid.h"
 #include "MantidDataObjects/MDHistoWorkspace.h"
@@ -44,7 +46,7 @@ however, some visualisation frameworks won't be able to treat these factories in
     public:
 
       /// Constructor
-      vtkMDHistoQuadFactory(ThresholdRange_scptr thresholdRange, const std::string& scalarName);
+      vtkMDHistoQuadFactory(ThresholdRange_scptr thresholdRange, const VisualNormalization normalizationOption);
 
       /// Assignment operator
       vtkMDHistoQuadFactory& operator=(const vtkMDHistoQuadFactory& other);
@@ -76,7 +78,7 @@ however, some visualisation frameworks won't be able to treat these factories in
     private:
       Mantid::DataObjects::MDHistoWorkspace_sptr m_workspace;
 
-      std::string m_scalarName;
+      VisualNormalization m_normalizationOption;
 
       mutable ThresholdRange_scptr m_thresholdRange;
     
diff --git a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDLineFactory.h b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDLineFactory.h
index afda318f9f223b5b6f8fe936840beccae96cca29..ace2b631230dd32e529f5b94f1cd1e117e348d92 100644
--- a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDLineFactory.h
+++ b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDLineFactory.h
@@ -1,6 +1,7 @@
 #ifndef VATES_MD_LINE_FACTORY
 #define VATES_MD_LINE_FACTORY
 
+#include "MantidVatesAPI/Normalization.h"
 #include "MantidVatesAPI/vtkDataSetFactory.h"
 #include "MantidVatesAPI/ThresholdRange.h"
 #include <boost/shared_ptr.hpp>
@@ -40,7 +41,7 @@ namespace Mantid
 
     public:
       /// Constructor
-      vtkMDLineFactory(ThresholdRange_scptr thresholdRange, const std::string& scalarName);
+      vtkMDLineFactory(ThresholdRange_scptr thresholdRange, const VisualNormalization normalizationOption);
 
       /// Destructor
       virtual ~vtkMDLineFactory();
@@ -65,7 +66,7 @@ namespace Mantid
       ThresholdRange_scptr m_thresholdRange;
 
       ///Name of the scalar.
-      std::string m_scalarName;
+      const VisualNormalization m_normalizationOption;
 
       /// Data source for the visualisation.
       Mantid::API::Workspace_sptr m_workspace;
diff --git a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDQuadFactory.h b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDQuadFactory.h
index 2e208566b54200ea23266aff3045eda34014b8bf..b7f8a428ddd8c0dabd54e14fc6a0717af52d9b82 100644
--- a/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDQuadFactory.h
+++ b/Code/Mantid/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDQuadFactory.h
@@ -1,8 +1,10 @@
 #ifndef VATES_MD_QUAD_FACTORY
 #define VATES_MD_QUAD_FACTORY
 
-#include "MantidVatesAPI/vtkDataSetFactory.h"
+#include "MantidVatesAPI/Normalization.h"
 #include "MantidVatesAPI/ThresholdRange.h"
+#include "MantidVatesAPI/vtkDataSetFactory.h"
+
 #include <boost/shared_ptr.hpp>
 
 namespace Mantid
@@ -40,7 +42,7 @@ namespace Mantid
 
     public:
       /// Constructor
-      vtkMDQuadFactory(ThresholdRange_scptr thresholdRange, const std::string& scalarName);
+      vtkMDQuadFactory(ThresholdRange_scptr thresholdRange, const VisualNormalization normalizationOption);
 
       /// Destructor
       virtual ~vtkMDQuadFactory();
@@ -65,7 +67,7 @@ namespace Mantid
       ThresholdRange_scptr m_thresholdRange;
 
       ///Name of the scalar.
-      std::string m_scalarName;
+      const VisualNormalization m_normalizationOption;
 
       /// Data source for the visualisation.
       Mantid::API::Workspace_sptr m_workspace;
diff --git a/Code/Mantid/Vates/VatesAPI/src/Normalization.cpp b/Code/Mantid/Vates/VatesAPI/src/Normalization.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..f0efbb82f01a906af9a95f5085fae3d64480c8b2
--- /dev/null
+++ b/Code/Mantid/Vates/VatesAPI/src/Normalization.cpp
@@ -0,0 +1,77 @@
+#include "MantidVatesAPI/Normalization.h"
+#include "MantidAPI/IMDNode.h"
+#include "MantidAPI/IMDEventWorkspace.h"
+#include "MantidAPI/IMDIterator.h"
+
+namespace Mantid {
+namespace VATES {
+
+/**
+Choose and return the pointer to the member function for IMDNode to perform the
+requested normalisation.
+This is used for visualisation of IMDEventWorkspaces.
+@param normalizationOption : Visual Normalization option desired
+@param ws : workspace to fetch defaults from if needed
+@return member function to use on IMDNodes
+*/
+NormFuncIMDNodePtr makeMDEventNormalizationFunction(
+    VisualNormalization normalizationOption,
+    Mantid::API::IMDEventWorkspace const *const ws) {
+
+  using namespace Mantid::API;
+
+  // Fetch the default and continue
+  if (normalizationOption == AutoSelect) {
+    // enum to enum.
+    normalizationOption =
+        static_cast<VisualNormalization>(ws->displayNormalization());
+  }
+
+  NormFuncIMDNodePtr normalizationFunction;
+
+  if (normalizationOption == Mantid::VATES::NumEventsNormalization) {
+    normalizationFunction = &IMDNode::getSignalByNEvents;
+  } else if (normalizationOption == Mantid::VATES::NoNormalization) {
+    normalizationFunction = &IMDNode::getSignal;
+  } else {
+    normalizationFunction = &IMDNode::getSignalNormalized;
+  }
+
+  return normalizationFunction;
+}
+
+/**
+Create iterators with correct normalization normalization to an IMDIterator.
+@param normalizationOption : Visual Normalization option desired
+@param ws : workspace to fetch defaults from if needed
+@return new IMDIterator
+*/
+Mantid::API::IMDIterator * createIteratorWithNormalization(
+    const VisualNormalization normalizationOption,
+    Mantid::API::IMDWorkspace const * const ws) {
+
+  using namespace Mantid::API;
+
+  MDNormalization targetNormalization;
+  // Fetch the default and continue
+  if (normalizationOption == AutoSelect) {
+    // enum to enum.
+    targetNormalization =
+      static_cast<MDNormalization>(ws->displayNormalization());
+  }
+  else {
+    targetNormalization = static_cast<MDNormalization>(normalizationOption);
+  }
+
+  // Create the iterator
+  IMDIterator * iterator = ws->createIterator();
+  // Set normalization
+  iterator->setNormalization(targetNormalization);
+  // Return it
+  return iterator;
+}
+
+
+
+}
+}
\ No newline at end of file
diff --git a/Code/Mantid/Vates/VatesAPI/src/vtkDataSetFactory.cpp b/Code/Mantid/Vates/VatesAPI/src/vtkDataSetFactory.cpp
index cdcec61b6bd528f4cbd91943618d74a3b525da5c..c85c163a027920ea6b37b74d2f22ae7aa8740983 100644
--- a/Code/Mantid/Vates/VatesAPI/src/vtkDataSetFactory.cpp
+++ b/Code/Mantid/Vates/VatesAPI/src/vtkDataSetFactory.cpp
@@ -72,5 +72,9 @@ vtkDataSet* vtkDataSetFactory::oneStepCreate(Mantid::API::Workspace_sptr ws, Pro
   return this->create(progressUpdater);
 }
 
+// What we call the scalar array bearing the signal values in the vtk data set.
+const std::string vtkDataSetFactory::ScalarName ="signal";
+
 }
+
 }
diff --git a/Code/Mantid/Vates/VatesAPI/src/vtkMD0DFactory.cpp b/Code/Mantid/Vates/VatesAPI/src/vtkMD0DFactory.cpp
index aec3c485aeef744243571fdd1e076cf5b9b8c46f..7a46febd652aa0895e3dae3d58f71608031f0eb0 100644
--- a/Code/Mantid/Vates/VatesAPI/src/vtkMD0DFactory.cpp
+++ b/Code/Mantid/Vates/VatesAPI/src/vtkMD0DFactory.cpp
@@ -17,10 +17,8 @@ namespace Mantid
   {
     /**
     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)
+    vtkMD0DFactory::vtkMD0DFactory()
     {
     }
 
diff --git a/Code/Mantid/Vates/VatesAPI/src/vtkMDHexFactory.cpp b/Code/Mantid/Vates/VatesAPI/src/vtkMDHexFactory.cpp
index bdd9b18d11005c5b482c427383c24e1e105b750d..258cf753ecd9e5a85e98a88937fcd6de90fd8b86 100644
--- a/Code/Mantid/Vates/VatesAPI/src/vtkMDHexFactory.cpp
+++ b/Code/Mantid/Vates/VatesAPI/src/vtkMDHexFactory.cpp
@@ -1,7 +1,10 @@
+#include "MantidVatesAPI/vtkMDHexFactory.h"
+
 #include "MantidAPI/IMDEventWorkspace.h"
+#include "MantidAPI/IMDNode.h"
+#include "MantidAPI/IMDWorkspace.h"
 #include "MantidKernel/CPUTimer.h"
 #include "MantidDataObjects/MDEventFactory.h"
-#include "MantidVatesAPI/vtkMDHexFactory.h"
 #include "MantidVatesAPI/Common.h"
 #include "MantidVatesAPI/ProgressAction.h"
 #include "MantidVatesAPI/vtkNullUnstructuredGrid.h"
@@ -18,297 +21,287 @@ using namespace Mantid::Geometry;
 using Mantid::Kernel::CPUTimer;
 using Mantid::Kernel::ReadLock;
 
-namespace Mantid
-{
-  namespace VATES
-  {
-
-  /*Constructor
-    @Param thresholdRange : Threshold range strategy
-    @scalarName : Name for scalar signal array.
-    */
-  vtkMDHexFactory::vtkMDHexFactory(ThresholdRange_scptr thresholdRange, const std::string& scalarName, const size_t maxDepth) :
-    m_thresholdRange(thresholdRange), m_scalarName(scalarName), m_maxDepth(maxDepth),
-    dataSet(NULL), slice(false), sliceMask(NULL), sliceImplicitFunction(NULL), m_time(0)
-  {
-  }
+namespace Mantid {
 
-  /// Destructor
-  vtkMDHexFactory::~vtkMDHexFactory()
-  {
-  }
+namespace VATES {
 
-  //-------------------------------------------------------------------------------------------------
-  /* Generate the vtkDataSet from the objects input MDEventWorkspace (of a given type an dimensionality 3+)
-  *
-  * @param ws: workspace to draw from
-  * @return a fully constructed vtkUnstructuredGrid containing geometric and scalar data.
+
+/*Constructor
+  @param thresholdRange : Threshold range strategy
+  @param normalizationOption : Info object setting how normalization should be
+  done.
+  @param maxDepth : Maximum depth to search to
   */
-  template<typename MDE, size_t nd>
-  void vtkMDHexFactory::doCreate(typename MDEventWorkspace<MDE, nd>::sptr ws) const
-  {
-    bool VERBOSE = true;
-    CPUTimer tim;
-    // Acquire a scoped read-only lock to the workspace (prevent segfault from algos modifying ws)
-    ReadLock lock(*ws);
-
-    // First we get all the boxes, up to the given depth; with or wo the slice function
-    std::vector<API::IMDNode *> boxes;
-    if (this->slice)
-      ws->getBox()->getBoxes(boxes, m_maxDepth, true, this->sliceImplicitFunction);
-    else
-      ws->getBox()->getBoxes(boxes, m_maxDepth, true);
-
-
-    vtkIdType numBoxes = boxes.size();
-    vtkIdType imageSizeActual = 0;
-
-    if (VERBOSE) std::cout << tim << " to retrieve the " << numBoxes << " boxes down to depth " << m_maxDepth << std::endl;
-
-    // Create 8 points per box.
-    vtkPoints *points = vtkPoints::New();
-    points->Allocate(numBoxes * 8);
-    points->SetNumberOfPoints(numBoxes * 8);
-
-    // One scalar per box
-    vtkFloatArray * signals = vtkFloatArray::New();
-    signals->Allocate(numBoxes);
-    signals->SetName(m_scalarName.c_str());
-    signals->SetNumberOfComponents(1);
-    //signals->SetNumberOfValues(numBoxes);
-
-    // To cache the signal
-    float * signalArray = new float[numBoxes];
-
-    // True for boxes that we will use
-    bool * useBox = new bool[numBoxes];
-    memset(useBox, 0, sizeof(bool)*numBoxes);
-
-    // Create the data set
-    vtkUnstructuredGrid * visualDataSet = vtkUnstructuredGrid::New();
-    this->dataSet = visualDataSet;
-    visualDataSet->Allocate(numBoxes);
-
-    vtkIdList * hexPointList = vtkIdList::New();
-    hexPointList->SetNumberOfIds(8);
-
-    // This can be parallelized
-    // cppcheck-suppress syntaxError
+vtkMDHexFactory::vtkMDHexFactory(ThresholdRange_scptr thresholdRange,
+                                 const VisualNormalization normalizationOption,
+                                 const size_t maxDepth)
+    : m_thresholdRange(thresholdRange),
+      m_normalizationOption(normalizationOption), m_maxDepth(maxDepth),
+      dataSet(NULL), slice(false), sliceMask(NULL), sliceImplicitFunction(NULL),
+      m_time(0) {}
+
+/// Destructor
+vtkMDHexFactory::~vtkMDHexFactory() {}
+
+//-------------------------------------------------------------------------------------------------
+/* Generate the vtkDataSet from the objects input MDEventWorkspace (of a given
+*type an dimensionality 3+)
+*
+* @param ws: workspace to draw from
+* @return a fully constructed vtkUnstructuredGrid containing geometric and
+*scalar data.
+*/
+template <typename MDE, size_t nd>
+void vtkMDHexFactory::doCreate(
+    typename MDEventWorkspace<MDE, nd>::sptr ws) const {
+  bool VERBOSE = true;
+  CPUTimer tim;
+  // Acquire a scoped read-only lock to the workspace (prevent segfault from
+  // algos modifying ws)
+  ReadLock lock(*ws);
+
+  // First we get all the boxes, up to the given depth; with or wo the slice
+  // function
+  std::vector<API::IMDNode *> boxes;
+  if (this->slice)
+    ws->getBox()->getBoxes(boxes, m_maxDepth, true,
+                           this->sliceImplicitFunction);
+  else
+    ws->getBox()->getBoxes(boxes, m_maxDepth, true);
+
+  vtkIdType numBoxes = boxes.size();
+  vtkIdType imageSizeActual = 0;
+
+  if (VERBOSE)
+    std::cout << tim << " to retrieve the " << numBoxes
+              << " boxes down to depth " << m_maxDepth << std::endl;
+
+  // Create 8 points per box.
+  vtkPoints *points = vtkPoints::New();
+  points->Allocate(numBoxes * 8);
+  points->SetNumberOfPoints(numBoxes * 8);
+
+  // One scalar per box
+  vtkFloatArray *signals = vtkFloatArray::New();
+  signals->Allocate(numBoxes);
+  signals->SetName(ScalarName.c_str());
+  signals->SetNumberOfComponents(1);
+  // signals->SetNumberOfValues(numBoxes);
+
+  // To cache the signal
+  float *signalArray = new float[numBoxes];
+
+  // True for boxes that we will use
+  bool *useBox = new bool[numBoxes];
+  memset(useBox, 0, sizeof(bool) * numBoxes);
+
+  // Create the data set
+  vtkUnstructuredGrid *visualDataSet = vtkUnstructuredGrid::New();
+  this->dataSet = visualDataSet;
+  visualDataSet->Allocate(numBoxes);
+
+  vtkIdList *hexPointList = vtkIdList::New();
+  hexPointList->SetNumberOfIds(8);
+
+  NormFuncIMDNodePtr normFunction = makeMDEventNormalizationFunction(m_normalizationOption, ws.get());
+
+  // This can be parallelized
+  // cppcheck-suppress syntaxError
     PRAGMA_OMP( parallel for schedule (dynamic) )
-      for (int ii=0; ii<int(boxes.size()); ii++)
-      {
-        // Get the box here
-        size_t i = size_t(ii);
-        API::IMDNode * box = boxes[i];
-        Mantid::signal_t signal_normalized= box->getSignalNormalized();
-
-        if (!isSpecial( signal_normalized ) && m_thresholdRange->inRange(signal_normalized))
-        {
-          // Cache the signal and using of it
-          signalArray[i] = float(signal_normalized);
-          useBox[i] = true;
-
-          //Get the coordinates.
-          size_t numVertexes = 0;
-          coord_t * coords;
-
-          // If slicing down to 3D, specify which dimensions to keep.
-          if (this->slice)
-            coords = box->getVertexesArray(numVertexes, 3, this->sliceMask);
-          else
-            coords = box->getVertexesArray(numVertexes);
-
-          if (numVertexes == 8)
-          {
-            //Iterate through all coordinates. Candidate for speed improvement.
-            for(size_t v = 0; v < numVertexes; v++)
-            {
-              coord_t * coord = coords + v*3;
-              // Set the point at that given ID
-              points->SetPoint(i*8 + v, coord[0], coord[1], coord[2]);
-              std::string msg;
-            }
-
-          } // valid number of vertexes returned
-
-          // Free memory
-          delete [] coords;
-        }
-      } // For each box
-
-      if (VERBOSE) std::cout << tim << " to create the necessary points." << std::endl;
-      //Add points
-      visualDataSet->SetPoints(points);
-
-      for (size_t i=0; i<boxes.size(); i++)
-      {
-        if (useBox[i])
-        {
-          // The bare point ID
-          vtkIdType pointIds = i * 8;
-
-          //Add signal
-          signals->InsertNextValue(signalArray[i]);
+    for (int ii = 0; ii < int(boxes.size()); ii++) {
+      // Get the box here
+      size_t i = size_t(ii);
+      API::IMDNode *box = boxes[i];
+      Mantid::signal_t signal_normalized = (box->*normFunction)(); 
+
+      if (!isSpecial(signal_normalized) &&
+          m_thresholdRange->inRange(signal_normalized)) {
+        // Cache the signal and using of it
+        signalArray[i] = float(signal_normalized);
+        useBox[i] = true;
+
+        // Get the coordinates.
+        size_t numVertexes = 0;
+        coord_t *coords;
+
+        // If slicing down to 3D, specify which dimensions to keep.
+        if (this->slice)
+          coords = box->getVertexesArray(numVertexes, 3, this->sliceMask);
+        else
+          coords = box->getVertexesArray(numVertexes);
+
+        if (numVertexes == 8) {
+          // Iterate through all coordinates. Candidate for speed improvement.
+          for (size_t v = 0; v < numVertexes; v++) {
+            coord_t *coord = coords + v * 3;
+            // Set the point at that given ID
+            points->SetPoint(i * 8 + v, coord[0], coord[1], coord[2]);
+            std::string msg;
+          }
 
-          hexPointList->SetId(0, pointIds + 0); //xyx
-          hexPointList->SetId(1, pointIds + 1); //dxyz
-          hexPointList->SetId(2, pointIds + 3); //dxdyz
-          hexPointList->SetId(3, pointIds + 2); //xdyz
-          hexPointList->SetId(4, pointIds + 4); //xydz
-          hexPointList->SetId(5, pointIds + 5); //dxydz
-          hexPointList->SetId(6, pointIds + 7); //dxdydz
-          hexPointList->SetId(7, pointIds + 6); //xdydz
+        } // valid number of vertexes returned
 
-          //Add cells
-          visualDataSet->InsertNextCell(VTK_HEXAHEDRON, hexPointList);
+        // Free memory
+        delete[] coords;
+      }
+    } // For each box
 
+    if (VERBOSE)
+      std::cout << tim << " to create the necessary points." << std::endl;
+    // Add points
+    visualDataSet->SetPoints(points);
 
-          double bounds[6];
+    for (size_t i = 0; i < boxes.size(); i++) {
+      if (useBox[i]) {
+        // The bare point ID
+        vtkIdType pointIds = i * 8;
 
-          visualDataSet->GetCellBounds(imageSizeActual, bounds);
+        // Add signal
+        signals->InsertNextValue(signalArray[i]);
 
-          if(bounds[0] < -10 || bounds[2] < -10 ||bounds[4]< -10)
-          {
-            std::string msg = "";
-          }
-          imageSizeActual++;
-        }
-      } // for each box.
+        hexPointList->SetId(0, pointIds + 0); // xyx
+        hexPointList->SetId(1, pointIds + 1); // dxyz
+        hexPointList->SetId(2, pointIds + 3); // dxdyz
+        hexPointList->SetId(3, pointIds + 2); // xdyz
+        hexPointList->SetId(4, pointIds + 4); // xydz
+        hexPointList->SetId(5, pointIds + 5); // dxydz
+        hexPointList->SetId(6, pointIds + 7); // dxdydz
+        hexPointList->SetId(7, pointIds + 6); // xdydz
 
-      delete[] signalArray;
-      delete[] useBox;
+        // Add cells
+        visualDataSet->InsertNextCell(VTK_HEXAHEDRON, hexPointList);
 
-      //Shrink to fit
-      signals->Squeeze();
-      visualDataSet->Squeeze();
+        double bounds[6];
 
-      //Add scalars
-      visualDataSet->GetCellData()->SetScalars(signals);
+        visualDataSet->GetCellBounds(imageSizeActual, bounds);
 
-      // Hedge against empty data sets
-      if (visualDataSet->GetNumberOfPoints() <= 0)
-      {
-        visualDataSet->Delete();
-        vtkNullUnstructuredGrid nullGrid;
-        visualDataSet = nullGrid.createNullData();
-        this->dataSet = visualDataSet;
+        if (bounds[0] < -10 || bounds[2] < -10 || bounds[4] < -10) {
+          std::string msg = "";
+        }
+        imageSizeActual++;
       }
+    } // for each box.
 
-      if (VERBOSE) std::cout << tim << " to create " << imageSizeActual << " hexahedrons." << std::endl;
+    delete[] signalArray;
+    delete[] useBox;
 
-  }
+    // Shrink to fit
+    signals->Squeeze();
+    visualDataSet->Squeeze();
 
+    // Add scalars
+    visualDataSet->GetCellData()->SetScalars(signals);
 
-  //-------------------------------------------------------------------------------------------------
-  /*
-  Generate the vtkDataSet from the objects input IMDEventWorkspace
-  @param progressUpdating: Reporting object to pass progress information up the stack.
-  @Return a fully constructed vtkUnstructuredGrid containing geometric and scalar data.
-  */
-  vtkDataSet* vtkMDHexFactory::create(ProgressAction& progressUpdating) const
-  {
-    this->dataSet = tryDelegatingCreation<IMDEventWorkspace, 3>(m_workspace, progressUpdating, false);
-    if(this->dataSet != NULL)
-    {
-      return this->dataSet;
+    // Hedge against empty data sets
+    if (visualDataSet->GetNumberOfPoints() <= 0) {
+      visualDataSet->Delete();
+      vtkNullUnstructuredGrid nullGrid;
+      visualDataSet = nullGrid.createNullData();
+      this->dataSet = visualDataSet;
     }
-    else
-    {
-      IMDEventWorkspace_sptr imdws = this->castAndCheck<IMDEventWorkspace, 3>(m_workspace, false);
-
-      size_t nd = imdws->getNumDims();
-      if (nd > 3)
-      {
-        // Slice from >3D down to 3D
-        this->slice = true;
-        this->sliceMask = new bool[nd];
-        this->sliceImplicitFunction = new MDImplicitFunction();
-
-        // Make the mask of dimensions
-        // TODO: Smarter mapping
-        for (size_t d=0; d<nd; d++)
-          this->sliceMask[d] = (d<3);
-
-        // Define where the slice is in 4D
-        // TODO: Where to slice? Right now is just 0
-        std::vector<coord_t> point(nd, 0);
-        point[3] = coord_t(m_time); //Specifically for 4th/time dimension.
-
-        // Define two opposing planes that point in all higher dimensions
-        std::vector<coord_t> normal1(nd, 0);
-        std::vector<coord_t> normal2(nd, 0);
-        for (size_t d=3; d<nd; d++)
-        {
-          normal1[d] = +1.0;
-          normal2[d] = -1.0;
-        }
-        // This creates a 0-thickness region to slice in.
-        sliceImplicitFunction->addPlane( MDPlane(normal1, point) );
-        sliceImplicitFunction->addPlane( MDPlane(normal2, point) );
 
-        //coord_t pointA[4] = {0, 0, 0, -1.0};
-        //coord_t pointB[4] = {0, 0, 0, +2.0};
-      }
-      else
-      {
-        // Direct 3D, so no slicing
-        this->slice = false;
-      }
-      progressUpdating.eventRaised(0.1);
-      // Macro to call the right instance of the
-      CALL_MDEVENT_FUNCTION(this->doCreate, imdws);
-      progressUpdating.eventRaised(1.0);
-
-      // Clean up
-      if (this->slice)
-      {
-        delete[] this->sliceMask;
-        delete this->sliceImplicitFunction;
-      }
+    if (VERBOSE)
+      std::cout << tim << " to create " << imageSizeActual << " hexahedrons."
+                << std::endl;
+}
 
-      // The macro does not allow return calls, so we used a member variable.
-      return this->dataSet;
+//-------------------------------------------------------------------------------------------------
+/*
+Generate the vtkDataSet from the objects input IMDEventWorkspace
+@param progressUpdating: Reporting object to pass progress information up the
+stack.
+@Return a fully constructed vtkUnstructuredGrid containing geometric and scalar
+data.
+*/
+vtkDataSet *vtkMDHexFactory::create(ProgressAction &progressUpdating) const {
+  this->dataSet = tryDelegatingCreation<IMDEventWorkspace, 3>(
+      m_workspace, progressUpdating, false);
+  if (this->dataSet != NULL) {
+    return this->dataSet;
+  } else {
+    IMDEventWorkspace_sptr imdws =
+        this->castAndCheck<IMDEventWorkspace, 3>(m_workspace, false);
+
+    size_t nd = imdws->getNumDims();
+    if (nd > 3) {
+      // Slice from >3D down to 3D
+      this->slice = true;
+      this->sliceMask = new bool[nd];
+      this->sliceImplicitFunction = new MDImplicitFunction();
+
+      // Make the mask of dimensions
+      // TODO: Smarter mapping
+      for (size_t d = 0; d < nd; d++)
+        this->sliceMask[d] = (d < 3);
+
+      // Define where the slice is in 4D
+      // TODO: Where to slice? Right now is just 0
+      std::vector<coord_t> point(nd, 0);
+      point[3] = coord_t(m_time); // Specifically for 4th/time dimension.
+
+      // Define two opposing planes that point in all higher dimensions
+      std::vector<coord_t> normal1(nd, 0);
+      std::vector<coord_t> normal2(nd, 0);
+      for (size_t d = 3; d < nd; d++) {
+        normal1[d] = +1.0;
+        normal2[d] = -1.0;
+      }
+      // This creates a 0-thickness region to slice in.
+      sliceImplicitFunction->addPlane(MDPlane(normal1, point));
+      sliceImplicitFunction->addPlane(MDPlane(normal2, point));
+
+      // coord_t pointA[4] = {0, 0, 0, -1.0};
+      // coord_t pointB[4] = {0, 0, 0, +2.0};
+    } else {
+      // Direct 3D, so no slicing
+      this->slice = false;
+    }
+    progressUpdating.eventRaised(0.1);
+    // Macro to call the right instance of the
+    CALL_MDEVENT_FUNCTION(this->doCreate, imdws);
+    progressUpdating.eventRaised(1.0);
+
+    // Clean up
+    if (this->slice) {
+      delete[] this->sliceMask;
+      delete this->sliceImplicitFunction;
     }
-  }
 
-  /*
-  Initalize the factory with the workspace. This allows top level decision on what factory to use, but allows presenter/algorithms to pass in the
-  dataobjects (workspaces) to run against at a later time. If workspace is not an IMDEventWorkspace, attempts to use any run-time successor set.
-  @Param ws : Workspace to use.
-  */
-  void vtkMDHexFactory::initialize(Mantid::API::Workspace_sptr ws)
-  {
-    IMDEventWorkspace_sptr imdws = doInitialize<IMDEventWorkspace, 3>(ws, false);
-    m_workspace = imdws;
-    
-    //Setup range values according to whatever strategy object has been injected.
-    m_thresholdRange->setWorkspace(ws);
-    m_thresholdRange->calculate();
+    // The macro does not allow return calls, so we used a member variable.
+    return this->dataSet;
   }
+}
 
-  /// Validate the current object.
-  void vtkMDHexFactory::validate() const
-  { 
-    if(!m_workspace)
-    {
-      throw std::runtime_error("Invalid vtkMDHexFactory. Workspace is null");
-    }
-  }
+/*
+Initalize the factory with the workspace. This allows top level decision on what
+factory to use, but allows presenter/algorithms to pass in the
+dataobjects (workspaces) to run against at a later time. If workspace is not an
+IMDEventWorkspace, attempts to use any run-time successor set.
+@Param ws : Workspace to use.
+*/
+void vtkMDHexFactory::initialize(Mantid::API::Workspace_sptr ws) {
+  IMDEventWorkspace_sptr imdws = doInitialize<IMDEventWorkspace, 3>(ws, false);
+  m_workspace = imdws;
+
+  // Setup range values according to whatever strategy object has been injected.
+  m_thresholdRange->setWorkspace(ws);
+  m_thresholdRange->calculate();
+}
 
-  /** Sets the recursion depth to a specified level in the workspace.
-  */
-  void vtkMDHexFactory::setRecursionDepth(size_t depth)
-  {
-    m_maxDepth = depth;
+/// Validate the current object.
+void vtkMDHexFactory::validate() const {
+  if (!m_workspace) {
+    throw std::runtime_error("Invalid vtkMDHexFactory. Workspace is null");
   }
+}
 
-  /*
-  Set the time value.
-  */
-  void vtkMDHexFactory::setTime(double time)
-  {
-    m_time = time;
-  }
+/** Sets the recursion depth to a specified level in the workspace.
+*/
+void vtkMDHexFactory::setRecursionDepth(size_t depth) { m_maxDepth = depth; }
 
-  }
+/*
+Set the time value.
+*/
+void vtkMDHexFactory::setTime(double time) { m_time = time; }
+}
 }
diff --git a/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoHex4DFactory.cpp b/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoHex4DFactory.cpp
index ddccca5282d0fb3ab3cc5a7e5398ffaedfae24cd..8a849bbe88b45b4003907f6f267497598c441d24 100644
--- a/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoHex4DFactory.cpp
+++ b/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoHex4DFactory.cpp
@@ -17,8 +17,8 @@ namespace VATES
 {
 
   template<typename TimeMapper>
-  vtkMDHistoHex4DFactory<TimeMapper>::vtkMDHistoHex4DFactory(ThresholdRange_scptr thresholdRange, const std::string& scalarName, const double timestep)
-  : vtkMDHistoHexFactory(thresholdRange,  scalarName),
+  vtkMDHistoHex4DFactory<TimeMapper>::vtkMDHistoHex4DFactory(ThresholdRange_scptr thresholdRange, const VisualNormalization normalization, const double timestep)
+  : vtkMDHistoHexFactory(thresholdRange,  normalization),
     m_timestep(timestep)
   {
   }
@@ -33,7 +33,7 @@ namespace VATES
   {
     if(this != &other)
     {
-      this->m_scalarName = other.m_scalarName;
+      this->m_normalizationOption = other.m_normalizationOption;
       this->m_thresholdRange = other.m_thresholdRange;
       this->m_workspace = other.m_workspace;
       this->m_timestep = other.m_timestep;
@@ -95,7 +95,7 @@ namespace VATES
     else
     {
       // Create the mesh in a 4D mode
-      return this->create3Dor4D(m_timeMapper(m_timestep), true, progressUpdating);
+      return this->create3Dor4D(m_timeMapper(m_timestep), progressUpdating);
     }
   }
 
diff --git a/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoHexFactory.cpp b/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoHexFactory.cpp
index 54935b90efdaaa948b0c533fe902dad3b6697f04..0c309e309875d2585e3639d8477e1058638eb243 100644
--- a/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoHexFactory.cpp
+++ b/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoHexFactory.cpp
@@ -1,10 +1,13 @@
 #include "MantidAPI/IMDWorkspace.h"
 #include "MantidKernel/CPUTimer.h"
 #include "MantidDataObjects/MDHistoWorkspace.h"
-#include "MantidVatesAPI/vtkMDHistoHexFactory.h"
+#include "MantidDataObjects/MDHistoWorkspaceIterator.h"
+
 #include "MantidVatesAPI/Common.h"
+#include "MantidVatesAPI/Normalization.h"
 #include "MantidVatesAPI/ProgressAction.h"
 #include "MantidVatesAPI/vtkNullUnstructuredGrid.h"
+#include "MantidVatesAPI/vtkMDHistoHexFactory.h"
 #include "MantidAPI/NullCoordTransform.h"
 #include "MantidKernel/ReadLock.h"
 
@@ -14,305 +17,321 @@ using Mantid::Kernel::CPUTimer;
 using namespace Mantid::DataObjects;
 using Mantid::Kernel::ReadLock;
 
-namespace Mantid
-{
-namespace VATES 
-{
-
-  vtkMDHistoHexFactory::vtkMDHistoHexFactory(ThresholdRange_scptr thresholdRange, const std::string& scalarName) :
-  m_scalarName(scalarName), m_thresholdRange(thresholdRange)
-  {
+namespace Mantid {
+namespace VATES {
+
+vtkMDHistoHexFactory::vtkMDHistoHexFactory(
+    ThresholdRange_scptr thresholdRange,
+    const VisualNormalization normalizationOption)
+    : m_normalizationOption(normalizationOption),
+      m_thresholdRange(thresholdRange) {}
+
+/**
+Assigment operator
+@param other : vtkMDHistoHexFactory to assign to this instance from.
+@return ref to assigned current instance.
+*/
+vtkMDHistoHexFactory &vtkMDHistoHexFactory::
+operator=(const vtkMDHistoHexFactory &other) {
+  if (this != &other) {
+    this->m_normalizationOption = other.m_normalizationOption;
+    this->m_thresholdRange = other.m_thresholdRange;
+    this->m_workspace = other.m_workspace;
   }
+  return *this;
+}
 
-  /**
-  Assigment operator
-  @param other : vtkMDHistoHexFactory to assign to this instance from.
-  @return ref to assigned current instance.
-  */
-  vtkMDHistoHexFactory& vtkMDHistoHexFactory::operator=(const vtkMDHistoHexFactory& other)
-  {
-    if(this != &other)
-    {
-      this->m_scalarName = other.m_scalarName;
-      this->m_thresholdRange = other.m_thresholdRange;
-      this->m_workspace = other.m_workspace;
-    }
-    return *this;
-  }
+/**
+Copy Constructor
+@param other : instance to copy from.
+*/
+vtkMDHistoHexFactory::vtkMDHistoHexFactory(const vtkMDHistoHexFactory &other) {
+  this->m_normalizationOption = other.m_normalizationOption;
+  this->m_thresholdRange = other.m_thresholdRange;
+  this->m_workspace = other.m_workspace;
+}
 
-  /**
-  Copy Constructor
-  @param other : instance to copy from.
-  */
-  vtkMDHistoHexFactory::vtkMDHistoHexFactory(const vtkMDHistoHexFactory& other)
-  {
-   this->m_scalarName = other.m_scalarName;
-   this->m_thresholdRange = other.m_thresholdRange;
-   this->m_workspace = other.m_workspace;
-  }
+void vtkMDHistoHexFactory::initialize(Mantid::API::Workspace_sptr workspace) {
+  m_workspace = doInitialize<MDHistoWorkspace, 3>(workspace);
 
-  void vtkMDHistoHexFactory::initialize(Mantid::API::Workspace_sptr workspace)
-  {
-    m_workspace = doInitialize<MDHistoWorkspace, 3>(workspace);
+  // Setup range values according to whatever strategy object has been injected.
+  m_thresholdRange->setWorkspace(workspace);
+  m_thresholdRange->calculate();
+}
 
-    //Setup range values according to whatever strategy object has been injected.
-    m_thresholdRange->setWorkspace(workspace);
-    m_thresholdRange->calculate();
-  }
+void vtkMDHistoHexFactory::validateWsNotNull() const {
 
-  void vtkMDHistoHexFactory::validateWsNotNull() const
-  {
-    
-    if(NULL == m_workspace.get())
-    {
-      throw std::runtime_error("IMDWorkspace is null");
-    }
+  if (NULL == m_workspace.get()) {
+    throw std::runtime_error("IMDWorkspace is null");
   }
+}
 
-  void vtkMDHistoHexFactory::validate() const
-  {
-    validateWsNotNull();
+void vtkMDHistoHexFactory::validate() const { validateWsNotNull(); }
+
+/** Method for creating a 3D or 4D data set
+ *
+ * @param timestep :: index of the time step (4th dimension) in the workspace.
+ *        Set to 0 for a 3D workspace.
+ * @param progressUpdate: Progress updating. passes progress information up the
+ *stack.
+ * @return the vtkDataSet created
+ */
+vtkDataSet *
+vtkMDHistoHexFactory::create3Dor4D(size_t timestep, 
+                                   ProgressAction &progressUpdate) const {
+  // Acquire a scoped read-only lock to the workspace (prevent segfault from
+  // algos modifying ws)
+  ReadLock lock(*m_workspace);
+
+  const size_t nDims = m_workspace->getNonIntegratedDimensions().size();
+
+  std::vector<size_t> indexMultiplier(nDims, 0);
+
+  // For quick indexing, accumulate these values
+  // First multiplier
+  indexMultiplier[0] = m_workspace->getDimension(0)->getNBins();
+  for (size_t d = 1; d < nDims; d++) {
+    indexMultiplier[d] =
+        indexMultiplier[d - 1] * m_workspace->getDimension(d)->getNBins();
   }
 
-
-  /** Method for creating a 3D or 4D data set
-   *
-   * @param timestep :: index of the time step (4th dimension) in the workspace.
-   *        Set to 0 for a 3D workspace.
-   * @param do4D :: if true, create a 4D dataset, else to 3D
-   * @param progressUpdate: Progress updating. passes progress information up the stack.
-   * @return the vtkDataSet created
-   */
-  vtkDataSet* vtkMDHistoHexFactory::create3Dor4D(size_t timestep, bool do4D, ProgressAction & progressUpdate) const
-  {
-    // Acquire a scoped read-only lock to the workspace (prevent segfault from algos modifying ws)
-    ReadLock lock(*m_workspace);
-
-    const int nBinsX = static_cast<int>( m_workspace->getXDimension()->getNBins() );
-    const int nBinsY = static_cast<int>( m_workspace->getYDimension()->getNBins() );
-    const int nBinsZ = static_cast<int>( m_workspace->getZDimension()->getNBins() );
-
-    const coord_t maxX = m_workspace->getXDimension()->getMaximum();
-    const coord_t minX = m_workspace->getXDimension()->getMinimum();
-    const coord_t maxY = m_workspace->getYDimension()->getMaximum();
-    const coord_t minY = m_workspace->getYDimension()->getMinimum();
-    const coord_t maxZ = m_workspace->getZDimension()->getMaximum();
-    const coord_t minZ = m_workspace->getZDimension()->getMinimum();
-
-    coord_t incrementX = (maxX - minX) / static_cast<coord_t>(nBinsX);
-    coord_t incrementY = (maxY - minY) / static_cast<coord_t>(nBinsY);
-    coord_t incrementZ = (maxZ - minZ) / static_cast<coord_t>(nBinsZ);
-
-    const int imageSize = (nBinsX ) * (nBinsY ) * (nBinsZ );
-    vtkPoints *points = vtkPoints::New();
-    points->Allocate(static_cast<int>(imageSize));
-
-    vtkFloatArray * signal = vtkFloatArray::New();
-    signal->Allocate(imageSize);
-    signal->SetName(m_scalarName.c_str());
-    signal->SetNumberOfComponents(1);
-
-    double signalScalar;
-    const int nPointsX = nBinsX+1;
-    const int nPointsY = nBinsY+1;
-    const int nPointsZ = nBinsZ+1;
-
-    CPUTimer tim;
-
-    /* The idea of the next chunk of code is that you should only
-     create the points that will be needed; so an array of pointNeeded
-     is set so that all required vertices are marked, and created in a second step. */
-
-    // Array of the points that should be created, set to false
-    bool * pointNeeded = new bool[nPointsX*nPointsY*nPointsZ];
-    memset(pointNeeded, 0, nPointsX*nPointsY*nPointsZ*sizeof(bool));
-    // Array with true where the voxel should be shown
-    bool * voxelShown = new bool[nBinsX*nBinsY*nBinsZ];
-    double progressFactor = 0.5/double(nBinsZ);
-    double progressOffset = 0.5;
-
-    size_t index = 0;
-    for (int z = 0; z < nBinsZ; z++)
-    {
-      //Report progress updates for the first 50%
-      progressUpdate.eventRaised(double(z)*progressFactor);
-      for (int y = 0; y < nBinsY; y++)
-      {
-        for (int x = 0; x < nBinsX; x++)
-        {
-          /* NOTE: It is very important to match the ordering of the two arrays
-           * (the one used in MDHistoWorkspace and voxelShown/pointNeeded).
-           * If you access the array in the wrong way and can't cache it on L1/L2 cache, I got a factor of 8x slowdown.
-           */
-          //index = x + (nBinsX * y) + (nBinsX*nBinsY*z);
-
-          if (do4D)
-            signalScalar = m_workspace->getSignalNormalizedAt(x,y,z, timestep);
-          else
-            signalScalar = m_workspace->getSignalNormalizedAt(x,y,z);
-
-          if (isSpecial( signalScalar ) || !m_thresholdRange->inRange(signalScalar))
-          {
-            // out of range
-            voxelShown[index] = false;
-          }
-          else
-          {
-            // Valid data
-            voxelShown[index] = true;
-            signal->InsertNextValue(static_cast<float>(signalScalar));
-
-            // Make sure all 8 neighboring points are set to true
-            size_t pointIndex = x + (nPointsX * y) + (nPointsX*nPointsY*z); //(Note this index is different then the other one)
-            pointNeeded[pointIndex] = true;  pointIndex++;
-            pointNeeded[pointIndex] = true;  pointIndex += nPointsX-1;
-            pointNeeded[pointIndex] = true;  pointIndex++;
-            pointNeeded[pointIndex] = true;  pointIndex += nPointsX*nPointsY - nPointsX - 1;
-            pointNeeded[pointIndex] = true;  pointIndex++;
-            pointNeeded[pointIndex] = true;  pointIndex += nPointsX-1;
-            pointNeeded[pointIndex] = true;  pointIndex++;
-            pointNeeded[pointIndex] = true;
-          }
-          index++;
+  const int nBinsX = static_cast<int>(m_workspace->getXDimension()->getNBins());
+  const int nBinsY = static_cast<int>(m_workspace->getYDimension()->getNBins());
+  const int nBinsZ = static_cast<int>(m_workspace->getZDimension()->getNBins());
+
+  const coord_t maxX = m_workspace->getXDimension()->getMaximum();
+  const coord_t minX = m_workspace->getXDimension()->getMinimum();
+  const coord_t maxY = m_workspace->getYDimension()->getMaximum();
+  const coord_t minY = m_workspace->getYDimension()->getMinimum();
+  const coord_t maxZ = m_workspace->getZDimension()->getMaximum();
+  const coord_t minZ = m_workspace->getZDimension()->getMinimum();
+
+  coord_t incrementX = (maxX - minX) / static_cast<coord_t>(nBinsX);
+  coord_t incrementY = (maxY - minY) / static_cast<coord_t>(nBinsY);
+  coord_t incrementZ = (maxZ - minZ) / static_cast<coord_t>(nBinsZ);
+
+  const int imageSize = (nBinsX) * (nBinsY) * (nBinsZ);
+  vtkPoints *points = vtkPoints::New();
+  points->Allocate(static_cast<int>(imageSize));
+
+  vtkFloatArray *signal = vtkFloatArray::New();
+  signal->Allocate(imageSize);
+  signal->SetName(vtkDataSetFactory::ScalarName.c_str());
+  signal->SetNumberOfComponents(1);
+
+  const int nPointsX = nBinsX + 1;
+  const int nPointsY = nBinsY + 1;
+  const int nPointsZ = nBinsZ + 1;
+
+  CPUTimer tim;
+
+  /* The idea of the next chunk of code is that you should only
+   create the points that will be needed; so an array of pointNeeded
+   is set so that all required vertices are marked, and created in a second
+   step. */
+
+  // Array of the points that should be created, set to false
+  bool *pointNeeded = new bool[nPointsX * nPointsY * nPointsZ];
+  memset(pointNeeded, 0, nPointsX * nPointsY * nPointsZ * sizeof(bool));
+  // Array with true where the voxel should be shown
+  bool *voxelShown = new bool[nBinsX * nBinsY * nBinsZ];
+  double progressFactor = 0.5 / double(nBinsZ);
+  double progressOffset = 0.5;
+
+  boost::scoped_ptr<MDHistoWorkspaceIterator> iterator(
+      dynamic_cast<MDHistoWorkspaceIterator *>(createIteratorWithNormalization(
+          m_normalizationOption, m_workspace.get())));
+  size_t index = 0;
+
+  for (int z = 0; z < nBinsZ; z++) {
+    // Report progress updates for the first 50%
+    progressUpdate.eventRaised(double(z) * progressFactor);
+    for (int y = 0; y < nBinsY; y++) {
+      for (int x = 0; x < nBinsX; x++) {
+        /* NOTE: It is very important to match the ordering of the two arrays
+         * (the one used in MDHistoWorkspace and voxelShown/pointNeeded).
+         * If you access the array in the wrong way and can't cache it on L1/L2
+         * cache, I got a factor of 8x slowdown.
+         */
+        // index = x + (nBinsX * y) + (nBinsX*nBinsY*z);
+
+        size_t linearIndex = 0;
+        if (nDims == 4) {
+          linearIndex = x + (indexMultiplier[0] * y) + (indexMultiplier[1] * z)
+                         + (timestep * indexMultiplier[2]);
+        } else {
+          linearIndex = x + (indexMultiplier[0] * y) + (indexMultiplier[1] * z);
         }
+        iterator->jumpTo(linearIndex);
+        const double signalScalar =
+            iterator->getNormalizedSignal(); // Normalized by the requested
+                                             // method applied above.
+
+        if (isSpecial(signalScalar) ||
+            !m_thresholdRange->inRange(signalScalar)) {
+          // out of range
+          voxelShown[index] = false;
+        } else {
+          // Valid data
+          voxelShown[index] = true;
+          signal->InsertNextValue(static_cast<float>(signalScalar));
+
+          // Make sure all 8 neighboring points are set to true
+          size_t pointIndex =
+              x + (nPointsX * y) +
+              (nPointsX * nPointsY *
+               z); //(Note this index is different then the other one)
+          pointNeeded[pointIndex] = true;
+          pointIndex++;
+          pointNeeded[pointIndex] = true;
+          pointIndex += nPointsX - 1;
+          pointNeeded[pointIndex] = true;
+          pointIndex++;
+          pointNeeded[pointIndex] = true;
+          pointIndex += nPointsX * nPointsY - nPointsX - 1;
+          pointNeeded[pointIndex] = true;
+          pointIndex++;
+          pointNeeded[pointIndex] = true;
+          pointIndex += nPointsX - 1;
+          pointNeeded[pointIndex] = true;
+          pointIndex++;
+          pointNeeded[pointIndex] = true;
+        }
+        index++;
       }
     }
+  }
 
-    std::cout << tim << " to check all the signal values." << std::endl;
-
-    // Get the transformation that takes the points in the TRANSFORMED space back into the ORIGINAL (not-rotated) space.
-    Mantid::API::CoordTransform const * transform = NULL;
-    if (m_useTransform)
-      transform = m_workspace->getTransformToOriginal();
-
-    Mantid::coord_t in[3]; 
-    Mantid::coord_t out[3];
-            
-    // Array with the point IDs (only set where needed)
-    vtkIdType * pointIDs = new vtkIdType[nPointsX*nPointsY*nPointsZ];
-    index = 0;
-    progressFactor = 0.5/static_cast<double>(nPointsZ);
-
-    for (int z = 0; z < nPointsZ; z++)
-    {
-      //Report progress updates for the last 50%
-      progressUpdate.eventRaised(double(z)*progressFactor + progressOffset);
-      in[2] = (minZ + (static_cast<coord_t>(z) * incrementZ)); //Calculate increment in z;
-      for (int y = 0; y < nPointsY; y++)
-      {
-        in[1] = (minY + (static_cast<coord_t>(y) * incrementY)); //Calculate increment in y;
-        for (int x = 0; x < nPointsX; x++)
-        {
-          // Create the point only when needed
-          if (pointNeeded[index])
-          {
-            in[0] = (minX + (static_cast<coord_t>(x) * incrementX)); //Calculate increment in x;
-            if (transform)
-            {
-              transform->apply(in, out);
-              pointIDs[index] = points->InsertNextPoint(out);
-            }
-            else
-            {
-              pointIDs[index] = points->InsertNextPoint(in);
-            }
+  std::cout << tim << " to check all the signal values." << std::endl;
+
+  // Get the transformation that takes the points in the TRANSFORMED space back
+  // into the ORIGINAL (not-rotated) space.
+  Mantid::API::CoordTransform const *transform = NULL;
+  if (m_useTransform)
+    transform = m_workspace->getTransformToOriginal();
+
+  Mantid::coord_t in[3];
+  Mantid::coord_t out[3];
+
+  // Array with the point IDs (only set where needed)
+  vtkIdType *pointIDs = new vtkIdType[nPointsX * nPointsY * nPointsZ];
+  index = 0;
+  progressFactor = 0.5 / static_cast<double>(nPointsZ);
+
+  for (int z = 0; z < nPointsZ; z++) {
+    // Report progress updates for the last 50%
+    progressUpdate.eventRaised(double(z) * progressFactor + progressOffset);
+    in[2] = (minZ + (static_cast<coord_t>(z) *
+                     incrementZ)); // Calculate increment in z;
+    for (int y = 0; y < nPointsY; y++) {
+      in[1] = (minY + (static_cast<coord_t>(y) *
+                       incrementY)); // Calculate increment in y;
+      for (int x = 0; x < nPointsX; x++) {
+        // Create the point only when needed
+        if (pointNeeded[index]) {
+          in[0] = (minX + (static_cast<coord_t>(x) *
+                           incrementX)); // Calculate increment in x;
+          if (transform) {
+            transform->apply(in, out);
+            pointIDs[index] = points->InsertNextPoint(out);
+          } else {
+            pointIDs[index] = points->InsertNextPoint(in);
           }
-          index++;
         }
+        index++;
       }
     }
+  }
 
-    std::cout << tim << " to create the needed points." << std::endl;
-
-    vtkUnstructuredGrid *visualDataSet = vtkUnstructuredGrid::New();
-    visualDataSet->Allocate(imageSize);
-    visualDataSet->SetPoints(points);
-    visualDataSet->GetCellData()->SetScalars(signal);
-
-    // ------ Hexahedron creation ----------------
-    // It is approx. 40 x faster to create the hexadron only once, and reuse it for each voxel.
-    vtkHexahedron *theHex = vtkHexahedron::New();
-    index = 0;
-    
-    for (int z = 0; z < nBinsZ; z++)
-    {
-      for (int y = 0; y < nBinsY; y++)
-      {
-        for (int x = 0; x < nBinsX; x++)
-        {
-          if (voxelShown[index])
-          {
-            //Only create topologies for those cells which are not sparse.
-            // create a hexahedron topology
-            vtkIdType id_xyz =    pointIDs[(x)   + (y)*nPointsX + z*nPointsX*nPointsY];
-            vtkIdType id_dxyz =   pointIDs[(x+1) + (y)*nPointsX + z*nPointsX*nPointsY];
-            vtkIdType id_dxdyz =  pointIDs[(x+1) + (y+1)*nPointsX + z*nPointsX*nPointsY];
-            vtkIdType id_xdyz =   pointIDs[(x)   + (y+1)*nPointsX + z*nPointsX*nPointsY];
-
-            vtkIdType id_xydz =   pointIDs[(x)   + (y)*nPointsX + (z+1)*nPointsX*nPointsY];
-            vtkIdType id_dxydz =  pointIDs[(x+1) + (y)*nPointsX + (z+1)*nPointsX*nPointsY];
-            vtkIdType id_dxdydz = pointIDs[(x+1) + (y+1)*nPointsX + (z+1)*nPointsX*nPointsY];
-            vtkIdType id_xdydz =  pointIDs[(x)   + (y+1)*nPointsX + (z+1)*nPointsX*nPointsY];
-
-            //create the hexahedron
-            theHex->GetPointIds()->SetId(0, id_xyz);
-            theHex->GetPointIds()->SetId(1, id_dxyz);
-            theHex->GetPointIds()->SetId(2, id_dxdyz);
-            theHex->GetPointIds()->SetId(3, id_xdyz);
-            theHex->GetPointIds()->SetId(4, id_xydz);
-            theHex->GetPointIds()->SetId(5, id_dxydz);
-            theHex->GetPointIds()->SetId(6, id_dxdydz);
-            theHex->GetPointIds()->SetId(7, id_xdydz);
-
-            visualDataSet->InsertNextCell(VTK_HEXAHEDRON, theHex->GetPointIds());
-          }
-          index++;
+  std::cout << tim << " to create the needed points." << std::endl;
+
+  vtkUnstructuredGrid *visualDataSet = vtkUnstructuredGrid::New();
+  visualDataSet->Allocate(imageSize);
+  visualDataSet->SetPoints(points);
+  visualDataSet->GetCellData()->SetScalars(signal);
+
+  // ------ Hexahedron creation ----------------
+  // It is approx. 40 x faster to create the hexadron only once, and reuse it
+  // for each voxel.
+  vtkHexahedron *theHex = vtkHexahedron::New();
+  index = 0;
+
+  for (int z = 0; z < nBinsZ; z++) {
+    for (int y = 0; y < nBinsY; y++) {
+      for (int x = 0; x < nBinsX; x++) {
+        if (voxelShown[index]) {
+          // Only create topologies for those cells which are not sparse.
+          // create a hexahedron topology
+          vtkIdType id_xyz =
+              pointIDs[(x) + (y)*nPointsX + z * nPointsX * nPointsY];
+          vtkIdType id_dxyz =
+              pointIDs[(x + 1) + (y)*nPointsX + z * nPointsX * nPointsY];
+          vtkIdType id_dxdyz =
+              pointIDs[(x + 1) + (y + 1) * nPointsX + z * nPointsX * nPointsY];
+          vtkIdType id_xdyz =
+              pointIDs[(x) + (y + 1) * nPointsX + z * nPointsX * nPointsY];
+
+          vtkIdType id_xydz =
+              pointIDs[(x) + (y)*nPointsX + (z + 1) * nPointsX * nPointsY];
+          vtkIdType id_dxydz =
+              pointIDs[(x + 1) + (y)*nPointsX + (z + 1) * nPointsX * nPointsY];
+          vtkIdType id_dxdydz = pointIDs[(x + 1) + (y + 1) * nPointsX +
+                                         (z + 1) * nPointsX * nPointsY];
+          vtkIdType id_xdydz = pointIDs[(x) + (y + 1) * nPointsX +
+                                        (z + 1) * nPointsX * nPointsY];
+
+          // create the hexahedron
+          theHex->GetPointIds()->SetId(0, id_xyz);
+          theHex->GetPointIds()->SetId(1, id_dxyz);
+          theHex->GetPointIds()->SetId(2, id_dxdyz);
+          theHex->GetPointIds()->SetId(3, id_xdyz);
+          theHex->GetPointIds()->SetId(4, id_xydz);
+          theHex->GetPointIds()->SetId(5, id_dxydz);
+          theHex->GetPointIds()->SetId(6, id_dxdydz);
+          theHex->GetPointIds()->SetId(7, id_xdydz);
+
+          visualDataSet->InsertNextCell(VTK_HEXAHEDRON, theHex->GetPointIds());
         }
+        index++;
       }
     }
-    theHex->Delete();
-    points->Delete();
-    signal->Delete();
-    visualDataSet->Squeeze();
-    delete [] pointIDs;
-    delete [] voxelShown;
-    delete [] pointNeeded;
-
-    // Hedge against empty data sets
-    if (visualDataSet->GetNumberOfPoints() <= 0)
-    {
-      visualDataSet->Delete();
-      vtkNullUnstructuredGrid nullGrid;
-      visualDataSet = nullGrid.createNullData();
-    }
-
-    return visualDataSet;
   }
-
-
-  /**
-  Create the vtkStructuredGrid from the provided workspace
-  @param progressUpdating: Reporting object to pass progress information up the stack.
-  @return fully constructed vtkDataSet.
-  */
-  vtkDataSet* vtkMDHistoHexFactory::create(ProgressAction& progressUpdating) const
-  {
-    vtkDataSet* product = tryDelegatingCreation<MDHistoWorkspace, 3>(m_workspace, progressUpdating);
-    if(product != NULL)
-    {
-      return product;
-    }
-    else
-    {
-      // Create in 3D mode
-      return this->create3Dor4D(0, false, progressUpdating);
-    }
+  theHex->Delete();
+  points->Delete();
+  signal->Delete();
+  visualDataSet->Squeeze();
+  delete[] pointIDs;
+  delete[] voxelShown;
+  delete[] pointNeeded;
+
+  // Hedge against empty data sets
+  if (visualDataSet->GetNumberOfPoints() <= 0) {
+    visualDataSet->Delete();
+    vtkNullUnstructuredGrid nullGrid;
+    visualDataSet = nullGrid.createNullData();
   }
 
+  return visualDataSet;
+}
 
-  vtkMDHistoHexFactory::~vtkMDHistoHexFactory()
-  {
+/**
+Create the vtkStructuredGrid from the provided workspace
+@param progressUpdating: Reporting object to pass progress information up the
+stack.
+@return fully constructed vtkDataSet.
+*/
+vtkDataSet *
+vtkMDHistoHexFactory::create(ProgressAction &progressUpdating) const {
+  vtkDataSet *product =
+      tryDelegatingCreation<MDHistoWorkspace, 3>(m_workspace, progressUpdating);
+  if (product != NULL) {
+    return product;
+  } else {
+    // Create in 3D mode
+    return this->create3Dor4D(0, progressUpdating);
   }
+}
 
+vtkMDHistoHexFactory::~vtkMDHistoHexFactory() {}
 }
 }
diff --git a/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoLineFactory.cpp b/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoLineFactory.cpp
index b7aabb2e6cae64ccf6de42477baf153537c84c21..296f744cafc12311ed586a2089c603e137e72804 100644
--- a/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoLineFactory.cpp
+++ b/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoLineFactory.cpp
@@ -29,7 +29,7 @@ namespace Mantid
   namespace VATES
   {
 
-    vtkMDHistoLineFactory::vtkMDHistoLineFactory(ThresholdRange_scptr thresholdRange, const std::string& scalarName) : m_scalarName(scalarName),
+    vtkMDHistoLineFactory::vtkMDHistoLineFactory(ThresholdRange_scptr thresholdRange, const VisualNormalization normaliztionOption) : m_normalizationOption(normaliztionOption),
       m_thresholdRange(thresholdRange)
     {
     }
@@ -43,7 +43,7 @@ namespace Mantid
     {
       if(this != &other)
       {
-        this->m_scalarName = other.m_scalarName;
+        this->m_normalizationOption = other.m_normalizationOption;
         this->m_thresholdRange = other.m_thresholdRange;
         this->m_workspace = other.m_workspace;
       }
@@ -56,7 +56,7 @@ namespace Mantid
     */
     vtkMDHistoLineFactory::vtkMDHistoLineFactory(const vtkMDHistoLineFactory& other)
     {
-      this->m_scalarName = other.m_scalarName;
+      this->m_normalizationOption = other.m_normalizationOption;
       this->m_thresholdRange = other.m_thresholdRange;
       this->m_workspace = other.m_workspace;
     }
@@ -91,7 +91,7 @@ namespace Mantid
 
         vtkFloatArray * signal = vtkFloatArray::New();
         signal->Allocate(imageSize);
-        signal->SetName(m_scalarName.c_str());
+        signal->SetName(vtkDataSetFactory::ScalarName.c_str());
         signal->SetNumberOfComponents(1);
 
         UnstructuredPoint unstructPoint;
diff --git a/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoQuadFactory.cpp b/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoQuadFactory.cpp
index 794622e51a72f7255722b59091a86bb9597b2676..748722813c5ac3a15ecafcdd812c525e03cee2c2 100644
--- a/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoQuadFactory.cpp
+++ b/Code/Mantid/Vates/VatesAPI/src/vtkMDHistoQuadFactory.cpp
@@ -1,6 +1,7 @@
 #include "MantidAPI/IMDWorkspace.h"
 #include "MantidKernel/CPUTimer.h"
 #include "MantidDataObjects/MDHistoWorkspace.h"
+#include "MantidDataObjects/MDHistoWorkspaceIterator.h"
 #include "MantidAPI/NullCoordTransform.h"
 #include "MantidVatesAPI/vtkMDHistoQuadFactory.h"
 #include "MantidVatesAPI/Common.h"
@@ -15,9 +16,11 @@
 #include "MantidKernel/ReadLock.h"
 #include "MantidKernel/Logger.h"
 
+
 using Mantid::API::IMDWorkspace;
 using Mantid::Kernel::CPUTimer;
 using Mantid::DataObjects::MDHistoWorkspace;
+using Mantid::DataObjects::MDHistoWorkspaceIterator;
 
 namespace
 {
@@ -29,7 +32,7 @@ namespace Mantid
 
   namespace VATES
   {
-    vtkMDHistoQuadFactory::vtkMDHistoQuadFactory(ThresholdRange_scptr thresholdRange, const std::string& scalarName) : m_scalarName(scalarName), m_thresholdRange(thresholdRange)
+    vtkMDHistoQuadFactory::vtkMDHistoQuadFactory(ThresholdRange_scptr thresholdRange, const VisualNormalization normalizationOption) : m_normalizationOption(normalizationOption), m_thresholdRange(thresholdRange)
     {
     }
 
@@ -42,7 +45,7 @@ namespace Mantid
     {
       if(this != &other)
       {
-        this->m_scalarName = other.m_scalarName;
+        this->m_normalizationOption = other.m_normalizationOption;
         this->m_thresholdRange = other.m_thresholdRange;
         this->m_workspace = other.m_workspace;
       }
@@ -55,7 +58,7 @@ namespace Mantid
     */
     vtkMDHistoQuadFactory::vtkMDHistoQuadFactory(const vtkMDHistoQuadFactory& other)
     {
-      this->m_scalarName = other.m_scalarName;
+      this->m_normalizationOption = other.m_normalizationOption;
       this->m_thresholdRange = other.m_thresholdRange;
       this->m_workspace = other.m_workspace;
     }
@@ -95,7 +98,7 @@ namespace Mantid
 
         vtkFloatArray * signal = vtkFloatArray::New();
         signal->Allocate(imageSize);
-        signal->SetName(m_scalarName.c_str());
+        signal->SetName(vtkDataSetFactory::ScalarName.c_str());
         signal->SetNumberOfComponents(1);
 
         //The following represent actual calculated positions.
@@ -116,7 +119,8 @@ namespace Mantid
 
         double progressFactor = 0.5/double(nBinsX);
         double progressOffset = 0.5;
-
+        boost::scoped_ptr<MDHistoWorkspaceIterator> iterator(dynamic_cast<MDHistoWorkspaceIterator*>(createIteratorWithNormalization(m_normalizationOption, m_workspace.get())));
+    
         size_t index = 0;
         for (int i = 0; i < nBinsX; i++)
         {
@@ -125,7 +129,9 @@ namespace Mantid
           for (int j = 0; j < nBinsY; j++)
           {
             index = j + nBinsY*i;
-            signalScalar = static_cast<float>(m_workspace->getSignalNormalizedAt(i, j));
+            iterator->jumpTo(index);
+            signalScalar = static_cast<float>(iterator->getNormalizedSignal()); // Get signal normalized as per m_normalizationOption
+
             if (isSpecial( signalScalar ) || !m_thresholdRange->inRange(signalScalar))
             {
               // out of range
diff --git a/Code/Mantid/Vates/VatesAPI/src/vtkMDLineFactory.cpp b/Code/Mantid/Vates/VatesAPI/src/vtkMDLineFactory.cpp
index c66e528aff082005bf273639153724f70929e13c..30b534d40d5c58c0fd95670a27f7191cd972d6a5 100644
--- a/Code/Mantid/Vates/VatesAPI/src/vtkMDLineFactory.cpp
+++ b/Code/Mantid/Vates/VatesAPI/src/vtkMDLineFactory.cpp
@@ -29,9 +29,9 @@ namespace Mantid
     /**
     Constructor
     @param thresholdRange : Thresholding range functor
-    @param scalarName : Name to give to signal
+    @param normalizationOption : Normalization option to use
     */
-    vtkMDLineFactory::vtkMDLineFactory(ThresholdRange_scptr thresholdRange, const std::string& scalarName) : m_thresholdRange(thresholdRange), m_scalarName(scalarName)
+    vtkMDLineFactory::vtkMDLineFactory(ThresholdRange_scptr thresholdRange, const VisualNormalization normalizationOption) : m_thresholdRange(thresholdRange), m_normalizationOption(normalizationOption)
     {
     }
 
@@ -74,7 +74,7 @@ namespace Mantid
         }
         
         //Ensure destruction in any event.
-        boost::scoped_ptr<IMDIterator> it(imdws->createIterator());
+        boost::scoped_ptr<IMDIterator> it(createIteratorWithNormalization(m_normalizationOption, imdws.get()));
 
         // Create 2 points per box.
         vtkPoints *points = vtkPoints::New();
@@ -83,7 +83,7 @@ namespace Mantid
         // One scalar per box
         vtkFloatArray * signals = vtkFloatArray::New();
         signals->Allocate(it->getDataSize());
-        signals->SetName(m_scalarName.c_str());
+        signals->SetName(vtkDataSetFactory::ScalarName.c_str());
         signals->SetNumberOfComponents(1);
 
         size_t nVertexes;
diff --git a/Code/Mantid/Vates/VatesAPI/src/vtkMDQuadFactory.cpp b/Code/Mantid/Vates/VatesAPI/src/vtkMDQuadFactory.cpp
index 3debbc0aeb26cdb8f36730aafd86b4d689e10d24..a9abe6422ee95c39124eec4e72d84ab2001751c9 100644
--- a/Code/Mantid/Vates/VatesAPI/src/vtkMDQuadFactory.cpp
+++ b/Code/Mantid/Vates/VatesAPI/src/vtkMDQuadFactory.cpp
@@ -27,7 +27,7 @@ namespace Mantid
   namespace VATES
   {
     /// Constructor
-    vtkMDQuadFactory::vtkMDQuadFactory(ThresholdRange_scptr thresholdRange, const std::string& scalarName) : m_thresholdRange(thresholdRange), m_scalarName(scalarName)
+    vtkMDQuadFactory::vtkMDQuadFactory(ThresholdRange_scptr thresholdRange, const VisualNormalization normalizationOption) : m_thresholdRange(thresholdRange), m_normalizationOption(normalizationOption)
     {
     }
 
@@ -69,8 +69,8 @@ namespace Mantid
           masks[i_dim] = !bIntegrated; //TRUE for unmaksed, integrated dimensions are masked.
         }
 
-        //Ensure destruction in any event.
-        boost::scoped_ptr<IMDIterator> it(imdws->createIterator());
+        //Make iterator, which will use the desired normalization. Ensure destruction in any eventuality. 
+        boost::scoped_ptr<IMDIterator> it(createIteratorWithNormalization(m_normalizationOption, imdws.get()));
 
         // Create 4 points per box.
         vtkPoints *points = vtkPoints::New();
@@ -79,7 +79,7 @@ namespace Mantid
         // One scalar per box
         vtkFloatArray * signals = vtkFloatArray::New();
         signals->Allocate(it->getDataSize());
-        signals->SetName(m_scalarName.c_str());
+        signals->SetName(vtkDataSetFactory::ScalarName.c_str());
         signals->SetNumberOfComponents(1);
 
         size_t nVertexes;
@@ -107,11 +107,11 @@ namespace Mantid
         {
           progressUpdating.eventRaised(progressFactor * double(iBox));
 
-          Mantid::signal_t signal_normalized= it->getNormalizedSignal();
-          if (!isSpecial( signal_normalized ) && m_thresholdRange->inRange(signal_normalized))
+          Mantid::signal_t signal = it->getNormalizedSignal();
+          if (!isSpecial( signal ) && m_thresholdRange->inRange(signal))
           {
             useBox[iBox] = true;
-            signals->InsertNextValue(static_cast<float>(signal_normalized));
+            signals->InsertNextValue(static_cast<float>(signal));
 
             coord_t* coords = it->getVertexesArray(nVertexes, nNonIntegrated, masks);
             delete [] coords;
diff --git a/Code/Mantid/Vates/VatesAPI/test/NormalizationTest.h b/Code/Mantid/Vates/VatesAPI/test/NormalizationTest.h
new file mode 100644
index 0000000000000000000000000000000000000000..f70981eb9ea4a0d08eadc847dc8b08a177bd4d06
--- /dev/null
+++ b/Code/Mantid/Vates/VatesAPI/test/NormalizationTest.h
@@ -0,0 +1,25 @@
+#ifndef NORMALIZATIONTEST_H_
+#define NORMALIZATIONTEST_H_
+
+#include "MantidAPI/IMDWorkspace.h"
+#include "MantidVatesAPI/Normalization.h"
+#include <cxxtest/TestSuite.h>
+
+using namespace Mantid::VATES;
+
+class NormalizationTest : public CxxTest::TestSuite {
+
+public:
+
+  void test_emum_to_enum() {
+    // Ensure that enum definitions do not change. They should remain synched.
+    TS_ASSERT_EQUALS(static_cast<int>(Mantid::API::NoNormalization),
+                     static_cast<int>(Mantid::VATES::NoNormalization));
+    TS_ASSERT_EQUALS(static_cast<int>(Mantid::API::VolumeNormalization),
+                     static_cast<int>(Mantid::VATES::VolumeNormalization));
+    TS_ASSERT_EQUALS(static_cast<int>(Mantid::API::NumEventsNormalization),
+                     static_cast<int>(Mantid::VATES::NumEventsNormalization));
+  }
+};
+
+#endif
diff --git a/Code/Mantid/Vates/VatesAPI/test/vtkDataSetFactoryTest.h b/Code/Mantid/Vates/VatesAPI/test/vtkDataSetFactoryTest.h
index 434b20176d60ff30035d7517b55b63a53324ac15..f53e677e6a94f90496dd3f09af0bc014afd7b643 100644
--- a/Code/Mantid/Vates/VatesAPI/test/vtkDataSetFactoryTest.h
+++ b/Code/Mantid/Vates/VatesAPI/test/vtkDataSetFactoryTest.h
@@ -2,6 +2,7 @@
 #ifndef VTKDATASETFACTORYTEST_H_
 #define VTKDATASETFACTORYTEST_H_
 
+#include "MantidAPI/IMDWorkspace.h"
 #include "MantidVatesAPI/vtkDataSetFactory.h"
 #include "MantidVatesAPI/ProgressAction.h"
 #include <cxxtest/TestSuite.h>
@@ -121,7 +122,6 @@ public:
     TS_ASSERT(Mock::VerifyAndClearExpectations(&factory));
   }
 
-
 };
 
 #endif
diff --git a/Code/Mantid/Vates/VatesAPI/test/vtkDataSetToScaledDataSetTest.h b/Code/Mantid/Vates/VatesAPI/test/vtkDataSetToScaledDataSetTest.h
index 76c891a84077644a7dbdd787a80b60ccbb79626e..0155f19ddbe4a9897b32242f15fc99036cc80936 100644
--- a/Code/Mantid/Vates/VatesAPI/test/vtkDataSetToScaledDataSetTest.h
+++ b/Code/Mantid/Vates/VatesAPI/test/vtkDataSetToScaledDataSetTest.h
@@ -2,6 +2,7 @@
 #define MANTID_VATESAPI_VTKDATASETTOSCALEDDATASETTEST_H_
 
 #include "MantidTestHelpers/MDEventsTestHelper.h"
+#include "MantidAPI/IMDWorkspace.h"
 #include "MantidVatesAPI/FieldDataToMetadata.h"
 #include "MantidVatesAPI/MetadataJsonManager.h"
 #include "MantidVatesAPI/MetadataToFieldData.h"
@@ -33,7 +34,7 @@ private:
                                                                      10.0,
                                                                      1);
     vtkMDHexFactory factory(ThresholdRange_scptr(new NoThresholdRange),
-                            "signal");
+                            VolumeNormalization);
     factory.initialize(ws);
     return vtkUnstructuredGrid::SafeDownCast(factory.create(progressUpdate));
   }
diff --git a/Code/Mantid/Vates/VatesAPI/test/vtkMD0DFactoryTest.h b/Code/Mantid/Vates/VatesAPI/test/vtkMD0DFactoryTest.h
index 3d8c9fd971019bb9684d68915fbc7aac5b6dc37e..4041fd870aab3edf0ffc69d5ae6c7b499fc9b7f0 100644
--- a/Code/Mantid/Vates/VatesAPI/test/vtkMD0DFactoryTest.h
+++ b/Code/Mantid/Vates/VatesAPI/test/vtkMD0DFactoryTest.h
@@ -3,22 +3,9 @@
 #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
 {
@@ -28,7 +15,7 @@ public:
   {
     // Arrange
     FakeProgressAction progressUpdater;
-    vtkMD0DFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), "signal");
+    vtkMD0DFactory factory;
 
     vtkDataSet* dataSet = NULL;
 
diff --git a/Code/Mantid/Vates/VatesAPI/test/vtkMDHexFactoryTest.h b/Code/Mantid/Vates/VatesAPI/test/vtkMDHexFactoryTest.h
index 4fa380c9d591c9ecfda89248097523c71fb03f58..8244231bc1cfb14474cb492b01334b516db70b7e 100644
--- a/Code/Mantid/Vates/VatesAPI/test/vtkMDHexFactoryTest.h
+++ b/Code/Mantid/Vates/VatesAPI/test/vtkMDHexFactoryTest.h
@@ -48,7 +48,7 @@ private:
     Workspace_sptr binned_ws = AnalysisDataService::Instance().retrieve("binned");
     FakeProgressAction progressUpdater;
 
-    vtkMDHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), "signal");
+    vtkMDHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), VATES::VolumeNormalization);
     factory.setCheckDimensionality(doCheckDimensionality);
     if(doCheckDimensionality)
     {
@@ -70,13 +70,13 @@ public:
   void testCreateWithoutInitalizeThrows()
   {
     FakeProgressAction progressUpdater;
-    vtkMDHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), "signal");
+    vtkMDHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), VATES::VolumeNormalization);
     TSM_ASSERT_THROWS("Have NOT initalized object. Should throw.", factory.create(progressUpdater), std::runtime_error);
   }
 
   void testInitalizeWithNullWorkspaceThrows()
   {
-    vtkMDHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), "signal");
+    vtkMDHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), VATES::VolumeNormalization);
 
     IMDEventWorkspace* ws = NULL;
     TSM_ASSERT_THROWS("This is a NULL workspace. Should throw.", factory.initialize( Workspace_sptr(ws) ), std::invalid_argument);
@@ -85,7 +85,7 @@ public:
 
   void testGetFactoryTypeName()
   {
-    vtkMDHexFactory factory(ThresholdRange_scptr(new NoThresholdRange), "signal");
+    vtkMDHexFactory factory(ThresholdRange_scptr(new NoThresholdRange), VATES::VolumeNormalization);
     TS_ASSERT_EQUALS("vtkMDHexFactory", factory.getFactoryTypeName());
   }
 
@@ -95,7 +95,7 @@ public:
     EXPECT_CALL(*mockSuccessor, initialize(_)).Times(1);
     EXPECT_CALL(*mockSuccessor, getFactoryTypeName()).Times(1);
 
-    vtkMDHexFactory factory(ThresholdRange_scptr(new NoThresholdRange), "signal");
+    vtkMDHexFactory factory(ThresholdRange_scptr(new NoThresholdRange), VATES::VolumeNormalization);
     factory.SetSuccessor(mockSuccessor);
 
     ITableWorkspace_sptr ws(new Mantid::DataObjects::TableWorkspace);
@@ -112,7 +112,7 @@ public:
     EXPECT_CALL(*mockSuccessor, create(Ref(progressUpdater))).Times(1).WillOnce(Return(vtkStructuredGrid::New()));
     EXPECT_CALL(*mockSuccessor, getFactoryTypeName()).Times(1);
 
-    vtkMDHexFactory factory(ThresholdRange_scptr(new NoThresholdRange), "signal");
+    vtkMDHexFactory factory(ThresholdRange_scptr(new NoThresholdRange), VATES::VolumeNormalization);
     factory.SetSuccessor(mockSuccessor);
 
     ITableWorkspace_sptr ws(new Mantid::DataObjects::TableWorkspace);
@@ -125,7 +125,7 @@ public:
   void testOnInitaliseCannotDelegateToSuccessor()
   {
     FakeProgressAction progressUpdater;
-    vtkMDHexFactory factory(ThresholdRange_scptr(new NoThresholdRange), "signal");
+    vtkMDHexFactory factory(ThresholdRange_scptr(new NoThresholdRange), VATES::VolumeNormalization);
     //factory.SetSuccessor(mockSuccessor); No Successor set.
 
     ITableWorkspace_sptr ws(new Mantid::DataObjects::TableWorkspace);
@@ -135,7 +135,7 @@ public:
   void testCreateWithoutInitializeThrows()
   {
     FakeProgressAction progressUpdater;
-    vtkMDHexFactory factory(ThresholdRange_scptr(new NoThresholdRange), "signal");
+    vtkMDHexFactory factory(ThresholdRange_scptr(new NoThresholdRange), VATES::VolumeNormalization);
     //initialize not called!
     TS_ASSERT_THROWS(factory.create(progressUpdater), std::runtime_error);
   }
@@ -156,7 +156,7 @@ public:
     FakeProgressAction progressUpdate;
 
     Mantid::DataObjects::MDEventWorkspace3Lean::sptr ws = MDEventsTestHelper::makeMDEW<3>(10, 0.0, 10.0, 1);
-    vtkMDHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), "signal");
+    vtkMDHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), VATES::VolumeNormalization);
     factory.initialize(ws);
     vtkDataSet* product = NULL;
 
@@ -190,7 +190,7 @@ public:
     EXPECT_CALL(mockProgressAction, eventRaised(_)).Times(AtLeast(1));
 
     Mantid::DataObjects::MDEventWorkspace4Lean::sptr ws = MDEventsTestHelper::makeMDEW<4>(5, -10.0, 10.0, 1);
-    vtkMDHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), "signal");
+    vtkMDHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), VATES::VolumeNormalization);
     factory.initialize(ws);
     vtkDataSet* product = NULL;
 
@@ -247,7 +247,7 @@ public :
   {
     FakeProgressAction progressUpdate;
 
-    vtkMDHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), "signal");
+    vtkMDHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), VATES::VolumeNormalization);
     factory.initialize(m_ws3);
     vtkDataSet* product = NULL;
 
@@ -283,7 +283,7 @@ public :
   {
     FakeProgressAction progressUpdate;
 
-    vtkMDHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), "signal");
+    vtkMDHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), VATES::VolumeNormalization);
     factory.initialize(m_ws4);
     vtkDataSet* product = NULL;
 
diff --git a/Code/Mantid/Vates/VatesAPI/test/vtkMDHistoHex4DFactoryTest.h b/Code/Mantid/Vates/VatesAPI/test/vtkMDHistoHex4DFactoryTest.h
index 053fe1588f654ce38574676fa09ca9a0ba645922..de2973f81cd83f38a23ec6a6a714183593b77d28 100644
--- a/Code/Mantid/Vates/VatesAPI/test/vtkMDHistoHex4DFactoryTest.h
+++ b/Code/Mantid/Vates/VatesAPI/test/vtkMDHistoHex4DFactoryTest.h
@@ -37,15 +37,15 @@ public:
 
     //Set up so that only cells with signal values == 1 should not be filtered out by thresholding.
 
-    vtkMDHistoHex4DFactory<TimeStepToTimeStep> inside(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 2)), "signal", 0);
+    vtkMDHistoHex4DFactory<TimeStepToTimeStep> inside(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 2)), Mantid::VATES::VolumeNormalization, 0);
     inside.initialize(ws_sptr);
     vtkUnstructuredGrid* insideProduct = dynamic_cast<vtkUnstructuredGrid*>(inside.create(progressAction));
 
-    vtkMDHistoHex4DFactory<TimeStepToTimeStep> below(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 0.5)),"signal", 0);
+    vtkMDHistoHex4DFactory<TimeStepToTimeStep> below(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 0.5)), Mantid::VATES::VolumeNormalization, 0);
     below.initialize(ws_sptr);
     vtkUnstructuredGrid* belowProduct = dynamic_cast<vtkUnstructuredGrid*>(below.create(progressAction));
 
-    vtkMDHistoHex4DFactory<TimeStepToTimeStep> above(ThresholdRange_scptr(new UserDefinedThresholdRange(2, 3)), "signal", 0);
+    vtkMDHistoHex4DFactory<TimeStepToTimeStep> above(ThresholdRange_scptr(new UserDefinedThresholdRange(2, 3)), Mantid::VATES::VolumeNormalization, 0);
     above.initialize(ws_sptr);
     vtkUnstructuredGrid* aboveProduct = dynamic_cast<vtkUnstructuredGrid*>(above.create(progressAction));
 
@@ -64,7 +64,7 @@ public:
     EXPECT_CALL(mockProgressAction, eventRaised(AllOf(Le(100),Ge(0)))).Times(AtLeast(1));
 
     MDHistoWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 4);
-    vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory(ThresholdRange_scptr(new NoThresholdRange), "signal", 0);
+    vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory(ThresholdRange_scptr(new NoThresholdRange), Mantid::VATES::VolumeNormalization, 0);
 
     factory.initialize(ws_sptr);
     vtkDataSet* product= factory.create(mockProgressAction);
@@ -84,13 +84,13 @@ public:
 
     //Constructional method ensures that factory is only suitable for providing mesh information.
     vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory =
-      vtkMDHistoHex4DFactory<TimeStepToTimeStep> (ThresholdRange_scptr(pRange), "signal", 0);
+      vtkMDHistoHex4DFactory<TimeStepToTimeStep> (ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization, 0);
     factory.initialize(ws_sptr);
 
     vtkDataSet* product = factory.create(progressUpdate);
     TSM_ASSERT_EQUALS("A single array should be present on the product dataset.", 1, product->GetCellData()->GetNumberOfArrays());
     vtkDataArray* signalData = product->GetCellData()->GetArray(0);
-    TSM_ASSERT_EQUALS("The obtained cell data has the wrong name.", std::string("signal"), signalData->GetName());
+    TSM_ASSERT_EQUALS("The obtained cell data has the wrong name.", std::string("signal"), std::string(signalData->GetName()));
     const int correctCellNumber = 10*10*10;
     TSM_ASSERT_EQUALS("The number of signal values generated is incorrect.", correctCellNumber, signalData->GetSize());
     
@@ -103,7 +103,7 @@ public:
     IMDWorkspace* nullWorkspace = NULL;
     Mantid::API::IMDWorkspace_sptr ws_sptr(nullWorkspace);
     UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 100);
-    vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory(ThresholdRange_scptr(pRange), "signal", 1);
+    vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory(ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization, 1);
 
     TSM_ASSERT_THROWS("No workspace, so should not be possible to complete initialization.", factory.initialize(ws_sptr), std::invalid_argument);
   }
@@ -113,7 +113,7 @@ public:
     FakeProgressAction progressAction;
 
     UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 100);
-    vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory(ThresholdRange_scptr(pRange), "signal", 1);
+    vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory(ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization, 1);
     TS_ASSERT_THROWS(factory.create(progressAction), std::runtime_error);
   }
 
@@ -131,7 +131,7 @@ public:
 
     //Constructional method ensures that factory is only suitable for providing mesh information.
     vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory =
-      vtkMDHistoHex4DFactory<TimeStepToTimeStep> (ThresholdRange_scptr(pRange), "signal", (double)0);
+      vtkMDHistoHex4DFactory<TimeStepToTimeStep> (ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization, (double)0);
 
     //Successor is provided.
     factory.SetSuccessor(pMockFactorySuccessor);
@@ -151,7 +151,7 @@ public:
 
     //Constructional method ensures that factory is only suitable for providing mesh information.
     vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory =
-      vtkMDHistoHex4DFactory<TimeStepToTimeStep> (ThresholdRange_scptr(pRange), "signal", (double)0);
+      vtkMDHistoHex4DFactory<TimeStepToTimeStep> (ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization, (double)0);
 
     TSM_ASSERT_THROWS("Should have thrown an execption given that no successor was available.", factory.initialize(ws_sptr), std::runtime_error);
   }
@@ -173,7 +173,7 @@ public:
 
     //Constructional method ensures that factory is only suitable for providing mesh information.
     vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory =
-      vtkMDHistoHex4DFactory<TimeStepToTimeStep> (ThresholdRange_scptr(pRange), "signal", (double)0);
+      vtkMDHistoHex4DFactory<TimeStepToTimeStep> (ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization, (double)0);
 
     //Successor is provided.
     factory.SetSuccessor(pMockFactorySuccessor);
@@ -191,7 +191,7 @@ public:
     UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 100);
 
     vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory =
-      vtkMDHistoHex4DFactory<TimeStepToTimeStep> (ThresholdRange_scptr(pRange), "signal", (double)0);
+      vtkMDHistoHex4DFactory<TimeStepToTimeStep> (ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization, (double)0);
     TS_ASSERT_EQUALS("vtkMDHistoHex4DFactory", factory.getFactoryTypeName());
   }
 
@@ -220,7 +220,7 @@ public:
     FakeProgressAction progressUpdate;
 
     UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 100000);
-    vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory(ThresholdRange_scptr(pRange), "signal", 0);
+    vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory(ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization, 0);
     factory.initialize(m_ws_sptr);
     TS_ASSERT_THROWS_NOTHING(factory.create(progressUpdate));
   }
diff --git a/Code/Mantid/Vates/VatesAPI/test/vtkMDHistoHexFactoryTest.h b/Code/Mantid/Vates/VatesAPI/test/vtkMDHistoHexFactoryTest.h
index 0d7c346393895ed165bdf351987ec16ca2ddaecd..06df691c089f07076e6248b876e3b77dff581860 100644
--- a/Code/Mantid/Vates/VatesAPI/test/vtkMDHistoHexFactoryTest.h
+++ b/Code/Mantid/Vates/VatesAPI/test/vtkMDHistoHexFactoryTest.h
@@ -36,15 +36,15 @@ class vtkMDHistoHexFactoryTest: public CxxTest::TestSuite
     MDHistoWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 3);
     ws_sptr->setTransformFromOriginal(new NullCoordTransform);
 
-    vtkMDHistoHexFactory inside(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 2)), "signal");
+    vtkMDHistoHexFactory inside(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 2)), Mantid::VATES::VolumeNormalization);
     inside.initialize(ws_sptr);
     vtkUnstructuredGrid* insideProduct = dynamic_cast<vtkUnstructuredGrid*>(inside.create(progressUpdate));
 
-    vtkMDHistoHexFactory below(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 0.5)), "signal");
+    vtkMDHistoHexFactory below(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 0.5)), Mantid::VATES::VolumeNormalization);
     below.initialize(ws_sptr);
     vtkUnstructuredGrid* belowProduct = dynamic_cast<vtkUnstructuredGrid*>(below.create(progressUpdate));
 
-    vtkMDHistoHexFactory above(ThresholdRange_scptr(new UserDefinedThresholdRange(2, 3)), "signal");
+    vtkMDHistoHexFactory above(ThresholdRange_scptr(new UserDefinedThresholdRange(2, 3)), Mantid::VATES::VolumeNormalization);
     above.initialize(ws_sptr);
     vtkUnstructuredGrid* aboveProduct = dynamic_cast<vtkUnstructuredGrid*>(above.create(progressUpdate));
 
@@ -65,13 +65,13 @@ class vtkMDHistoHexFactoryTest: public CxxTest::TestSuite
     ws_sptr->setTransformFromOriginal(new NullCoordTransform);
 
     //Constructional method ensures that factory is only suitable for providing mesh information.
-    vtkMDHistoHexFactory factory (ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), "signal");
+    vtkMDHistoHexFactory factory (ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), Mantid::VATES::VolumeNormalization);
     factory.initialize(ws_sptr);
 
     vtkDataSet* product = factory.create(progressUpdate);
     TSM_ASSERT_EQUALS("A single array should be present on the product dataset.", 1, product->GetCellData()->GetNumberOfArrays());
     vtkDataArray* signalData = product->GetCellData()->GetArray(0);
-    TSM_ASSERT_EQUALS("The obtained cell data has the wrong name.", std::string("signal"), signalData->GetName());
+    TSM_ASSERT_EQUALS("The obtained cell data has the wrong name.", std::string("signal"), std::string(signalData->GetName()));
     const int correctCellNumber = 10 * 10 * 10;
     TSM_ASSERT_EQUALS("The number of signal values generated is incorrect.", correctCellNumber, signalData->GetSize());
     product->Delete();
@@ -84,7 +84,7 @@ class vtkMDHistoHexFactoryTest: public CxxTest::TestSuite
     EXPECT_CALL(mockProgressAction, eventRaised(AllOf(Le(100),Ge(0)))).Times(AtLeast(1));
 
     MDHistoWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 3);
-    vtkMDHistoHexFactory factory(ThresholdRange_scptr(new NoThresholdRange), "signal");
+    vtkMDHistoHexFactory factory(ThresholdRange_scptr(new NoThresholdRange), Mantid::VATES::VolumeNormalization);
 
     factory.initialize(ws_sptr);
     vtkDataSet* product= factory.create(mockProgressAction);
@@ -98,7 +98,7 @@ class vtkMDHistoHexFactoryTest: public CxxTest::TestSuite
     IMDWorkspace* nullWorkspace = NULL;
     Mantid::API::IMDWorkspace_sptr ws_sptr(nullWorkspace);
     
-    vtkMDHistoHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), "signal");
+    vtkMDHistoHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), Mantid::VATES::VolumeNormalization);
 
     TSM_ASSERT_THROWS("No workspace, so should not be possible to complete initialization.", factory.initialize(ws_sptr), std::invalid_argument);
   }
@@ -106,7 +106,7 @@ class vtkMDHistoHexFactoryTest: public CxxTest::TestSuite
   void testCreateWithoutInitializeThrows()
   {
     FakeProgressAction progressUpdate;
-    vtkMDHistoHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), "signal");
+    vtkMDHistoHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), Mantid::VATES::VolumeNormalization);
     TS_ASSERT_THROWS(factory.create(progressUpdate), std::runtime_error);
   }
 
@@ -120,7 +120,7 @@ class vtkMDHistoHexFactoryTest: public CxxTest::TestSuite
     EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName()).WillOnce(testing::Return("TypeA")); 
 
     //Constructional method ensures that factory is only suitable for providing mesh information.
-    vtkMDHistoHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), "signal");
+    vtkMDHistoHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), Mantid::VATES::VolumeNormalization);
 
     //Successor is provided.
     factory.SetSuccessor(pMockFactorySuccessor);
@@ -136,7 +136,7 @@ class vtkMDHistoHexFactoryTest: public CxxTest::TestSuite
     Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2);
 
     //Constructional method ensures that factory is only suitable for providing mesh information.
-    vtkMDHistoHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), "signal");
+    vtkMDHistoHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), Mantid::VATES::VolumeNormalization);
 
     TSM_ASSERT_THROWS("Should have thrown an execption given that no successor was available.", factory.initialize(ws_sptr), std::runtime_error);
   }
@@ -155,7 +155,7 @@ class vtkMDHistoHexFactoryTest: public CxxTest::TestSuite
 
 
     //Constructional method ensures that factory is only suitable for providing mesh information.
-    vtkMDHistoHexFactory factory (ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), "signal");
+    vtkMDHistoHexFactory factory (ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), Mantid::VATES::VolumeNormalization);
 
     //Successor is provided.
     factory.SetSuccessor(pMockFactorySuccessor);
@@ -169,7 +169,7 @@ class vtkMDHistoHexFactoryTest: public CxxTest::TestSuite
   void testTypeName()
   {
     using namespace Mantid::VATES;
-    vtkMDHistoHexFactory factory (ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), "signal");
+    vtkMDHistoHexFactory factory (ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), Mantid::VATES::VolumeNormalization);
     TS_ASSERT_EQUALS("vtkMDHistoHexFactory", factory.getFactoryTypeName());
   }
 
@@ -198,7 +198,7 @@ public:
     FakeProgressAction progressUpdate;
 
     //Create the factory.
-    vtkMDHistoHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), "signal");
+    vtkMDHistoHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), Mantid::VATES::VolumeNormalization);
     factory.initialize(m_ws_sptr);
 
     TS_ASSERT_THROWS_NOTHING(factory.create(progressUpdate));
diff --git a/Code/Mantid/Vates/VatesAPI/test/vtkMDHistoLineFactoryTest.h b/Code/Mantid/Vates/VatesAPI/test/vtkMDHistoLineFactoryTest.h
index 0555e16fc83ba2cc1d12898b2ad2cf99480a6905..806d9a412aed3b1a6b50566993e9ed23b13c027e 100644
--- a/Code/Mantid/Vates/VatesAPI/test/vtkMDHistoLineFactoryTest.h
+++ b/Code/Mantid/Vates/VatesAPI/test/vtkMDHistoLineFactoryTest.h
@@ -33,7 +33,7 @@ public:
     IMDWorkspace* nullWorkspace = NULL;
     Mantid::API::IMDWorkspace_sptr ws_sptr(nullWorkspace);
 
-    vtkMDHistoLineFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), "signal");
+    vtkMDHistoLineFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), Mantid::VATES::VolumeNormalization);
 
     TSM_ASSERT_THROWS("No workspace, so should not be possible to complete initialization.", factory.initialize(ws_sptr), std::invalid_argument);
   }
@@ -41,7 +41,7 @@ public:
   void testCreateWithoutInitializeThrows()
   {
     FakeProgressAction progressUpdate;
-    vtkMDHistoLineFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), "signal");
+    vtkMDHistoLineFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), Mantid::VATES::VolumeNormalization);
     TS_ASSERT_THROWS(factory.create(progressUpdate), std::runtime_error);
   }
 
@@ -52,7 +52,7 @@ public:
     Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 1);
 
     //Thresholds have been set such that the signal values (hard-coded to 1, see above) will fall between the minimum 0 and maximum 2.
-    vtkMDHistoLineFactory inside(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 2)), "signal");
+    vtkMDHistoLineFactory inside(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 2)), Mantid::VATES::VolumeNormalization);
     inside.initialize(ws_sptr);
     vtkUnstructuredGrid* insideProduct = dynamic_cast<vtkUnstructuredGrid*>(inside.create(progressUpdate));
 
@@ -70,7 +70,7 @@ public:
     Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 1);
 
     //Thresholds have been set such that the signal values (hard-coded to 1, see above) will fall above and outside the minimum 0 and maximum 0.5.
-    vtkMDHistoLineFactory above(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 0.5)), "signal");
+    vtkMDHistoLineFactory above(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 0.5)), Mantid::VATES::VolumeNormalization);
     above.initialize(ws_sptr);
     vtkUnstructuredGrid* aboveProduct = dynamic_cast<vtkUnstructuredGrid*>(above.create(progressUpdate));
 
@@ -85,7 +85,7 @@ public:
     Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 1);
 
     //Thresholds have been set such that the signal values (hard-coded to 1, see above) will fall below and outside the minimum 1.5 and maximum 2.
-    vtkMDHistoLineFactory below(ThresholdRange_scptr(new UserDefinedThresholdRange(1.5, 2)), "signal");
+    vtkMDHistoLineFactory below(ThresholdRange_scptr(new UserDefinedThresholdRange(1.5, 2)), Mantid::VATES::VolumeNormalization);
     below.initialize(ws_sptr);
     vtkUnstructuredGrid* belowProduct = dynamic_cast<vtkUnstructuredGrid*>(below.create(progressUpdate));
 
@@ -100,7 +100,7 @@ public:
     EXPECT_CALL(mockProgressAction, eventRaised(AllOf(Le(100),Ge(0)))).Times(AtLeast(1));
 
     MDHistoWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 1);
-    vtkMDHistoLineFactory factory(ThresholdRange_scptr(new NoThresholdRange), "signal");
+    vtkMDHistoLineFactory factory(ThresholdRange_scptr(new NoThresholdRange), Mantid::VATES::VolumeNormalization);
 
     factory.initialize(ws_sptr);
     vtkDataSet* product= factory.create(mockProgressAction);
@@ -120,7 +120,7 @@ public:
     EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName()).WillOnce(testing::Return("TypeA")); 
 
     //Constructional method ensures that factory is only suitable for providing mesh information.
-    vtkMDHistoLineFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), "signal");
+    vtkMDHistoLineFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), Mantid::VATES::VolumeNormalization);
 
     //Successor is provided.
     factory.SetSuccessor(pMockFactorySuccessor);
@@ -136,7 +136,7 @@ public:
     Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 3);
 
     //Constructional method ensures that factory is only suitable for providing mesh information.
-    vtkMDHistoLineFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)),"signal");
+    vtkMDHistoLineFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)),Mantid::VATES::VolumeNormalization);
 
     TSM_ASSERT_THROWS("Should have thrown an execption given that no successor was available.", factory.initialize(ws_sptr), std::runtime_error);
   }
@@ -154,7 +154,7 @@ public:
     EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName()).WillOnce(testing::Return("TypeA")); 
 
     //Constructional method ensures that factory is only suitable for providing mesh information.
-    vtkMDHistoLineFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)),"signal");
+    vtkMDHistoLineFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)),Mantid::VATES::VolumeNormalization);
 
     //Successor is provided.
     factory.SetSuccessor(pMockFactorySuccessor);
@@ -167,7 +167,7 @@ public:
 
   void testTypeName()
   {
-    vtkMDHistoLineFactory factory (ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)),"signal");
+    vtkMDHistoLineFactory factory (ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)),Mantid::VATES::VolumeNormalization);
     TS_ASSERT_EQUALS("vtkMDHistoLineFactory", factory.getFactoryTypeName());
   }
 
@@ -193,7 +193,7 @@ public:
 	{
     FakeProgressAction progressUpdate;
     //Thresholds have been set such that the signal values (hard-coded to 1, see above) will fall between the minimum 0 and maximum 2.
-    vtkMDHistoLineFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 2)),"signal");
+    vtkMDHistoLineFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 2)),Mantid::VATES::VolumeNormalization);
     factory.initialize(m_ws_sptr);
     TS_ASSERT_THROWS_NOTHING(factory.create(progressUpdate));
 	}
diff --git a/Code/Mantid/Vates/VatesAPI/test/vtkMDHistoQuadFactoryTest.h b/Code/Mantid/Vates/VatesAPI/test/vtkMDHistoQuadFactoryTest.h
index 5b30bb1eff8714fca37113c187e5c98469507b41..95fb9d02c33d36dd5a1b55843c4cd7b67c5cf785 100644
--- a/Code/Mantid/Vates/VatesAPI/test/vtkMDHistoQuadFactoryTest.h
+++ b/Code/Mantid/Vates/VatesAPI/test/vtkMDHistoQuadFactoryTest.h
@@ -38,7 +38,7 @@ public:
     Mantid::API::IMDWorkspace_sptr ws_sptr(nullWorkspace);
 
     UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 100);
-    vtkMDHistoQuadFactory factory(ThresholdRange_scptr(pRange), "signal");
+    vtkMDHistoQuadFactory factory(ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization);
 
     TSM_ASSERT_THROWS("No workspace, so should not be possible to complete initialization.", factory.initialize(ws_sptr), std::invalid_argument);
   }
@@ -48,7 +48,7 @@ public:
     FakeProgressAction progressUpdate;
 
     UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 100);
-    vtkMDHistoQuadFactory factory(ThresholdRange_scptr(pRange), "signal");
+    vtkMDHistoQuadFactory factory(ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization);
     TS_ASSERT_THROWS(factory.create(progressUpdate), std::runtime_error);
   }
 
@@ -61,7 +61,7 @@ public:
 
     //Thresholds have been set such that the signal values (hard-coded to 1, see above) will fall between the minimum 0 and maximum 2.
     UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 2);
-    vtkMDHistoQuadFactory inside(ThresholdRange_scptr(pRange), "signal");
+    vtkMDHistoQuadFactory inside(ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization);
     inside.initialize(ws_sptr);
     vtkUnstructuredGrid* insideProduct = dynamic_cast<vtkUnstructuredGrid*>(inside.create(progressUpdate));
 
@@ -77,7 +77,7 @@ public:
 
     //Thresholds have been set such that the signal values (hard-coded to 1, see above) will fall above and outside the minimum 0 and maximum 0.5.
     UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 0.5);
-    vtkMDHistoQuadFactory above(ThresholdRange_scptr(pRange), "signal");
+    vtkMDHistoQuadFactory above(ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization);
     above.initialize(ws_sptr);
     vtkUnstructuredGrid* aboveProduct = dynamic_cast<vtkUnstructuredGrid*>(above.create(progressUpdate));
 
@@ -95,7 +95,7 @@ public:
 
     //Thresholds have been set such that the signal values (hard-coded to 1, see above) will fall below and outside the minimum 1.5 and maximum 2.
     UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(1.5, 2);
-    vtkMDHistoQuadFactory below(ThresholdRange_scptr(pRange), "signal");
+    vtkMDHistoQuadFactory below(ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization);
 
     below.initialize(ws_sptr);
     vtkUnstructuredGrid* belowProduct = dynamic_cast<vtkUnstructuredGrid*>(below.create(progressUpdate));
@@ -118,7 +118,7 @@ public:
 
     //Constructional method ensures that factory is only suitable for providing mesh information.
     UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 1);
-    vtkMDHistoQuadFactory factory(ThresholdRange_scptr(pRange), "signal");
+    vtkMDHistoQuadFactory factory(ThresholdRange_scptr(pRange),Mantid::VATES::VolumeNormalization);
 
     //Successor is provided.
     factory.SetSuccessor(pMockFactorySuccessor);
@@ -136,7 +136,7 @@ public:
 
     //Constructional method ensures that factory is only suitable for providing mesh information.
     UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 1);
-    vtkMDHistoQuadFactory factory(ThresholdRange_scptr(pRange), "signal");
+    vtkMDHistoQuadFactory factory(ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization);
 
     TSM_ASSERT_THROWS("Should have thrown an execption given that no successor was available.", factory.initialize(ws_sptr), std::runtime_error);
   }
@@ -155,7 +155,7 @@ public:
 
     //Constructional method ensures that factory is only suitable for providing mesh information.
     UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 1);
-    vtkMDHistoQuadFactory factory(ThresholdRange_scptr(pRange), "signal");
+    vtkMDHistoQuadFactory factory(ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization);
 
     //Successor is provided.
     factory.SetSuccessor(pMockFactorySuccessor);
@@ -170,7 +170,7 @@ public:
   void testTypeName()
   {
     UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 1);
-    vtkMDHistoQuadFactory factory(ThresholdRange_scptr(pRange), "signal");
+    vtkMDHistoQuadFactory factory(ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization);
     TS_ASSERT_EQUALS("vtkMDHistoQuadFactory", factory.getFactoryTypeName());
   }
 
@@ -181,7 +181,7 @@ public:
     EXPECT_CALL(mockProgressAction, eventRaised(AllOf(Le(100),Ge(0)))).Times(AtLeast(1));
 
     MDHistoWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2);
-    vtkMDHistoQuadFactory factory(ThresholdRange_scptr(new NoThresholdRange), "signal");
+    vtkMDHistoQuadFactory factory(ThresholdRange_scptr(new NoThresholdRange), Mantid::VATES::VolumeNormalization);
 
     factory.initialize(ws_sptr);
     vtkDataSet* product= factory.create(mockProgressAction);
@@ -214,7 +214,7 @@ public:
     FakeProgressAction progressUpdate;
     //Thresholds have been set such that the signal values (hard-coded to 1, see above) will fall between the minimum 0 and maximum 2.
     UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 1);
-    vtkMDHistoQuadFactory factory(ThresholdRange_scptr(pRange), "signal");
+    vtkMDHistoQuadFactory factory(ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization);
     factory.initialize(m_ws_sptr);
     TS_ASSERT_THROWS_NOTHING(factory.create(progressUpdate));
 	}
diff --git a/Code/Mantid/Vates/VatesAPI/test/vtkMDLineFactoryTest.h b/Code/Mantid/Vates/VatesAPI/test/vtkMDLineFactoryTest.h
index 17c3a61aca525ab73df26644bb8459c636b07670..2974c77e2c797ca6c8593fb9bd5a0c8278780c83 100644
--- a/Code/Mantid/Vates/VatesAPI/test/vtkMDLineFactoryTest.h
+++ b/Code/Mantid/Vates/VatesAPI/test/vtkMDLineFactoryTest.h
@@ -25,7 +25,7 @@ public:
 
   void testGetFactoryTypeName()
   {
-    vtkMDLineFactory factory(ThresholdRange_scptr(new NoThresholdRange), "signal");
+    vtkMDLineFactory factory(ThresholdRange_scptr(new NoThresholdRange),Mantid::VATES::VolumeNormalization);
     TS_ASSERT_EQUALS("vtkMDLineFactory", factory.getFactoryTypeName());
   }
 
@@ -35,7 +35,7 @@ public:
     EXPECT_CALL(*mockSuccessor, initialize(_)).Times(1);
     EXPECT_CALL(*mockSuccessor, getFactoryTypeName()).Times(1);
 
-    vtkMDLineFactory factory(ThresholdRange_scptr(new NoThresholdRange), "signal");
+    vtkMDLineFactory factory(ThresholdRange_scptr(new NoThresholdRange),Mantid::VATES::VolumeNormalization);
     factory.SetSuccessor(mockSuccessor);
 
     ITableWorkspace_sptr ws(new Mantid::DataObjects::TableWorkspace);
@@ -53,7 +53,7 @@ public:
     EXPECT_CALL(*mockSuccessor, create(Ref(progressUpdate))).Times(1).WillOnce(Return(vtkStructuredGrid::New()));
     EXPECT_CALL(*mockSuccessor, getFactoryTypeName()).Times(1);
 
-    vtkMDLineFactory factory(ThresholdRange_scptr(new NoThresholdRange), "signal");
+    vtkMDLineFactory factory(ThresholdRange_scptr(new NoThresholdRange),Mantid::VATES::VolumeNormalization);
     factory.SetSuccessor(mockSuccessor);
 
     ITableWorkspace_sptr ws(new Mantid::DataObjects::TableWorkspace);
@@ -65,7 +65,7 @@ public:
 
   void testOnInitaliseCannotDelegateToSuccessor()
   {
-    vtkMDLineFactory factory(ThresholdRange_scptr(new NoThresholdRange), "signal");
+    vtkMDLineFactory factory(ThresholdRange_scptr(new NoThresholdRange),Mantid::VATES::VolumeNormalization);
     //factory.SetSuccessor(mockSuccessor); No Successor set.
 
     ITableWorkspace_sptr ws(new Mantid::DataObjects::TableWorkspace);
@@ -76,7 +76,7 @@ public:
   {
     FakeProgressAction progressUpdate;
 
-    vtkMDLineFactory factory(ThresholdRange_scptr(new NoThresholdRange), "signal");
+    vtkMDLineFactory factory(ThresholdRange_scptr(new NoThresholdRange),Mantid::VATES::VolumeNormalization);
     //initialize not called!
     TS_ASSERT_THROWS(factory.create(progressUpdate), std::runtime_error);
   }
@@ -101,7 +101,7 @@ public:
 
     Workspace_sptr binned = Mantid::API::AnalysisDataService::Instance().retrieve("binned");
 
-    vtkMDLineFactory factory(ThresholdRange_scptr(new NoThresholdRange), "signal");
+    vtkMDLineFactory factory(ThresholdRange_scptr(new NoThresholdRange),Mantid::VATES::VolumeNormalization);
     factory.initialize(binned);
 
     vtkDataSet* product = factory.create(mockProgressAction);
@@ -151,7 +151,7 @@ public:
 
     Workspace_sptr binned = Mantid::API::AnalysisDataService::Instance().retrieve("binned");
 
-    vtkMDLineFactory factory(ThresholdRange_scptr(new NoThresholdRange), "signal");
+    vtkMDLineFactory factory(ThresholdRange_scptr(new NoThresholdRange),Mantid::VATES::VolumeNormalization);
     factory.initialize(binned);
 
     vtkDataSet* product = factory.create(progressAction);
diff --git a/Code/Mantid/Vates/VatesAPI/test/vtkMDQuadFactoryTest.h b/Code/Mantid/Vates/VatesAPI/test/vtkMDQuadFactoryTest.h
index 6207f3f3c8112cd9f950d03bfa3904659916b73f..75e7e93d70cde146aee182af5339efd6582e0c7c 100644
--- a/Code/Mantid/Vates/VatesAPI/test/vtkMDQuadFactoryTest.h
+++ b/Code/Mantid/Vates/VatesAPI/test/vtkMDQuadFactoryTest.h
@@ -26,7 +26,7 @@ public:
 
   void testGetFactoryTypeName()
   {
-    vtkMDQuadFactory factory(ThresholdRange_scptr(new NoThresholdRange), "signal");
+    vtkMDQuadFactory factory(ThresholdRange_scptr(new NoThresholdRange), Mantid::VATES::VolumeNormalization);
     TS_ASSERT_EQUALS("vtkMDQuadFactory", factory.getFactoryTypeName());
   }
 
@@ -36,7 +36,7 @@ public:
     EXPECT_CALL(*mockSuccessor, initialize(_)).Times(1);
     EXPECT_CALL(*mockSuccessor, getFactoryTypeName()).Times(1);
 
-    vtkMDQuadFactory factory(ThresholdRange_scptr(new NoThresholdRange), "signal");
+    vtkMDQuadFactory factory(ThresholdRange_scptr(new NoThresholdRange), Mantid::VATES::VolumeNormalization);
     factory.SetSuccessor(mockSuccessor);
 
     ITableWorkspace_sptr ws(new Mantid::DataObjects::TableWorkspace);
@@ -54,7 +54,7 @@ public:
     EXPECT_CALL(*mockSuccessor, create(Ref(progressUpdate))).Times(1).WillOnce(Return(vtkStructuredGrid::New()));
     EXPECT_CALL(*mockSuccessor, getFactoryTypeName()).Times(1);
 
-    vtkMDQuadFactory factory(ThresholdRange_scptr(new NoThresholdRange), "signal");
+    vtkMDQuadFactory factory(ThresholdRange_scptr(new NoThresholdRange), Mantid::VATES::VolumeNormalization);
     factory.SetSuccessor(mockSuccessor);
 
     ITableWorkspace_sptr ws(new Mantid::DataObjects::TableWorkspace);
@@ -66,7 +66,7 @@ public:
 
   void testOnInitaliseCannotDelegateToSuccessor()
   {
-    vtkMDQuadFactory factory(ThresholdRange_scptr(new NoThresholdRange), "signal");
+    vtkMDQuadFactory factory(ThresholdRange_scptr(new NoThresholdRange), Mantid::VATES::VolumeNormalization);
     //factory.SetSuccessor(mockSuccessor); No Successor set.
 
     ITableWorkspace_sptr ws(new Mantid::DataObjects::TableWorkspace);
@@ -77,7 +77,7 @@ public:
   {
     FakeProgressAction progressUpdate;
 
-    vtkMDQuadFactory factory(ThresholdRange_scptr(new NoThresholdRange), "signal");
+    vtkMDQuadFactory factory(ThresholdRange_scptr(new NoThresholdRange), Mantid::VATES::VolumeNormalization);
     //initialize not called!
     TS_ASSERT_THROWS(factory.create(progressUpdate), std::runtime_error);
   }
@@ -103,7 +103,7 @@ public:
 
     Workspace_sptr binned = Mantid::API::AnalysisDataService::Instance().retrieve("binned");
 
-    vtkMDQuadFactory factory(ThresholdRange_scptr(new NoThresholdRange), "signal");
+    vtkMDQuadFactory factory(ThresholdRange_scptr(new NoThresholdRange), Mantid::VATES::VolumeNormalization);
     factory.initialize(binned);
 
     vtkDataSet* product = factory.create(mockProgressAction);
@@ -153,7 +153,7 @@ public:
     FakeProgressAction progressUpdate;
     Workspace_sptr binned = Mantid::API::AnalysisDataService::Instance().retrieve("binned");
 
-    vtkMDQuadFactory factory(ThresholdRange_scptr(new NoThresholdRange), "signal");
+    vtkMDQuadFactory factory(ThresholdRange_scptr(new NoThresholdRange), Mantid::VATES::VolumeNormalization);
     factory.initialize(binned);
 
     vtkDataSet* product = factory.create(progressUpdate);
diff --git a/Code/Mantid/docs/source/algorithms/EnginXFitPeaks-v1.rst b/Code/Mantid/docs/source/algorithms/EnginXFitPeaks-v1.rst
index 270401faa1e58b9226ac9a9de7dbd9a0f4308382..524b90cbbfde0d4ec0cc1b769afab5071c1742f4 100644
--- a/Code/Mantid/docs/source/algorithms/EnginXFitPeaks-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/EnginXFitPeaks-v1.rst
@@ -11,7 +11,7 @@ Description
 
 .. warning::
 
-   This algorithm is being developed for a specific instrument. It might get changed or even 
+   This algorithm is being developed for a specific instrument. It might get changed or even
    removed without a notification, should instrument scientists decide to do so.
 
 
@@ -50,20 +50,20 @@ Usage
 
    # Run the algorithm. Defaults are shown below. Files entered must be in .csv format and if both ExpectedPeaks and ExpectedPeaksFromFile are entered, the latter will be used.
    # difc, zero = EnginXFitPeaks(InputWorkspace = No default, WorkspaceIndex = None, ExpectedPeaks=[0.6, 1.9], ExpectedPeaksFromFile=None)
-   
-   difc, zero = EnginXFitPeaks(ws, 0, [0.6, 1.9])
-   
-   
+
+   difc, zero = EnginXFitPeaks(ws, 0, [0.65, 1.9])
+
+
 
    # Print the results
-   print "Difc:", difc
-   print "Zero:", zero
+   print "Difc: %.1f" % difc
+   print "Zero: %.1f" % zero
 
 Output:
 
 .. testoutput:: ExTwoPeaks
 
-   Difc: 49019.4561189
-   Zero: -58131.0062365
+   Difc: 18400.0
+   Zero: 46.0
 
 .. categories::
diff --git a/Code/Mantid/docs/source/algorithms/EnginXFocus-v1.rst b/Code/Mantid/docs/source/algorithms/EnginXFocus-v1.rst
index 13f2faac63a349b5463fc51143885f71937d245f..28cb93a3cbcf6122ca6ef1e691306edaeeaf182e 100644
--- a/Code/Mantid/docs/source/algorithms/EnginXFocus-v1.rst
+++ b/Code/Mantid/docs/source/algorithms/EnginXFocus-v1.rst
@@ -14,8 +14,10 @@ Description
    This algorithm is being developed for a specific instrument. It might get changed or even 
    removed without a notification, should instrument scientists decide to do so.
 
-Performs a TOF to dSpacing conversion using calibrated pixel positions, focuses the values in dSpacing
-and then converts them back to TOF.
+Performs a TOF to dSpacing conversion using calibrated pixel
+positions, focuses the values in dSpacing and then converts them back
+to TOF. The output workspace produced by this algorithm has one
+spectrum.
 
 Usage
 -----
diff --git a/Code/Mantid/docs/source/concepts/InstrumentDefinitionFile.rst b/Code/Mantid/docs/source/concepts/InstrumentDefinitionFile.rst
index ee404baee5d47be44bdaaecff9d1d310f4107b76..1b991a2258435ea048e366b4603d7b1342d33551 100644
--- a/Code/Mantid/docs/source/concepts/InstrumentDefinitionFile.rst
+++ b/Code/Mantid/docs/source/concepts/InstrumentDefinitionFile.rst
@@ -172,10 +172,9 @@ which must be included. An example is
                   xsi:schemaLocation="http://www.mantidproject.org/IDF/1.0 http://schema.mantidproject.org/IDF/1.0/IDFSchema.xsd"
                   name="ARCS"
                   valid-from="1900-01-31 23:59:59"
-                  valid-to="2100-01-31 23:59:59"
-                  last-modified="2010-10-12 08:54:07.279621">
+                  valid-to="2100-01-31 23:59:59">
 
-Of the four attributes in the example above
+Of the attributes in the example above
 
 -  xmlns, xmlns:xsi, xsi:schemaLocation are required attributes that can
    be copied verbatim as above
@@ -186,9 +185,6 @@ Of the four attributes in the example above
    23:59:01
 -  valid-to may optionally be added to indicate the date to which the
    IDF is valid to. If not used, the file is permanently valid. (+)
--  last-modified is optional. Changing it can be used as an alternative
-   to force MantidPlot to reload the IDF, which e.g. might be useful
-   during the build up of an IDF
 
 (+) 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
diff --git a/Code/Mantid/docs/source/concepts/PointAndSpaceGroups.rst b/Code/Mantid/docs/source/concepts/PointAndSpaceGroups.rst
index f879d1e12310122c055e4c1d1038aa92ea9d9658..57a52cd3acf978d68f265af15859613f64439771 100644
--- a/Code/Mantid/docs/source/concepts/PointAndSpaceGroups.rst
+++ b/Code/Mantid/docs/source/concepts/PointAndSpaceGroups.rst
@@ -307,7 +307,7 @@ Which produces the following output:
 
     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
@@ -364,6 +364,58 @@ This prints the following information:
     [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.
+
+With the space group information it's also possible to derive information about site symmetry at specific coordinates and construct the site symmetry group, which is the sub-group of the point group that contains the symmetry operations of the space group that leave the point unchanged. In the following script, the site symmetry group of the :math:`6h` position (coordinates :math:`x, 2x, 1/4`) in space group :math:`P6_3/mmc` (no. 194) is determined:
+
+.. testcode:: ExSiteSymmetryGroup
+
+    from mantid.kernel import V3D
+    from mantid.geometry import SpaceGroupFactory, Group
+    import numpy as np
+
+    # Function that transforms coordinates to the interval [0, 1)
+    def getWrappedCoordinates(coordinates):
+        tmp = coordinates + V3D(1, 1, 1)
+        return V3D(np.fmod(tmp.X(), 1.0), np.fmod(tmp.Y(), 1.0), np.fmod(tmp.Z(), 1.0))
+
+    # Function that construct the site symmetry group
+    def getSiteSymmetryGroup(spaceGroup, point):
+        symOps = spaceGroup.getSymmetryOperations()
+
+        ops = []
+        for op in symOps:
+            transformed = getWrappedCoordinates(op.transformCoordinates(point))
+
+            # If the transformed coordinate is equivalent to the original, add it to the group
+            if transformed == point:
+                ops.append(op)
+
+        # Return group with symmetry operations that leave point unchanged
+        return Group(ops)
+
+    # Construct space group object
+    sg = SpaceGroupFactory.createSpaceGroup("P 63/m m c")
+
+    # Point on 6h-position, [x, 2x, 1/4]
+    point = V3D(0.31, 0.62, 0.25)
+
+    siteSymmGroup = getSiteSymmetryGroup(sg, point)
+
+    print "Site symmetry group fulfills group axioms:", siteSymmGroup.isGroup()
+    print "Order of site symmetry group:", siteSymmGroup.getOrder()
+    print "Order of space group:", sg.getOrder()
+    print "Site multiplicity:", sg.getOrder() / siteSymmGroup.getOrder()
+
+The script produces the following output:
+
+.. testoutput:: ExSiteSymmetryGroup
+
+    Site symmetry group fulfills group axioms: True
+    Order of site symmetry group: 4
+    Order of space group: 24
+    Site multiplicity: 6
+
+There are four symmmetry operations that leave the coordinates :math:`x,2x,1/4` unchanged, they fulfill the group axioms. Dividing the order of the space group by the order of the site symmetry group gives the correct site multiplicity 6. 
     
 .. [ITAPointGroups] International Tables for Crystallography (2006). Vol. A, ch. 10.1, p. 762
 
diff --git a/Code/Mantid/docs/source/concepts/SymmetryGroups.rst b/Code/Mantid/docs/source/concepts/SymmetryGroups.rst
index 07a8d428143694b2bbb6c4f13a608eea6cabd929..538ebd222bde86a386d16ef011ef2526e414d534 100644
--- a/Code/Mantid/docs/source/concepts/SymmetryGroups.rst
+++ b/Code/Mantid/docs/source/concepts/SymmetryGroups.rst
@@ -255,8 +255,74 @@ As more operations are added to a group, it can be useful to display the group i
       - :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).
+
+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). Groups are available through the Python interface of Mantid. The following code generates the group in the table above (with the y-axis being characteristic for rotation and mirror symmetry) and checks whether this set of symmetry operations is indeed a Group:
+
+.. testcode:: ExSymmetryGroup
+
+    from mantid.geometry import Group
+
+    group = Group("x,y,z; -x,-y,-z; -x,y,-z; x,-y,z")
+
+    print "Order of group:", group.getOrder()
+    print "Fulfills group axioms:", group.isGroup()
+
+This code confirms what was demonstrated by the group table above, the specified set of symmetry operations fulfills the group axioms:
+
+.. testoutput:: ExSymmetryGroup
+
+    Order of group: 4
+    Fulfills group axioms: True
+
+For more fine-grained information, the four axioms can also be checked separately. Please note that the associativity axiom is always fulfilled due to the way the binary operation for symmetry operations is defined, it's included for completeness reasons. In the next example, the inversion operation is removed and the four axioms are checked:
+
+.. testcode:: ExSymmetryGroupAxioms
+
+    from mantid.geometry import Group, GroupAxiom
+
+    group = Group("x,y,z; -x,y,-z; x,-y,z")
+
+    print "Group axioms fulfilled:"
+    print "  1. Closure:", group.fulfillsAxiom(GroupAxiom.Closure)
+    print "  2. Associativity:", group.fulfillsAxiom(GroupAxiom.Associativity)
+    print "  3. Identity:", group.fulfillsAxiom(GroupAxiom.Identity)
+    print "  4. Inversion:", group.fulfillsAxiom(GroupAxiom.Inversion)
+
+The code reveals that axioms 2 - 4 are fulfilled, but that the group is not closed:
+
+.. testoutput:: ExSymmetryGroupAxioms
+
+    Group axioms fulfilled:
+      1. Closure: False
+      2. Associativity: True
+      3. Identity: True
+      4. Inversion: True
+
+Looking into the group table above shows the reason: The combination of a mirror plane and a two-fold rotation axis implies the the presence of an inversion center. Similarly, the identity can be removed:
+
+.. testcode:: ExSymmetryGroupAxiomsIdentity
+
+    from mantid.geometry import Group, GroupAxiom
+
+    group = Group("-x,-y,-z; -x,y,-z; x,-y,z")
+
+    print "Group axioms fulfilled:"
+    print "  1. Closure:", group.fulfillsAxiom(GroupAxiom.Closure)
+    print "  2. Associativity:", group.fulfillsAxiom(GroupAxiom.Associativity)
+    print "  3. Identity:", group.fulfillsAxiom(GroupAxiom.Identity)
+    print "  4. Inversion:", group.fulfillsAxiom(GroupAxiom.Inversion)
+
+In contrast to removing the inversion, the group now also lacks an identity element:
+
+.. testoutput:: ExSymmetryGroupAxiomsIdentity
+
+    Group axioms fulfilled:
+      1. Closure: False
+      2. Associativity: True
+      3. Identity: False
+      4. Inversion: True
+
+Using these specific checks can be helpful for finding out why a certain set of symmetry operations is not a group.
 
 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`.
 
diff --git a/Code/Mantid/docs/source/interfaces/Indirect_DataAnalysis.rst b/Code/Mantid/docs/source/interfaces/Indirect_DataAnalysis.rst
index 0843e4d911962523b6a69969f5586d48a64b42b8..a648dca3657c10843b861de8eb8871cb2ef0de41 100644
--- a/Code/Mantid/docs/source/interfaces/Indirect_DataAnalysis.rst
+++ b/Code/Mantid/docs/source/interfaces/Indirect_DataAnalysis.rst
@@ -37,6 +37,18 @@ Manage Directories
   Opens the Manage Directories dialog allowing you to change your search directories
   and default save directory and enable/disable data archive search.
 
+Bayesian
+--------
+
+There is the option to perform Bayesian data analysis on the I(Q, t) Fit ConvFit
+tabs on this interface by using the :ref:`FABADA` fitting minimizer, however in
+order to to use this you will need to use better starting parameters than the
+defaults provided by the interface.
+
+You may also experience issues where the starting parameters may give a reliable
+fit on one spectra but not others, in this case the best option is to reduce
+the number of spectra that are fitted in one operation.
+
 Elwin
 -----
 
@@ -78,6 +90,11 @@ SE log name
   The name of the sample environment log entry in the input files sample logs
   (defaults to sample).
 
+SE log value
+  The value to be taken from the "SE log name" data series (defaults to the
+  specified value in the intrument parameters file, and in the absence of such
+  specification, defaults to "last value")
+
 Plot Result
   If enabled will plot the result as a spectra plot.
 
@@ -230,10 +247,25 @@ Plot Guess
   When checked a curve will be created on the plot window based on the bitting
   parameters.
 
+Max Iterations
+  The maximum number of iterations that can be carried out by the fitting
+  algorithm (automatically increased when FABADA is enabled).
+
 StartX & EndX
   The range of :math:`x` over which the fitting will be applied (blue lines on
   preview plot).
 
+Use FABADA
+  Select to enable use of the :ref:`FABADA` minimizer when performing the fit.
+
+Output Chain
+  Select to enable output of the FABADA chain when using FABADA as the fitting
+  minimizer.
+
+Chain Length
+  Number of further steps carried out by fitting algorithm once parameters have
+  converged (see :ref:`FABADA` documentation)
+
 Linear Background A0
   The constant amplitude of the background (horizontal green line on the preview
   plot).
@@ -350,10 +382,25 @@ Plot Guess
   When checked a curve will be created on the plot window based on the bitting
   parameters.
 
+Max Iterations
+  The maximum number of iterations that can be carried out by the fitting
+  algorithm (automatically increased when FABADA is enabled).
+
 StartX & EndX
   The range of :math:`x` over which the fitting will be applied (blue lines on
   preview plot).
 
+Use FABADA
+  Select to enable use of the :ref:`FABADA` minimizer when performing the fit.
+
+Output Chain
+  Select to enable output of the FABADA chain when using FABADA as the fitting
+  minimizer.
+
+Chain Length
+  Number of further steps carried out by fitting algorithm once parameters have
+  converged (see :ref:`FABADA` documentation)
+
 A0 & A1 (background)
   The A0 and A1 parameters as they appear in the LinearBackground fir function,
   depending on the Fit Type selected A1 may not be shown.
diff --git a/Code/Mantid/instrument/BASIS_Parameters.xml b/Code/Mantid/instrument/BASIS_Parameters.xml
index 66590b11be07a5f735ad05c69ff6aa7bdb50fe11..dbbded1231a399384db67ed369e41e717731365b 100644
--- a/Code/Mantid/instrument/BASIS_Parameters.xml
+++ b/Code/Mantid/instrument/BASIS_Parameters.xml
@@ -65,7 +65,10 @@
     <value val="AnalyserReflection" />
 </parameter>
 <parameter name="Workflow.SE-log" type="string">
-    <value val="SetpointLP1" />
+    <value val="SensorA" />
+</parameter>
+<parameter name="Workflow.SE-log-value" type="string">
+    <value val="average" />
 </parameter>
 
 </component-link>
diff --git a/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py b/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py
index c8f8360318aa44449c007805ee73a2870709c26d..63718163ff3c806a3381b53b76c9968954a252a4 100644
--- a/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py
+++ b/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py
@@ -49,7 +49,10 @@ def calculateEISF(params_table):
             mtd[params_table].setCell(error_col_name, i, error)
 
 
-def confitSeq(inputWS, func, startX, endX, ftype, bgd, temperature=None, specMin=0, specMax=None, convolve=True, Plot='None', Save=False):
+def confitSeq(inputWS, func, startX, endX, ftype, bgd,
+              temperature=None, specMin=0, specMax=None, convolve=True,
+              minimizer='Levenberg-Marquardt', max_iterations=500,
+              Plot='None', Save=False):
     StartTime('ConvFit')
 
     bgd = bgd[:-2]
@@ -82,10 +85,16 @@ def confitSeq(inputWS, func, startX, endX, ftype, bgd, temperature=None, specMin
         fit_args['PassWSIndexToFunction'] = True
 
     PlotPeakByLogValue(Input=';'.join(input_params),
-                       OutputWorkspace=output_workspace, Function=func,
-                       StartX=startX, EndX=endX, FitType='Sequential',
-                       CreateOutput=True, OutputCompositeMembers=True,
+                       OutputWorkspace=output_workspace,
+                       Function=func,
+                       StartX=startX,
+                       EndX=endX,
+                       FitType='Sequential',
+                       CreateOutput=True,
+                       OutputCompositeMembers=True,
                        ConvolveMembers=convolve,
+                       MaxIterations=max_iterations,
+                       Minimizer=minimizer,
                        **fit_args)
 
     DeleteWorkspace(output_workspace + '_NormalisedCovarianceMatrices')
@@ -159,7 +168,11 @@ def confitSeq(inputWS, func, startX, endX, ftype, bgd, temperature=None, specMin
 # FuryFit
 ##############################################################################
 
-def furyfitSeq(inputWS, func, ftype, startx, endx, spec_min=0, spec_max=None, intensities_constrained=False, Save=False, Plot='None'):
+def furyfitSeq(inputWS, func, ftype, startx, endx,
+               spec_min=0, spec_max=None,
+               intensities_constrained=False,
+               minimizer='Levenberg-Marquardt', max_iterations=500,
+               Save=False, Plot='None'):
     StartTime('FuryFit')
 
     fit_type = ftype[:-2]
@@ -183,8 +196,15 @@ def furyfitSeq(inputWS, func, ftype, startx, endx, spec_min=0, spec_max=None, in
     input_str = [tmp_fit_workspace + ',i%d' % i for i in range(spec_min, spec_max + 1)]
     input_str = ';'.join(input_str)
 
-    PlotPeakByLogValue(Input=input_str, OutputWorkspace=output_workspace, Function=func,
-                       StartX=startx, EndX=endx, FitType='Sequential', CreateOutput=True)
+    PlotPeakByLogValue(Input=input_str,
+                       OutputWorkspace=output_workspace,
+                       Function=func,
+                       Minimizer=minimizer,
+                       MaxIterations=max_iterations,
+                       StartX=startx,
+                       EndX=endx,
+                       FitType='Sequential',
+                       CreateOutput=True)
 
     # Remove unsused workspaces
     DeleteWorkspace(output_workspace + '_NormalisedCovarianceMatrices')
@@ -231,7 +251,10 @@ def furyfitSeq(inputWS, func, ftype, startx, endx, spec_min=0, spec_max=None, in
     return result_workspace
 
 
-def furyfitMult(inputWS, function, ftype, startx, endx, spec_min=0, spec_max=None, intensities_constrained=False, Save=False, Plot='None'):
+def furyfitMult(inputWS, function, ftype, startx, endx,
+                spec_min=0, spec_max=None, intensities_constrained=False,
+                minimizer='Levenberg-Marquardt', max_iterations=500,
+                Save=False, Plot='None'):
     StartTime('FuryFit Multi')
 
     nHist = mtd[inputWS].getNumberHistograms()
@@ -257,8 +280,14 @@ def furyfitMult(inputWS, function, ftype, startx, endx, spec_min=0, spec_max=Non
 
     #fit multi-domian functino to workspace
     multi_domain_func, kwargs = createFuryMultiDomainFunction(function, tmp_fit_workspace)
-    Fit(Function=multi_domain_func, InputWorkspace=tmp_fit_workspace, WorkspaceIndex=0,
-        Output=output_workspace, CreateOutput=True, **kwargs)
+    Fit(Function=multi_domain_func,
+        InputWorkspace=tmp_fit_workspace,
+        WorkspaceIndex=0,
+        Output=output_workspace,
+        CreateOutput=True,
+        Minimizer=minimizer,
+        MaxIterations=max_iterations,
+        **kwargs)
 
     params_table = output_workspace + '_Parameters'
     transposeFitParametersTable(params_table)